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 |
|---|---|---|---|---|---|---|
hamadmarri/Biscuit | main/java/com/biscuit/commands/userStory/ListUserStories.java | // Path: main/java/com/biscuit/ColorCodes.java
// public class ColorCodes {
//
// // with normal background
// public static final String RESET = "\u001B[0m";
// public static final String BLACK = "\u001B[30;1m";
// public static final String RED = "\u001B[31;1m";
// public static final String GREEN = "\u001B[32;1m";
// public static final String YELLOW = "\u001B[33;1m";
// public static final String BLUE = "\u001B[34;1m";
// public static final String PURPLE = "\u001B[35;1m";
// public static final String CYAN = "\u001B[36;1m";
// public static final String WHITE = "\u001B[37;1m";
//
// // with black background
// public static final String B_RESET = "\u001B[0m";
// public static final String B_BLACK = "\u001B[30;40;1m";
// public static final String B_RED = "\u001B[31;40;1m";
// public static final String B_GREEN = "\u001B[32;40;1m";
// public static final String B_YELLOW = "\u001B[33;40;1m";
// public static final String B_BLUE = "\u001B[34;40;1m";
// public static final String B_PURPLE = "\u001B[35;40;1m";
// public static final String B_CYAN = "\u001B[36;40;1m";
// public static final String B_WHITE = "\u001B[37;40;1m";
//
// }
//
// Path: main/java/com/biscuit/commands/Command.java
// public interface Command {
//
// boolean execute() throws IOException;
// }
//
// Path: main/java/com/biscuit/models/Backlog.java
// public class Backlog {
//
// public transient Project project;
// public List<UserStory> userStories = new ArrayList<UserStory>();
//
//
// public void addUserStory(UserStory userStory) {
// this.userStories.add(userStory);
// }
//
//
// public void save() {
// project.save();
// }
// }
//
// Path: main/java/com/biscuit/models/Sprint.java
// public class Sprint {
//
// public transient Project project;
//
// // info
// public String name;
// public String description;
// public Status state;
// public Date startDate;
// public Date dueDate;
// public int assignedEffort;
// public int velocity;
//
// public List<UserStory> userStories = new ArrayList<>();
// public List<Bug> bugs;
// public List<Test> tests;
//
// // Completed 0pt 0% ToDo 8pt
//
// public static String[] fields;
// public static String[] fieldsAsHeader;
//
// static {
// fields = new String[] { "name", "description", "state", "start_date", "due_date", "assigned_effort", "velocity" };
// fieldsAsHeader = new String[] { "Name", "Description", "State", "Start Date", "Due Date", "Assigned Effort", "Velocity" };
// }
//
// public void addUserStory(UserStory userStory) {
// this.userStories.add(userStory);
// }
//
// public void save() {
// project.save();
// }
//
// }
//
// Path: main/java/com/biscuit/models/UserStory.java
// public class UserStory {
//
// public transient Project project;
//
// public String title;
// public String description;
// public Status state;
// public BusinessValue businessValue;
// public Date initiatedDate = null;
// public Date plannedDate = null;
// public Date dueDate = null;
// public int points;
//
// public static String[] fields;
//
// public List<Task> tasks = new ArrayList<>();
// public List<Bug> bugs = new ArrayList<>();
// public List<Test> tests = new ArrayList<>();
//
// static {
// fields = new String[] { "title", "description", "state", "business_value", "initiated_date", "planned_date", "due_date", "tasks", "points" };
// }
//
//
// public void save() {
// project.save();
// }
//
// }
//
// Path: main/java/com/biscuit/models/services/DateService.java
// public class DateService {
//
// public static transient SimpleDateFormat dateFormat = new SimpleDateFormat("MMM. dd, yyyy");
//
//
// public static boolean isSet(Date d) {
// return (d.compareTo(new Date(0)) > 0);
// }
//
//
// public static String getDateAsString(Date d) {
// if (DateService.isSet(d)) {
// return DateService.dateFormat.format(d);
// }
// return "Not set yet";
// }
//
// }
| import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import com.biscuit.ColorCodes;
import com.biscuit.commands.Command;
import com.biscuit.models.Backlog;
import com.biscuit.models.Sprint;
import com.biscuit.models.UserStory;
import com.biscuit.models.services.DateService;
import de.vandermeer.asciitable.v2.RenderedTable;
import de.vandermeer.asciitable.v2.V2_AsciiTable;
import de.vandermeer.asciitable.v2.render.V2_AsciiTableRenderer;
import de.vandermeer.asciitable.v2.render.WidthLongestLine;
import de.vandermeer.asciitable.v2.themes.V2_E_TableThemes; | package com.biscuit.commands.userStory;
public class ListUserStories implements Command {
Backlog backlog = null; | // Path: main/java/com/biscuit/ColorCodes.java
// public class ColorCodes {
//
// // with normal background
// public static final String RESET = "\u001B[0m";
// public static final String BLACK = "\u001B[30;1m";
// public static final String RED = "\u001B[31;1m";
// public static final String GREEN = "\u001B[32;1m";
// public static final String YELLOW = "\u001B[33;1m";
// public static final String BLUE = "\u001B[34;1m";
// public static final String PURPLE = "\u001B[35;1m";
// public static final String CYAN = "\u001B[36;1m";
// public static final String WHITE = "\u001B[37;1m";
//
// // with black background
// public static final String B_RESET = "\u001B[0m";
// public static final String B_BLACK = "\u001B[30;40;1m";
// public static final String B_RED = "\u001B[31;40;1m";
// public static final String B_GREEN = "\u001B[32;40;1m";
// public static final String B_YELLOW = "\u001B[33;40;1m";
// public static final String B_BLUE = "\u001B[34;40;1m";
// public static final String B_PURPLE = "\u001B[35;40;1m";
// public static final String B_CYAN = "\u001B[36;40;1m";
// public static final String B_WHITE = "\u001B[37;40;1m";
//
// }
//
// Path: main/java/com/biscuit/commands/Command.java
// public interface Command {
//
// boolean execute() throws IOException;
// }
//
// Path: main/java/com/biscuit/models/Backlog.java
// public class Backlog {
//
// public transient Project project;
// public List<UserStory> userStories = new ArrayList<UserStory>();
//
//
// public void addUserStory(UserStory userStory) {
// this.userStories.add(userStory);
// }
//
//
// public void save() {
// project.save();
// }
// }
//
// Path: main/java/com/biscuit/models/Sprint.java
// public class Sprint {
//
// public transient Project project;
//
// // info
// public String name;
// public String description;
// public Status state;
// public Date startDate;
// public Date dueDate;
// public int assignedEffort;
// public int velocity;
//
// public List<UserStory> userStories = new ArrayList<>();
// public List<Bug> bugs;
// public List<Test> tests;
//
// // Completed 0pt 0% ToDo 8pt
//
// public static String[] fields;
// public static String[] fieldsAsHeader;
//
// static {
// fields = new String[] { "name", "description", "state", "start_date", "due_date", "assigned_effort", "velocity" };
// fieldsAsHeader = new String[] { "Name", "Description", "State", "Start Date", "Due Date", "Assigned Effort", "Velocity" };
// }
//
// public void addUserStory(UserStory userStory) {
// this.userStories.add(userStory);
// }
//
// public void save() {
// project.save();
// }
//
// }
//
// Path: main/java/com/biscuit/models/UserStory.java
// public class UserStory {
//
// public transient Project project;
//
// public String title;
// public String description;
// public Status state;
// public BusinessValue businessValue;
// public Date initiatedDate = null;
// public Date plannedDate = null;
// public Date dueDate = null;
// public int points;
//
// public static String[] fields;
//
// public List<Task> tasks = new ArrayList<>();
// public List<Bug> bugs = new ArrayList<>();
// public List<Test> tests = new ArrayList<>();
//
// static {
// fields = new String[] { "title", "description", "state", "business_value", "initiated_date", "planned_date", "due_date", "tasks", "points" };
// }
//
//
// public void save() {
// project.save();
// }
//
// }
//
// Path: main/java/com/biscuit/models/services/DateService.java
// public class DateService {
//
// public static transient SimpleDateFormat dateFormat = new SimpleDateFormat("MMM. dd, yyyy");
//
//
// public static boolean isSet(Date d) {
// return (d.compareTo(new Date(0)) > 0);
// }
//
//
// public static String getDateAsString(Date d) {
// if (DateService.isSet(d)) {
// return DateService.dateFormat.format(d);
// }
// return "Not set yet";
// }
//
// }
// Path: main/java/com/biscuit/commands/userStory/ListUserStories.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import com.biscuit.ColorCodes;
import com.biscuit.commands.Command;
import com.biscuit.models.Backlog;
import com.biscuit.models.Sprint;
import com.biscuit.models.UserStory;
import com.biscuit.models.services.DateService;
import de.vandermeer.asciitable.v2.RenderedTable;
import de.vandermeer.asciitable.v2.V2_AsciiTable;
import de.vandermeer.asciitable.v2.render.V2_AsciiTableRenderer;
import de.vandermeer.asciitable.v2.render.WidthLongestLine;
import de.vandermeer.asciitable.v2.themes.V2_E_TableThemes;
package com.biscuit.commands.userStory;
public class ListUserStories implements Command {
Backlog backlog = null; | Sprint sprint = null; |
hamadmarri/Biscuit | main/java/com/biscuit/commands/userStory/ListUserStories.java | // Path: main/java/com/biscuit/ColorCodes.java
// public class ColorCodes {
//
// // with normal background
// public static final String RESET = "\u001B[0m";
// public static final String BLACK = "\u001B[30;1m";
// public static final String RED = "\u001B[31;1m";
// public static final String GREEN = "\u001B[32;1m";
// public static final String YELLOW = "\u001B[33;1m";
// public static final String BLUE = "\u001B[34;1m";
// public static final String PURPLE = "\u001B[35;1m";
// public static final String CYAN = "\u001B[36;1m";
// public static final String WHITE = "\u001B[37;1m";
//
// // with black background
// public static final String B_RESET = "\u001B[0m";
// public static final String B_BLACK = "\u001B[30;40;1m";
// public static final String B_RED = "\u001B[31;40;1m";
// public static final String B_GREEN = "\u001B[32;40;1m";
// public static final String B_YELLOW = "\u001B[33;40;1m";
// public static final String B_BLUE = "\u001B[34;40;1m";
// public static final String B_PURPLE = "\u001B[35;40;1m";
// public static final String B_CYAN = "\u001B[36;40;1m";
// public static final String B_WHITE = "\u001B[37;40;1m";
//
// }
//
// Path: main/java/com/biscuit/commands/Command.java
// public interface Command {
//
// boolean execute() throws IOException;
// }
//
// Path: main/java/com/biscuit/models/Backlog.java
// public class Backlog {
//
// public transient Project project;
// public List<UserStory> userStories = new ArrayList<UserStory>();
//
//
// public void addUserStory(UserStory userStory) {
// this.userStories.add(userStory);
// }
//
//
// public void save() {
// project.save();
// }
// }
//
// Path: main/java/com/biscuit/models/Sprint.java
// public class Sprint {
//
// public transient Project project;
//
// // info
// public String name;
// public String description;
// public Status state;
// public Date startDate;
// public Date dueDate;
// public int assignedEffort;
// public int velocity;
//
// public List<UserStory> userStories = new ArrayList<>();
// public List<Bug> bugs;
// public List<Test> tests;
//
// // Completed 0pt 0% ToDo 8pt
//
// public static String[] fields;
// public static String[] fieldsAsHeader;
//
// static {
// fields = new String[] { "name", "description", "state", "start_date", "due_date", "assigned_effort", "velocity" };
// fieldsAsHeader = new String[] { "Name", "Description", "State", "Start Date", "Due Date", "Assigned Effort", "Velocity" };
// }
//
// public void addUserStory(UserStory userStory) {
// this.userStories.add(userStory);
// }
//
// public void save() {
// project.save();
// }
//
// }
//
// Path: main/java/com/biscuit/models/UserStory.java
// public class UserStory {
//
// public transient Project project;
//
// public String title;
// public String description;
// public Status state;
// public BusinessValue businessValue;
// public Date initiatedDate = null;
// public Date plannedDate = null;
// public Date dueDate = null;
// public int points;
//
// public static String[] fields;
//
// public List<Task> tasks = new ArrayList<>();
// public List<Bug> bugs = new ArrayList<>();
// public List<Test> tests = new ArrayList<>();
//
// static {
// fields = new String[] { "title", "description", "state", "business_value", "initiated_date", "planned_date", "due_date", "tasks", "points" };
// }
//
//
// public void save() {
// project.save();
// }
//
// }
//
// Path: main/java/com/biscuit/models/services/DateService.java
// public class DateService {
//
// public static transient SimpleDateFormat dateFormat = new SimpleDateFormat("MMM. dd, yyyy");
//
//
// public static boolean isSet(Date d) {
// return (d.compareTo(new Date(0)) > 0);
// }
//
//
// public static String getDateAsString(Date d) {
// if (DateService.isSet(d)) {
// return DateService.dateFormat.format(d);
// }
// return "Not set yet";
// }
//
// }
| import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import com.biscuit.ColorCodes;
import com.biscuit.commands.Command;
import com.biscuit.models.Backlog;
import com.biscuit.models.Sprint;
import com.biscuit.models.UserStory;
import com.biscuit.models.services.DateService;
import de.vandermeer.asciitable.v2.RenderedTable;
import de.vandermeer.asciitable.v2.V2_AsciiTable;
import de.vandermeer.asciitable.v2.render.V2_AsciiTableRenderer;
import de.vandermeer.asciitable.v2.render.WidthLongestLine;
import de.vandermeer.asciitable.v2.themes.V2_E_TableThemes; | package com.biscuit.commands.userStory;
public class ListUserStories implements Command {
Backlog backlog = null;
Sprint sprint = null; | // Path: main/java/com/biscuit/ColorCodes.java
// public class ColorCodes {
//
// // with normal background
// public static final String RESET = "\u001B[0m";
// public static final String BLACK = "\u001B[30;1m";
// public static final String RED = "\u001B[31;1m";
// public static final String GREEN = "\u001B[32;1m";
// public static final String YELLOW = "\u001B[33;1m";
// public static final String BLUE = "\u001B[34;1m";
// public static final String PURPLE = "\u001B[35;1m";
// public static final String CYAN = "\u001B[36;1m";
// public static final String WHITE = "\u001B[37;1m";
//
// // with black background
// public static final String B_RESET = "\u001B[0m";
// public static final String B_BLACK = "\u001B[30;40;1m";
// public static final String B_RED = "\u001B[31;40;1m";
// public static final String B_GREEN = "\u001B[32;40;1m";
// public static final String B_YELLOW = "\u001B[33;40;1m";
// public static final String B_BLUE = "\u001B[34;40;1m";
// public static final String B_PURPLE = "\u001B[35;40;1m";
// public static final String B_CYAN = "\u001B[36;40;1m";
// public static final String B_WHITE = "\u001B[37;40;1m";
//
// }
//
// Path: main/java/com/biscuit/commands/Command.java
// public interface Command {
//
// boolean execute() throws IOException;
// }
//
// Path: main/java/com/biscuit/models/Backlog.java
// public class Backlog {
//
// public transient Project project;
// public List<UserStory> userStories = new ArrayList<UserStory>();
//
//
// public void addUserStory(UserStory userStory) {
// this.userStories.add(userStory);
// }
//
//
// public void save() {
// project.save();
// }
// }
//
// Path: main/java/com/biscuit/models/Sprint.java
// public class Sprint {
//
// public transient Project project;
//
// // info
// public String name;
// public String description;
// public Status state;
// public Date startDate;
// public Date dueDate;
// public int assignedEffort;
// public int velocity;
//
// public List<UserStory> userStories = new ArrayList<>();
// public List<Bug> bugs;
// public List<Test> tests;
//
// // Completed 0pt 0% ToDo 8pt
//
// public static String[] fields;
// public static String[] fieldsAsHeader;
//
// static {
// fields = new String[] { "name", "description", "state", "start_date", "due_date", "assigned_effort", "velocity" };
// fieldsAsHeader = new String[] { "Name", "Description", "State", "Start Date", "Due Date", "Assigned Effort", "Velocity" };
// }
//
// public void addUserStory(UserStory userStory) {
// this.userStories.add(userStory);
// }
//
// public void save() {
// project.save();
// }
//
// }
//
// Path: main/java/com/biscuit/models/UserStory.java
// public class UserStory {
//
// public transient Project project;
//
// public String title;
// public String description;
// public Status state;
// public BusinessValue businessValue;
// public Date initiatedDate = null;
// public Date plannedDate = null;
// public Date dueDate = null;
// public int points;
//
// public static String[] fields;
//
// public List<Task> tasks = new ArrayList<>();
// public List<Bug> bugs = new ArrayList<>();
// public List<Test> tests = new ArrayList<>();
//
// static {
// fields = new String[] { "title", "description", "state", "business_value", "initiated_date", "planned_date", "due_date", "tasks", "points" };
// }
//
//
// public void save() {
// project.save();
// }
//
// }
//
// Path: main/java/com/biscuit/models/services/DateService.java
// public class DateService {
//
// public static transient SimpleDateFormat dateFormat = new SimpleDateFormat("MMM. dd, yyyy");
//
//
// public static boolean isSet(Date d) {
// return (d.compareTo(new Date(0)) > 0);
// }
//
//
// public static String getDateAsString(Date d) {
// if (DateService.isSet(d)) {
// return DateService.dateFormat.format(d);
// }
// return "Not set yet";
// }
//
// }
// Path: main/java/com/biscuit/commands/userStory/ListUserStories.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import com.biscuit.ColorCodes;
import com.biscuit.commands.Command;
import com.biscuit.models.Backlog;
import com.biscuit.models.Sprint;
import com.biscuit.models.UserStory;
import com.biscuit.models.services.DateService;
import de.vandermeer.asciitable.v2.RenderedTable;
import de.vandermeer.asciitable.v2.V2_AsciiTable;
import de.vandermeer.asciitable.v2.render.V2_AsciiTableRenderer;
import de.vandermeer.asciitable.v2.render.WidthLongestLine;
import de.vandermeer.asciitable.v2.themes.V2_E_TableThemes;
package com.biscuit.commands.userStory;
public class ListUserStories implements Command {
Backlog backlog = null;
Sprint sprint = null; | List<UserStory> userStories = null; |
hamadmarri/Biscuit | main/java/com/biscuit/views/View.java | // Path: main/java/com/biscuit/ColorCodes.java
// public class ColorCodes {
//
// // with normal background
// public static final String RESET = "\u001B[0m";
// public static final String BLACK = "\u001B[30;1m";
// public static final String RED = "\u001B[31;1m";
// public static final String GREEN = "\u001B[32;1m";
// public static final String YELLOW = "\u001B[33;1m";
// public static final String BLUE = "\u001B[34;1m";
// public static final String PURPLE = "\u001B[35;1m";
// public static final String CYAN = "\u001B[36;1m";
// public static final String WHITE = "\u001B[37;1m";
//
// // with black background
// public static final String B_RESET = "\u001B[0m";
// public static final String B_BLACK = "\u001B[30;40;1m";
// public static final String B_RED = "\u001B[31;40;1m";
// public static final String B_GREEN = "\u001B[32;40;1m";
// public static final String B_YELLOW = "\u001B[33;40;1m";
// public static final String B_BLUE = "\u001B[34;40;1m";
// public static final String B_PURPLE = "\u001B[35;40;1m";
// public static final String B_CYAN = "\u001B[36;40;1m";
// public static final String B_WHITE = "\u001B[37;40;1m";
//
// }
//
// Path: main/java/com/biscuit/factories/UniversalCompleterFactory.java
// public class UniversalCompleterFactory {
//
// public static List<Completer> getUniversalCompleters() {
// List<Completer> completers = new ArrayList<Completer>();
//
// // TODO: Universal commands
// // completers.add(new ArgumentCompleter(new StringsCompleter("clear",
// // "exit", "users", "contacts", "groups",
// // "dashboard", "toggle_prompt", "undo", "redo", "help"), new
// // NullCompleter()));
//
// // completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// // new StringsCompleter("users"), new StringsCompleter("filter",
// // "sort"),
// // new NullCompleter()));
// //
// // completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// // new StringsCompleter("groups"), new StringsCompleter("filter",
// // "sort"),
// // new NullCompleter()));
// //
// // completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// // new StringsCompleter("contacts"), new StringsCompleter("filter",
// // "sort"),
// // new NullCompleter()));
//
// // completers.add(new ArgumentCompleter(new StringsCompleter("add"), new
// // StringsCompleter("user", "group", "contact"), new NullCompleter()));
//
// completers.add(new ArgumentCompleter(new StringsCompleter("clear", "exit", "dashboard", "help"), new NullCompleter()));
// completers.add(new ArgumentCompleter(new StringsCompleter("go_to"), new StringsCompleter("dashboard"), new NullCompleter()));
//
// return completers;
// }
// }
| import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.biscuit.ColorCodes;
import com.biscuit.factories.UniversalCompleterFactory;
import jline.console.ConsoleReader;
import jline.console.completer.AggregateCompleter;
import jline.console.completer.Completer; | e.printStackTrace();
}
}
public View(View previousView, String name) {
this.previousView = previousView;
this.name = name;
}
public void view() {
if (!isViewed) {
addPromptViews();
isViewed = true;
}
setPrompt();
clearCompleters();
addCompleters();
read();
}
protected void clearCompleters() {
if (completer != null)
reader.removeCompleter(completer);
}
private static void addUniversalCompleters() { | // Path: main/java/com/biscuit/ColorCodes.java
// public class ColorCodes {
//
// // with normal background
// public static final String RESET = "\u001B[0m";
// public static final String BLACK = "\u001B[30;1m";
// public static final String RED = "\u001B[31;1m";
// public static final String GREEN = "\u001B[32;1m";
// public static final String YELLOW = "\u001B[33;1m";
// public static final String BLUE = "\u001B[34;1m";
// public static final String PURPLE = "\u001B[35;1m";
// public static final String CYAN = "\u001B[36;1m";
// public static final String WHITE = "\u001B[37;1m";
//
// // with black background
// public static final String B_RESET = "\u001B[0m";
// public static final String B_BLACK = "\u001B[30;40;1m";
// public static final String B_RED = "\u001B[31;40;1m";
// public static final String B_GREEN = "\u001B[32;40;1m";
// public static final String B_YELLOW = "\u001B[33;40;1m";
// public static final String B_BLUE = "\u001B[34;40;1m";
// public static final String B_PURPLE = "\u001B[35;40;1m";
// public static final String B_CYAN = "\u001B[36;40;1m";
// public static final String B_WHITE = "\u001B[37;40;1m";
//
// }
//
// Path: main/java/com/biscuit/factories/UniversalCompleterFactory.java
// public class UniversalCompleterFactory {
//
// public static List<Completer> getUniversalCompleters() {
// List<Completer> completers = new ArrayList<Completer>();
//
// // TODO: Universal commands
// // completers.add(new ArgumentCompleter(new StringsCompleter("clear",
// // "exit", "users", "contacts", "groups",
// // "dashboard", "toggle_prompt", "undo", "redo", "help"), new
// // NullCompleter()));
//
// // completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// // new StringsCompleter("users"), new StringsCompleter("filter",
// // "sort"),
// // new NullCompleter()));
// //
// // completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// // new StringsCompleter("groups"), new StringsCompleter("filter",
// // "sort"),
// // new NullCompleter()));
// //
// // completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// // new StringsCompleter("contacts"), new StringsCompleter("filter",
// // "sort"),
// // new NullCompleter()));
//
// // completers.add(new ArgumentCompleter(new StringsCompleter("add"), new
// // StringsCompleter("user", "group", "contact"), new NullCompleter()));
//
// completers.add(new ArgumentCompleter(new StringsCompleter("clear", "exit", "dashboard", "help"), new NullCompleter()));
// completers.add(new ArgumentCompleter(new StringsCompleter("go_to"), new StringsCompleter("dashboard"), new NullCompleter()));
//
// return completers;
// }
// }
// Path: main/java/com/biscuit/views/View.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.biscuit.ColorCodes;
import com.biscuit.factories.UniversalCompleterFactory;
import jline.console.ConsoleReader;
import jline.console.completer.AggregateCompleter;
import jline.console.completer.Completer;
e.printStackTrace();
}
}
public View(View previousView, String name) {
this.previousView = previousView;
this.name = name;
}
public void view() {
if (!isViewed) {
addPromptViews();
isViewed = true;
}
setPrompt();
clearCompleters();
addCompleters();
read();
}
protected void clearCompleters() {
if (completer != null)
reader.removeCompleter(completer);
}
private static void addUniversalCompleters() { | universalCompleters.addAll(UniversalCompleterFactory.getUniversalCompleters()); |
hamadmarri/Biscuit | main/java/com/biscuit/views/View.java | // Path: main/java/com/biscuit/ColorCodes.java
// public class ColorCodes {
//
// // with normal background
// public static final String RESET = "\u001B[0m";
// public static final String BLACK = "\u001B[30;1m";
// public static final String RED = "\u001B[31;1m";
// public static final String GREEN = "\u001B[32;1m";
// public static final String YELLOW = "\u001B[33;1m";
// public static final String BLUE = "\u001B[34;1m";
// public static final String PURPLE = "\u001B[35;1m";
// public static final String CYAN = "\u001B[36;1m";
// public static final String WHITE = "\u001B[37;1m";
//
// // with black background
// public static final String B_RESET = "\u001B[0m";
// public static final String B_BLACK = "\u001B[30;40;1m";
// public static final String B_RED = "\u001B[31;40;1m";
// public static final String B_GREEN = "\u001B[32;40;1m";
// public static final String B_YELLOW = "\u001B[33;40;1m";
// public static final String B_BLUE = "\u001B[34;40;1m";
// public static final String B_PURPLE = "\u001B[35;40;1m";
// public static final String B_CYAN = "\u001B[36;40;1m";
// public static final String B_WHITE = "\u001B[37;40;1m";
//
// }
//
// Path: main/java/com/biscuit/factories/UniversalCompleterFactory.java
// public class UniversalCompleterFactory {
//
// public static List<Completer> getUniversalCompleters() {
// List<Completer> completers = new ArrayList<Completer>();
//
// // TODO: Universal commands
// // completers.add(new ArgumentCompleter(new StringsCompleter("clear",
// // "exit", "users", "contacts", "groups",
// // "dashboard", "toggle_prompt", "undo", "redo", "help"), new
// // NullCompleter()));
//
// // completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// // new StringsCompleter("users"), new StringsCompleter("filter",
// // "sort"),
// // new NullCompleter()));
// //
// // completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// // new StringsCompleter("groups"), new StringsCompleter("filter",
// // "sort"),
// // new NullCompleter()));
// //
// // completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// // new StringsCompleter("contacts"), new StringsCompleter("filter",
// // "sort"),
// // new NullCompleter()));
//
// // completers.add(new ArgumentCompleter(new StringsCompleter("add"), new
// // StringsCompleter("user", "group", "contact"), new NullCompleter()));
//
// completers.add(new ArgumentCompleter(new StringsCompleter("clear", "exit", "dashboard", "help"), new NullCompleter()));
// completers.add(new ArgumentCompleter(new StringsCompleter("go_to"), new StringsCompleter("dashboard"), new NullCompleter()));
//
// return completers;
// }
// }
| import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.biscuit.ColorCodes;
import com.biscuit.factories.UniversalCompleterFactory;
import jline.console.ConsoleReader;
import jline.console.completer.AggregateCompleter;
import jline.console.completer.Completer; | while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
continue;
}
String words[] = line.split("\\s+");
if (checkIfUnivesalCommand(words)) {
continue;
}
if (!executeCommand(words)) {
System.out.println("invalid command!");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private boolean checkIfUnivesalCommand(String[] words) throws IOException {
if (words.length == 1) {
if (words[0].equals("clear")) {
reader.clearScreen();
return true;
} else if (words[0].equals("exit")) { | // Path: main/java/com/biscuit/ColorCodes.java
// public class ColorCodes {
//
// // with normal background
// public static final String RESET = "\u001B[0m";
// public static final String BLACK = "\u001B[30;1m";
// public static final String RED = "\u001B[31;1m";
// public static final String GREEN = "\u001B[32;1m";
// public static final String YELLOW = "\u001B[33;1m";
// public static final String BLUE = "\u001B[34;1m";
// public static final String PURPLE = "\u001B[35;1m";
// public static final String CYAN = "\u001B[36;1m";
// public static final String WHITE = "\u001B[37;1m";
//
// // with black background
// public static final String B_RESET = "\u001B[0m";
// public static final String B_BLACK = "\u001B[30;40;1m";
// public static final String B_RED = "\u001B[31;40;1m";
// public static final String B_GREEN = "\u001B[32;40;1m";
// public static final String B_YELLOW = "\u001B[33;40;1m";
// public static final String B_BLUE = "\u001B[34;40;1m";
// public static final String B_PURPLE = "\u001B[35;40;1m";
// public static final String B_CYAN = "\u001B[36;40;1m";
// public static final String B_WHITE = "\u001B[37;40;1m";
//
// }
//
// Path: main/java/com/biscuit/factories/UniversalCompleterFactory.java
// public class UniversalCompleterFactory {
//
// public static List<Completer> getUniversalCompleters() {
// List<Completer> completers = new ArrayList<Completer>();
//
// // TODO: Universal commands
// // completers.add(new ArgumentCompleter(new StringsCompleter("clear",
// // "exit", "users", "contacts", "groups",
// // "dashboard", "toggle_prompt", "undo", "redo", "help"), new
// // NullCompleter()));
//
// // completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// // new StringsCompleter("users"), new StringsCompleter("filter",
// // "sort"),
// // new NullCompleter()));
// //
// // completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// // new StringsCompleter("groups"), new StringsCompleter("filter",
// // "sort"),
// // new NullCompleter()));
// //
// // completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// // new StringsCompleter("contacts"), new StringsCompleter("filter",
// // "sort"),
// // new NullCompleter()));
//
// // completers.add(new ArgumentCompleter(new StringsCompleter("add"), new
// // StringsCompleter("user", "group", "contact"), new NullCompleter()));
//
// completers.add(new ArgumentCompleter(new StringsCompleter("clear", "exit", "dashboard", "help"), new NullCompleter()));
// completers.add(new ArgumentCompleter(new StringsCompleter("go_to"), new StringsCompleter("dashboard"), new NullCompleter()));
//
// return completers;
// }
// }
// Path: main/java/com/biscuit/views/View.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.biscuit.ColorCodes;
import com.biscuit.factories.UniversalCompleterFactory;
import jline.console.ConsoleReader;
import jline.console.completer.AggregateCompleter;
import jline.console.completer.Completer;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
continue;
}
String words[] = line.split("\\s+");
if (checkIfUnivesalCommand(words)) {
continue;
}
if (!executeCommand(words)) {
System.out.println("invalid command!");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private boolean checkIfUnivesalCommand(String[] words) throws IOException {
if (words.length == 1) {
if (words[0].equals("clear")) {
reader.clearScreen();
return true;
} else if (words[0].equals("exit")) { | System.out.println(ColorCodes.BLUE + "See ya!\n" + ColorCodes.RESET); |
pinfake/pes6j | src/pes6j/datablocks/PESConnection.java | // Path: src/pes6j/servers/Configuration.java
// public class Configuration {
//
// public static Properties serverProperties;
// public static Properties country2Continent;
// public static Properties authProperties;
// public static Properties gameServerProperties;
//
// public static void initializeServerProperties() throws IOException {
// serverProperties = new Properties();
// serverProperties.load(new FileInputStream("config/server.properties")); //$NON-NLS-1$
//
// }
//
// public static void initializeAuthProperties() throws IOException {
// authProperties = new Properties();
// authProperties.load(new FileInputStream("config/auth.properties")); //$NON-NLS-1$
//
// }
//
// public static void initializeGameServerProperties() throws IOException {
// gameServerProperties = new Properties();
// gameServerProperties.load(new FileInputStream("config/gameserver.properties")); //$NON-NLS-1$
// country2Continent = new Properties();
// country2Continent.load(new FileInputStream("config/country2continent.properties"));
// }
//
// public static void initializeGameServerProperties( String configFile ) throws IOException {
// gameServerProperties = new Properties();
// gameServerProperties.load(new FileInputStream(configFile)); //$NON-NLS-1$
// country2Continent = new Properties();
// country2Continent.load(new FileInputStream("config/country2continent.properties"));
// }
// }
//
// Path: src/pes6j/servers/HTTPFetchUserInfoThread.java
// public class HTTPFetchUserInfoThread extends Thread {
// public final static int FETCHED = 2;
// public final static int FETCHING = 1;
// public final static int IDLE = 0;
// String ip_address;
// String auth_url;
// UserInfo uInfo;
// int status;
//
// HTTPFetchUserInfoThread( String auth_url, String ip_address) {
// this.ip_address = ip_address;
// this.auth_url = auth_url;
// this.uInfo = null;
// this.status = IDLE;
// }
//
// public void run() {
// this.status = FETCHING;
// this.uInfo = Tools.getUserInfo( auth_url, ip_address );
// this.status = FETCHED;
// }
//
// public UserInfo getUserInfo() {
// return( this.uInfo );
// }
//
// public int getStatus() {
// return( this.status );
// }
// }
//
// Path: src/pes6j/servers/Logger.java
// public class Logger {
// File f;
// String fileName;
// FileWriter writer;
//
// public Logger( File f ) throws IOException {
// this.f = f;
// fileName = f.getPath();
// open();
// }
//
// public Logger( String fileName ) throws IOException {
// this.fileName = fileName;
// this.f = new File( fileName );
// open();
// }
//
// synchronized void open() throws IOException {
// writer = new FileWriter(f, true);
// }
//
// public synchronized void log(String message) {
// try {
// writer.write("[" + (new Date()).toString() + "] " + message + "\n");
// writer.flush();
// } catch( IOException ex ) {
// System.err.println( "ERROR!: Coultn't write to log - " + fileName );
// ex.printStackTrace();
// }
// }
//
// public synchronized void log(Exception ex) {
// try {
// writer.write("[" + (new Date()).toString() + "] ");
// PrintWriter pw = new PrintWriter( writer );
// ex.printStackTrace( pw );
// writer.write( "\n");
// writer.flush();
// } catch( IOException e ) {
// System.err.println( "ERROR!: Coultn't write to log - " + fileName );
// e.printStackTrace();
// }
// }
//
// public synchronized void log(String message, Message mes) {
// try {
// writer.write("[" + (new Date()).toString() + "] " + message + " DUMP:\n");
// writer.write( Util.toHex(mes.getBytes()) + "\n");
// writer.flush();
// } catch( IOException ex ) {
// System.err.println( "ERROR!: Couldn't write to log - " + fileName );
// ex.printStackTrace();
// }
// }
//
// public synchronized void log(String message, Vector<Message> mes) {
// try {
// writer.write("[" + (new Date()).toString() + "] " + message + " DUMPS:\n");
// for( int i = 0; i < mes.size(); i++ )
// writer.write( Util.toHex(mes.get(i).getBytes()) + "\n");
// writer.flush();
// } catch( IOException ex ) {
// System.err.println( "ERROR!: Couldn't write to log - " + fileName );
// ex.printStackTrace();
// }
// }
//
// public synchronized void close() throws IOException {
// writer.flush();
// writer.close();
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Stack;
import pes6j.servers.Configuration;
import pes6j.servers.HTTPFetchUserInfoThread;
import pes6j.servers.Logger; | package pes6j.datablocks;
public class PESConnection {
public static final int DEBUG_MESSAGES_SAVED = 4;
long pid;
SocketChannel outChannel;
OutputStream out;
InputStream in;
long seq;
Socket socket; | // Path: src/pes6j/servers/Configuration.java
// public class Configuration {
//
// public static Properties serverProperties;
// public static Properties country2Continent;
// public static Properties authProperties;
// public static Properties gameServerProperties;
//
// public static void initializeServerProperties() throws IOException {
// serverProperties = new Properties();
// serverProperties.load(new FileInputStream("config/server.properties")); //$NON-NLS-1$
//
// }
//
// public static void initializeAuthProperties() throws IOException {
// authProperties = new Properties();
// authProperties.load(new FileInputStream("config/auth.properties")); //$NON-NLS-1$
//
// }
//
// public static void initializeGameServerProperties() throws IOException {
// gameServerProperties = new Properties();
// gameServerProperties.load(new FileInputStream("config/gameserver.properties")); //$NON-NLS-1$
// country2Continent = new Properties();
// country2Continent.load(new FileInputStream("config/country2continent.properties"));
// }
//
// public static void initializeGameServerProperties( String configFile ) throws IOException {
// gameServerProperties = new Properties();
// gameServerProperties.load(new FileInputStream(configFile)); //$NON-NLS-1$
// country2Continent = new Properties();
// country2Continent.load(new FileInputStream("config/country2continent.properties"));
// }
// }
//
// Path: src/pes6j/servers/HTTPFetchUserInfoThread.java
// public class HTTPFetchUserInfoThread extends Thread {
// public final static int FETCHED = 2;
// public final static int FETCHING = 1;
// public final static int IDLE = 0;
// String ip_address;
// String auth_url;
// UserInfo uInfo;
// int status;
//
// HTTPFetchUserInfoThread( String auth_url, String ip_address) {
// this.ip_address = ip_address;
// this.auth_url = auth_url;
// this.uInfo = null;
// this.status = IDLE;
// }
//
// public void run() {
// this.status = FETCHING;
// this.uInfo = Tools.getUserInfo( auth_url, ip_address );
// this.status = FETCHED;
// }
//
// public UserInfo getUserInfo() {
// return( this.uInfo );
// }
//
// public int getStatus() {
// return( this.status );
// }
// }
//
// Path: src/pes6j/servers/Logger.java
// public class Logger {
// File f;
// String fileName;
// FileWriter writer;
//
// public Logger( File f ) throws IOException {
// this.f = f;
// fileName = f.getPath();
// open();
// }
//
// public Logger( String fileName ) throws IOException {
// this.fileName = fileName;
// this.f = new File( fileName );
// open();
// }
//
// synchronized void open() throws IOException {
// writer = new FileWriter(f, true);
// }
//
// public synchronized void log(String message) {
// try {
// writer.write("[" + (new Date()).toString() + "] " + message + "\n");
// writer.flush();
// } catch( IOException ex ) {
// System.err.println( "ERROR!: Coultn't write to log - " + fileName );
// ex.printStackTrace();
// }
// }
//
// public synchronized void log(Exception ex) {
// try {
// writer.write("[" + (new Date()).toString() + "] ");
// PrintWriter pw = new PrintWriter( writer );
// ex.printStackTrace( pw );
// writer.write( "\n");
// writer.flush();
// } catch( IOException e ) {
// System.err.println( "ERROR!: Coultn't write to log - " + fileName );
// e.printStackTrace();
// }
// }
//
// public synchronized void log(String message, Message mes) {
// try {
// writer.write("[" + (new Date()).toString() + "] " + message + " DUMP:\n");
// writer.write( Util.toHex(mes.getBytes()) + "\n");
// writer.flush();
// } catch( IOException ex ) {
// System.err.println( "ERROR!: Couldn't write to log - " + fileName );
// ex.printStackTrace();
// }
// }
//
// public synchronized void log(String message, Vector<Message> mes) {
// try {
// writer.write("[" + (new Date()).toString() + "] " + message + " DUMPS:\n");
// for( int i = 0; i < mes.size(); i++ )
// writer.write( Util.toHex(mes.get(i).getBytes()) + "\n");
// writer.flush();
// } catch( IOException ex ) {
// System.err.println( "ERROR!: Couldn't write to log - " + fileName );
// ex.printStackTrace();
// }
// }
//
// public synchronized void close() throws IOException {
// writer.flush();
// writer.close();
// }
// }
// Path: src/pes6j/datablocks/PESConnection.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Stack;
import pes6j.servers.Configuration;
import pes6j.servers.HTTPFetchUserInfoThread;
import pes6j.servers.Logger;
package pes6j.datablocks;
public class PESConnection {
public static final int DEBUG_MESSAGES_SAVED = 4;
long pid;
SocketChannel outChannel;
OutputStream out;
InputStream in;
long seq;
Socket socket; | Logger logger; |
pinfake/pes6j | src/pes6j/datablocks/PESConnection.java | // Path: src/pes6j/servers/Configuration.java
// public class Configuration {
//
// public static Properties serverProperties;
// public static Properties country2Continent;
// public static Properties authProperties;
// public static Properties gameServerProperties;
//
// public static void initializeServerProperties() throws IOException {
// serverProperties = new Properties();
// serverProperties.load(new FileInputStream("config/server.properties")); //$NON-NLS-1$
//
// }
//
// public static void initializeAuthProperties() throws IOException {
// authProperties = new Properties();
// authProperties.load(new FileInputStream("config/auth.properties")); //$NON-NLS-1$
//
// }
//
// public static void initializeGameServerProperties() throws IOException {
// gameServerProperties = new Properties();
// gameServerProperties.load(new FileInputStream("config/gameserver.properties")); //$NON-NLS-1$
// country2Continent = new Properties();
// country2Continent.load(new FileInputStream("config/country2continent.properties"));
// }
//
// public static void initializeGameServerProperties( String configFile ) throws IOException {
// gameServerProperties = new Properties();
// gameServerProperties.load(new FileInputStream(configFile)); //$NON-NLS-1$
// country2Continent = new Properties();
// country2Continent.load(new FileInputStream("config/country2continent.properties"));
// }
// }
//
// Path: src/pes6j/servers/HTTPFetchUserInfoThread.java
// public class HTTPFetchUserInfoThread extends Thread {
// public final static int FETCHED = 2;
// public final static int FETCHING = 1;
// public final static int IDLE = 0;
// String ip_address;
// String auth_url;
// UserInfo uInfo;
// int status;
//
// HTTPFetchUserInfoThread( String auth_url, String ip_address) {
// this.ip_address = ip_address;
// this.auth_url = auth_url;
// this.uInfo = null;
// this.status = IDLE;
// }
//
// public void run() {
// this.status = FETCHING;
// this.uInfo = Tools.getUserInfo( auth_url, ip_address );
// this.status = FETCHED;
// }
//
// public UserInfo getUserInfo() {
// return( this.uInfo );
// }
//
// public int getStatus() {
// return( this.status );
// }
// }
//
// Path: src/pes6j/servers/Logger.java
// public class Logger {
// File f;
// String fileName;
// FileWriter writer;
//
// public Logger( File f ) throws IOException {
// this.f = f;
// fileName = f.getPath();
// open();
// }
//
// public Logger( String fileName ) throws IOException {
// this.fileName = fileName;
// this.f = new File( fileName );
// open();
// }
//
// synchronized void open() throws IOException {
// writer = new FileWriter(f, true);
// }
//
// public synchronized void log(String message) {
// try {
// writer.write("[" + (new Date()).toString() + "] " + message + "\n");
// writer.flush();
// } catch( IOException ex ) {
// System.err.println( "ERROR!: Coultn't write to log - " + fileName );
// ex.printStackTrace();
// }
// }
//
// public synchronized void log(Exception ex) {
// try {
// writer.write("[" + (new Date()).toString() + "] ");
// PrintWriter pw = new PrintWriter( writer );
// ex.printStackTrace( pw );
// writer.write( "\n");
// writer.flush();
// } catch( IOException e ) {
// System.err.println( "ERROR!: Coultn't write to log - " + fileName );
// e.printStackTrace();
// }
// }
//
// public synchronized void log(String message, Message mes) {
// try {
// writer.write("[" + (new Date()).toString() + "] " + message + " DUMP:\n");
// writer.write( Util.toHex(mes.getBytes()) + "\n");
// writer.flush();
// } catch( IOException ex ) {
// System.err.println( "ERROR!: Couldn't write to log - " + fileName );
// ex.printStackTrace();
// }
// }
//
// public synchronized void log(String message, Vector<Message> mes) {
// try {
// writer.write("[" + (new Date()).toString() + "] " + message + " DUMPS:\n");
// for( int i = 0; i < mes.size(); i++ )
// writer.write( Util.toHex(mes.get(i).getBytes()) + "\n");
// writer.flush();
// } catch( IOException ex ) {
// System.err.println( "ERROR!: Couldn't write to log - " + fileName );
// ex.printStackTrace();
// }
// }
//
// public synchronized void close() throws IOException {
// writer.flush();
// writer.close();
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Stack;
import pes6j.servers.Configuration;
import pes6j.servers.HTTPFetchUserInfoThread;
import pes6j.servers.Logger; | package pes6j.datablocks;
public class PESConnection {
public static final int DEBUG_MESSAGES_SAVED = 4;
long pid;
SocketChannel outChannel;
OutputStream out;
InputStream in;
long seq;
Socket socket;
Logger logger;
long requester;
long recipient;
Stack<Message> lastMessages;
PlayerInfo pInfo;
UserInfo uInfo;
DataCdKeyAndPass cdkey;
long lastKATime;
byte[] readBuffer;
MyByteBuffer writeBuffer; | // Path: src/pes6j/servers/Configuration.java
// public class Configuration {
//
// public static Properties serverProperties;
// public static Properties country2Continent;
// public static Properties authProperties;
// public static Properties gameServerProperties;
//
// public static void initializeServerProperties() throws IOException {
// serverProperties = new Properties();
// serverProperties.load(new FileInputStream("config/server.properties")); //$NON-NLS-1$
//
// }
//
// public static void initializeAuthProperties() throws IOException {
// authProperties = new Properties();
// authProperties.load(new FileInputStream("config/auth.properties")); //$NON-NLS-1$
//
// }
//
// public static void initializeGameServerProperties() throws IOException {
// gameServerProperties = new Properties();
// gameServerProperties.load(new FileInputStream("config/gameserver.properties")); //$NON-NLS-1$
// country2Continent = new Properties();
// country2Continent.load(new FileInputStream("config/country2continent.properties"));
// }
//
// public static void initializeGameServerProperties( String configFile ) throws IOException {
// gameServerProperties = new Properties();
// gameServerProperties.load(new FileInputStream(configFile)); //$NON-NLS-1$
// country2Continent = new Properties();
// country2Continent.load(new FileInputStream("config/country2continent.properties"));
// }
// }
//
// Path: src/pes6j/servers/HTTPFetchUserInfoThread.java
// public class HTTPFetchUserInfoThread extends Thread {
// public final static int FETCHED = 2;
// public final static int FETCHING = 1;
// public final static int IDLE = 0;
// String ip_address;
// String auth_url;
// UserInfo uInfo;
// int status;
//
// HTTPFetchUserInfoThread( String auth_url, String ip_address) {
// this.ip_address = ip_address;
// this.auth_url = auth_url;
// this.uInfo = null;
// this.status = IDLE;
// }
//
// public void run() {
// this.status = FETCHING;
// this.uInfo = Tools.getUserInfo( auth_url, ip_address );
// this.status = FETCHED;
// }
//
// public UserInfo getUserInfo() {
// return( this.uInfo );
// }
//
// public int getStatus() {
// return( this.status );
// }
// }
//
// Path: src/pes6j/servers/Logger.java
// public class Logger {
// File f;
// String fileName;
// FileWriter writer;
//
// public Logger( File f ) throws IOException {
// this.f = f;
// fileName = f.getPath();
// open();
// }
//
// public Logger( String fileName ) throws IOException {
// this.fileName = fileName;
// this.f = new File( fileName );
// open();
// }
//
// synchronized void open() throws IOException {
// writer = new FileWriter(f, true);
// }
//
// public synchronized void log(String message) {
// try {
// writer.write("[" + (new Date()).toString() + "] " + message + "\n");
// writer.flush();
// } catch( IOException ex ) {
// System.err.println( "ERROR!: Coultn't write to log - " + fileName );
// ex.printStackTrace();
// }
// }
//
// public synchronized void log(Exception ex) {
// try {
// writer.write("[" + (new Date()).toString() + "] ");
// PrintWriter pw = new PrintWriter( writer );
// ex.printStackTrace( pw );
// writer.write( "\n");
// writer.flush();
// } catch( IOException e ) {
// System.err.println( "ERROR!: Coultn't write to log - " + fileName );
// e.printStackTrace();
// }
// }
//
// public synchronized void log(String message, Message mes) {
// try {
// writer.write("[" + (new Date()).toString() + "] " + message + " DUMP:\n");
// writer.write( Util.toHex(mes.getBytes()) + "\n");
// writer.flush();
// } catch( IOException ex ) {
// System.err.println( "ERROR!: Couldn't write to log - " + fileName );
// ex.printStackTrace();
// }
// }
//
// public synchronized void log(String message, Vector<Message> mes) {
// try {
// writer.write("[" + (new Date()).toString() + "] " + message + " DUMPS:\n");
// for( int i = 0; i < mes.size(); i++ )
// writer.write( Util.toHex(mes.get(i).getBytes()) + "\n");
// writer.flush();
// } catch( IOException ex ) {
// System.err.println( "ERROR!: Couldn't write to log - " + fileName );
// ex.printStackTrace();
// }
// }
//
// public synchronized void close() throws IOException {
// writer.flush();
// writer.close();
// }
// }
// Path: src/pes6j/datablocks/PESConnection.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Stack;
import pes6j.servers.Configuration;
import pes6j.servers.HTTPFetchUserInfoThread;
import pes6j.servers.Logger;
package pes6j.datablocks;
public class PESConnection {
public static final int DEBUG_MESSAGES_SAVED = 4;
long pid;
SocketChannel outChannel;
OutputStream out;
InputStream in;
long seq;
Socket socket;
Logger logger;
long requester;
long recipient;
Stack<Message> lastMessages;
PlayerInfo pInfo;
UserInfo uInfo;
DataCdKeyAndPass cdkey;
long lastKATime;
byte[] readBuffer;
MyByteBuffer writeBuffer; | HTTPFetchUserInfoThread uInfoThread; |
pinfake/pes6j | src/pes6j/servers/HTTPFetchUserInfoThread.java | // Path: src/pes6j/datablocks/UserInfo.java
// public class UserInfo {
// String username;
// int access;
//
// public UserInfo( String username, int access ) {
// this.username = username;
// this.access = access;
// }
//
// public String getUsername() {
// return( username );
// }
//
// public int getAccess() {
// return( access );
// }
//
// public void setUsername( String username ) {
// this.username = username;
// }
//
// public void setAccess( int access ) {
// this.access = access;
// }
// }
| import pes6j.datablocks.UserInfo; | package pes6j.servers;
public class HTTPFetchUserInfoThread extends Thread {
public final static int FETCHED = 2;
public final static int FETCHING = 1;
public final static int IDLE = 0;
String ip_address;
String auth_url; | // Path: src/pes6j/datablocks/UserInfo.java
// public class UserInfo {
// String username;
// int access;
//
// public UserInfo( String username, int access ) {
// this.username = username;
// this.access = access;
// }
//
// public String getUsername() {
// return( username );
// }
//
// public int getAccess() {
// return( access );
// }
//
// public void setUsername( String username ) {
// this.username = username;
// }
//
// public void setAccess( int access ) {
// this.access = access;
// }
// }
// Path: src/pes6j/servers/HTTPFetchUserInfoThread.java
import pes6j.datablocks.UserInfo;
package pes6j.servers;
public class HTTPFetchUserInfoThread extends Thread {
public final static int FETCHED = 2;
public final static int FETCHING = 1;
public final static int IDLE = 0;
String ip_address;
String auth_url; | UserInfo uInfo; |
wesabe/grendel | src/main/java/com/wesabe/grendel/entities/User.java | // Path: src/main/java/com/wesabe/grendel/openpgp/CryptographicException.java
// public class CryptographicException extends Exception {
// private static final long serialVersionUID = 7018291212808057570L;
//
// public CryptographicException(String message) {
// super(message);
// }
//
// public CryptographicException(Throwable cause) {
// super(cause);
// }
//
// public CryptographicException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/openpgp/KeySet.java
// public class KeySet {
// private final MasterKey masterKey;
// private final SubKey subKey;
//
// /**
// * Loads a {@link KeySet} from an array of bytes.
// *
// * @throws CryptographicException if the encoded {@link KeySet} is malformed
// */
// public static KeySet load(byte[] encoded) throws CryptographicException {
// return load(new ByteArrayInputStream(encoded));
// }
//
// /**
// * Loads a {@link KeySet} from a {@link PGPSecretKeyRing}.
// */
// public static KeySet load(PGPSecretKeyRing keyRing) throws CryptographicException {
// final List<PGPSecretKey> secretKeys = Iterators.toList(keyRing.getSecretKeys());
// final MasterKey masterKey = MasterKey.load(secretKeys.get(0));
// final SubKey subKey = SubKey.load(secretKeys.get(1), masterKey);
//
// return new KeySet(masterKey, subKey);
// }
//
// /**
// * Loads a {@link KeySet} from an {@link InputStream}.
// */
// public static KeySet load(InputStream input) throws CryptographicException {
// try {
// final PGPSecretKeyRing keyRing = new PGPSecretKeyRing(input);
// input.close();
// return load(keyRing);
// } catch (IOException e) {
// throw new CryptographicException(e);
// } catch (PGPException e) {
// throw new CryptographicException(e);
// }
// }
//
// protected KeySet(MasterKey masterKey, SubKey subKey) {
// this.masterKey = masterKey;
// this.subKey = subKey;
// }
//
// /**
// * Returns the keyset's {@link MasterKey}.
// */
// public MasterKey getMasterKey() {
// return masterKey;
// }
//
// /**
// * Returns the keyset's {@link SubKey}.
// */
// public SubKey getSubKey() {
// return subKey;
// }
//
// /**
// * Returns the keyset's user ID.
// */
// public String getUserID() {
// return masterKey.getUserID();
// }
//
// /**
// * Writes the keyset in encoded form, to {@code output}.
// *
// * @param output an {@link OutputStream}
// * @throws IOException if there is an error writing to {@code output}
// */
// public void encode(OutputStream output) throws IOException {
// masterKey.getSecretKey().encode(output);
// subKey.getSecretKey().encode(output);
// }
//
// /**
// * Returns the keyset in encoded form.
// */
// public byte[] getEncoded() {
// final ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// encode(output);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// return output.toByteArray();
// }
//
// @Override
// public String toString() {
// return String.format("[%s, %s]", masterKey, subKey);
// }
//
// /**
// * Given the keyset's passphrase, unlocks the secret keys and returns an
// * {@link UnlockedKeySet} equivalent of {@code this}.
// *
// * @param passphrase the key's passphrase
// * @return a {@link UnlockedKeySet} equivalent of {@code this}
// * @throws CryptographicException if {@code passphrase} is incorrect
// */
// public UnlockedKeySet unlock(char[] passphrase) throws CryptographicException {
// final UnlockedMasterKey unlockedMasterKey = masterKey.unlock(passphrase);
// final UnlockedSubKey unlockedSubKey = subKey.unlock(passphrase);
// return new UnlockedKeySet(unlockedMasterKey, unlockedSubKey);
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/util/HashCode.java
// public class HashCode {
// private HashCode() {}
//
// public static int calculate(Object... objects) {
// return Arrays.deepHashCode(objects);
// }
// }
| import static com.google.common.base.Objects.*;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.*;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.google.common.collect.Sets;
import com.wesabe.grendel.openpgp.CryptographicException;
import com.wesabe.grendel.openpgp.KeySet;
import com.wesabe.grendel.util.HashCode; | @Deprecated
public User() {
// blank constructor to be used by Hibernate
}
/**
* Creates a new Grendel user with a given {@link KeySet}.
*
* @param keySet the {@link KeySet} belonging to the user
*/
public User(KeySet keySet) {
setKeySet(keySet);
this.createdAt = new DateTime(DateTimeZone.UTC);
this.modifiedAt = new DateTime(DateTimeZone.UTC);
}
/**
* Returns the user's id.
*/
public String getId() {
return id;
}
/**
* Returns the user's {@link KeySet}.
*/
public KeySet getKeySet() {
if (keySet == null) {
try {
this.keySet = KeySet.load(encodedKeySet); | // Path: src/main/java/com/wesabe/grendel/openpgp/CryptographicException.java
// public class CryptographicException extends Exception {
// private static final long serialVersionUID = 7018291212808057570L;
//
// public CryptographicException(String message) {
// super(message);
// }
//
// public CryptographicException(Throwable cause) {
// super(cause);
// }
//
// public CryptographicException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/openpgp/KeySet.java
// public class KeySet {
// private final MasterKey masterKey;
// private final SubKey subKey;
//
// /**
// * Loads a {@link KeySet} from an array of bytes.
// *
// * @throws CryptographicException if the encoded {@link KeySet} is malformed
// */
// public static KeySet load(byte[] encoded) throws CryptographicException {
// return load(new ByteArrayInputStream(encoded));
// }
//
// /**
// * Loads a {@link KeySet} from a {@link PGPSecretKeyRing}.
// */
// public static KeySet load(PGPSecretKeyRing keyRing) throws CryptographicException {
// final List<PGPSecretKey> secretKeys = Iterators.toList(keyRing.getSecretKeys());
// final MasterKey masterKey = MasterKey.load(secretKeys.get(0));
// final SubKey subKey = SubKey.load(secretKeys.get(1), masterKey);
//
// return new KeySet(masterKey, subKey);
// }
//
// /**
// * Loads a {@link KeySet} from an {@link InputStream}.
// */
// public static KeySet load(InputStream input) throws CryptographicException {
// try {
// final PGPSecretKeyRing keyRing = new PGPSecretKeyRing(input);
// input.close();
// return load(keyRing);
// } catch (IOException e) {
// throw new CryptographicException(e);
// } catch (PGPException e) {
// throw new CryptographicException(e);
// }
// }
//
// protected KeySet(MasterKey masterKey, SubKey subKey) {
// this.masterKey = masterKey;
// this.subKey = subKey;
// }
//
// /**
// * Returns the keyset's {@link MasterKey}.
// */
// public MasterKey getMasterKey() {
// return masterKey;
// }
//
// /**
// * Returns the keyset's {@link SubKey}.
// */
// public SubKey getSubKey() {
// return subKey;
// }
//
// /**
// * Returns the keyset's user ID.
// */
// public String getUserID() {
// return masterKey.getUserID();
// }
//
// /**
// * Writes the keyset in encoded form, to {@code output}.
// *
// * @param output an {@link OutputStream}
// * @throws IOException if there is an error writing to {@code output}
// */
// public void encode(OutputStream output) throws IOException {
// masterKey.getSecretKey().encode(output);
// subKey.getSecretKey().encode(output);
// }
//
// /**
// * Returns the keyset in encoded form.
// */
// public byte[] getEncoded() {
// final ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// encode(output);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// return output.toByteArray();
// }
//
// @Override
// public String toString() {
// return String.format("[%s, %s]", masterKey, subKey);
// }
//
// /**
// * Given the keyset's passphrase, unlocks the secret keys and returns an
// * {@link UnlockedKeySet} equivalent of {@code this}.
// *
// * @param passphrase the key's passphrase
// * @return a {@link UnlockedKeySet} equivalent of {@code this}
// * @throws CryptographicException if {@code passphrase} is incorrect
// */
// public UnlockedKeySet unlock(char[] passphrase) throws CryptographicException {
// final UnlockedMasterKey unlockedMasterKey = masterKey.unlock(passphrase);
// final UnlockedSubKey unlockedSubKey = subKey.unlock(passphrase);
// return new UnlockedKeySet(unlockedMasterKey, unlockedSubKey);
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/util/HashCode.java
// public class HashCode {
// private HashCode() {}
//
// public static int calculate(Object... objects) {
// return Arrays.deepHashCode(objects);
// }
// }
// Path: src/main/java/com/wesabe/grendel/entities/User.java
import static com.google.common.base.Objects.*;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.*;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.google.common.collect.Sets;
import com.wesabe.grendel.openpgp.CryptographicException;
import com.wesabe.grendel.openpgp.KeySet;
import com.wesabe.grendel.util.HashCode;
@Deprecated
public User() {
// blank constructor to be used by Hibernate
}
/**
* Creates a new Grendel user with a given {@link KeySet}.
*
* @param keySet the {@link KeySet} belonging to the user
*/
public User(KeySet keySet) {
setKeySet(keySet);
this.createdAt = new DateTime(DateTimeZone.UTC);
this.modifiedAt = new DateTime(DateTimeZone.UTC);
}
/**
* Returns the user's id.
*/
public String getId() {
return id;
}
/**
* Returns the user's {@link KeySet}.
*/
public KeySet getKeySet() {
if (keySet == null) {
try {
this.keySet = KeySet.load(encodedKeySet); | } catch (CryptographicException e) { |
wesabe/grendel | src/main/java/com/wesabe/grendel/entities/User.java | // Path: src/main/java/com/wesabe/grendel/openpgp/CryptographicException.java
// public class CryptographicException extends Exception {
// private static final long serialVersionUID = 7018291212808057570L;
//
// public CryptographicException(String message) {
// super(message);
// }
//
// public CryptographicException(Throwable cause) {
// super(cause);
// }
//
// public CryptographicException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/openpgp/KeySet.java
// public class KeySet {
// private final MasterKey masterKey;
// private final SubKey subKey;
//
// /**
// * Loads a {@link KeySet} from an array of bytes.
// *
// * @throws CryptographicException if the encoded {@link KeySet} is malformed
// */
// public static KeySet load(byte[] encoded) throws CryptographicException {
// return load(new ByteArrayInputStream(encoded));
// }
//
// /**
// * Loads a {@link KeySet} from a {@link PGPSecretKeyRing}.
// */
// public static KeySet load(PGPSecretKeyRing keyRing) throws CryptographicException {
// final List<PGPSecretKey> secretKeys = Iterators.toList(keyRing.getSecretKeys());
// final MasterKey masterKey = MasterKey.load(secretKeys.get(0));
// final SubKey subKey = SubKey.load(secretKeys.get(1), masterKey);
//
// return new KeySet(masterKey, subKey);
// }
//
// /**
// * Loads a {@link KeySet} from an {@link InputStream}.
// */
// public static KeySet load(InputStream input) throws CryptographicException {
// try {
// final PGPSecretKeyRing keyRing = new PGPSecretKeyRing(input);
// input.close();
// return load(keyRing);
// } catch (IOException e) {
// throw new CryptographicException(e);
// } catch (PGPException e) {
// throw new CryptographicException(e);
// }
// }
//
// protected KeySet(MasterKey masterKey, SubKey subKey) {
// this.masterKey = masterKey;
// this.subKey = subKey;
// }
//
// /**
// * Returns the keyset's {@link MasterKey}.
// */
// public MasterKey getMasterKey() {
// return masterKey;
// }
//
// /**
// * Returns the keyset's {@link SubKey}.
// */
// public SubKey getSubKey() {
// return subKey;
// }
//
// /**
// * Returns the keyset's user ID.
// */
// public String getUserID() {
// return masterKey.getUserID();
// }
//
// /**
// * Writes the keyset in encoded form, to {@code output}.
// *
// * @param output an {@link OutputStream}
// * @throws IOException if there is an error writing to {@code output}
// */
// public void encode(OutputStream output) throws IOException {
// masterKey.getSecretKey().encode(output);
// subKey.getSecretKey().encode(output);
// }
//
// /**
// * Returns the keyset in encoded form.
// */
// public byte[] getEncoded() {
// final ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// encode(output);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// return output.toByteArray();
// }
//
// @Override
// public String toString() {
// return String.format("[%s, %s]", masterKey, subKey);
// }
//
// /**
// * Given the keyset's passphrase, unlocks the secret keys and returns an
// * {@link UnlockedKeySet} equivalent of {@code this}.
// *
// * @param passphrase the key's passphrase
// * @return a {@link UnlockedKeySet} equivalent of {@code this}
// * @throws CryptographicException if {@code passphrase} is incorrect
// */
// public UnlockedKeySet unlock(char[] passphrase) throws CryptographicException {
// final UnlockedMasterKey unlockedMasterKey = masterKey.unlock(passphrase);
// final UnlockedSubKey unlockedSubKey = subKey.unlock(passphrase);
// return new UnlockedKeySet(unlockedMasterKey, unlockedSubKey);
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/util/HashCode.java
// public class HashCode {
// private HashCode() {}
//
// public static int calculate(Object... objects) {
// return Arrays.deepHashCode(objects);
// }
// }
| import static com.google.common.base.Objects.*;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.*;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.google.common.collect.Sets;
import com.wesabe.grendel.openpgp.CryptographicException;
import com.wesabe.grendel.openpgp.KeySet;
import com.wesabe.grendel.util.HashCode; | return toUTC(modifiedAt);
}
/**
* Sets a UTC timestamp of when this user was last modified.
*/
public void setModifiedAt(DateTime modifiedAt) {
this.modifiedAt = toUTC(modifiedAt);
}
/**
* Returns a set of the user's {@link Document}s.
*/
public Set<Document> getDocuments() {
return documents;
}
/**
* Returns a set of the user's linked {@link Document}s.
*/
public Set<Document> getLinkedDocuments() {
return linkedDocuments;
}
private DateTime toUTC(DateTime dateTime) {
return dateTime.toDateTime(DateTimeZone.UTC);
}
@Override
public int hashCode() { | // Path: src/main/java/com/wesabe/grendel/openpgp/CryptographicException.java
// public class CryptographicException extends Exception {
// private static final long serialVersionUID = 7018291212808057570L;
//
// public CryptographicException(String message) {
// super(message);
// }
//
// public CryptographicException(Throwable cause) {
// super(cause);
// }
//
// public CryptographicException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/openpgp/KeySet.java
// public class KeySet {
// private final MasterKey masterKey;
// private final SubKey subKey;
//
// /**
// * Loads a {@link KeySet} from an array of bytes.
// *
// * @throws CryptographicException if the encoded {@link KeySet} is malformed
// */
// public static KeySet load(byte[] encoded) throws CryptographicException {
// return load(new ByteArrayInputStream(encoded));
// }
//
// /**
// * Loads a {@link KeySet} from a {@link PGPSecretKeyRing}.
// */
// public static KeySet load(PGPSecretKeyRing keyRing) throws CryptographicException {
// final List<PGPSecretKey> secretKeys = Iterators.toList(keyRing.getSecretKeys());
// final MasterKey masterKey = MasterKey.load(secretKeys.get(0));
// final SubKey subKey = SubKey.load(secretKeys.get(1), masterKey);
//
// return new KeySet(masterKey, subKey);
// }
//
// /**
// * Loads a {@link KeySet} from an {@link InputStream}.
// */
// public static KeySet load(InputStream input) throws CryptographicException {
// try {
// final PGPSecretKeyRing keyRing = new PGPSecretKeyRing(input);
// input.close();
// return load(keyRing);
// } catch (IOException e) {
// throw new CryptographicException(e);
// } catch (PGPException e) {
// throw new CryptographicException(e);
// }
// }
//
// protected KeySet(MasterKey masterKey, SubKey subKey) {
// this.masterKey = masterKey;
// this.subKey = subKey;
// }
//
// /**
// * Returns the keyset's {@link MasterKey}.
// */
// public MasterKey getMasterKey() {
// return masterKey;
// }
//
// /**
// * Returns the keyset's {@link SubKey}.
// */
// public SubKey getSubKey() {
// return subKey;
// }
//
// /**
// * Returns the keyset's user ID.
// */
// public String getUserID() {
// return masterKey.getUserID();
// }
//
// /**
// * Writes the keyset in encoded form, to {@code output}.
// *
// * @param output an {@link OutputStream}
// * @throws IOException if there is an error writing to {@code output}
// */
// public void encode(OutputStream output) throws IOException {
// masterKey.getSecretKey().encode(output);
// subKey.getSecretKey().encode(output);
// }
//
// /**
// * Returns the keyset in encoded form.
// */
// public byte[] getEncoded() {
// final ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// encode(output);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// return output.toByteArray();
// }
//
// @Override
// public String toString() {
// return String.format("[%s, %s]", masterKey, subKey);
// }
//
// /**
// * Given the keyset's passphrase, unlocks the secret keys and returns an
// * {@link UnlockedKeySet} equivalent of {@code this}.
// *
// * @param passphrase the key's passphrase
// * @return a {@link UnlockedKeySet} equivalent of {@code this}
// * @throws CryptographicException if {@code passphrase} is incorrect
// */
// public UnlockedKeySet unlock(char[] passphrase) throws CryptographicException {
// final UnlockedMasterKey unlockedMasterKey = masterKey.unlock(passphrase);
// final UnlockedSubKey unlockedSubKey = subKey.unlock(passphrase);
// return new UnlockedKeySet(unlockedMasterKey, unlockedSubKey);
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/util/HashCode.java
// public class HashCode {
// private HashCode() {}
//
// public static int calculate(Object... objects) {
// return Arrays.deepHashCode(objects);
// }
// }
// Path: src/main/java/com/wesabe/grendel/entities/User.java
import static com.google.common.base.Objects.*;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.*;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.google.common.collect.Sets;
import com.wesabe.grendel.openpgp.CryptographicException;
import com.wesabe.grendel.openpgp.KeySet;
import com.wesabe.grendel.util.HashCode;
return toUTC(modifiedAt);
}
/**
* Sets a UTC timestamp of when this user was last modified.
*/
public void setModifiedAt(DateTime modifiedAt) {
this.modifiedAt = toUTC(modifiedAt);
}
/**
* Returns a set of the user's {@link Document}s.
*/
public Set<Document> getDocuments() {
return documents;
}
/**
* Returns a set of the user's linked {@link Document}s.
*/
public Set<Document> getLinkedDocuments() {
return linkedDocuments;
}
private DateTime toUTC(DateTime dateTime) {
return dateTime.toDateTime(DateTimeZone.UTC);
}
@Override
public int hashCode() { | return HashCode.calculate(createdAt, encodedKeySet, id, modifiedAt); |
wesabe/grendel | src/main/java/com/wesabe/grendel/entities/DocumentPK.java | // Path: src/main/java/com/wesabe/grendel/util/HashCode.java
// public class HashCode {
// private HashCode() {}
//
// public static int calculate(Object... objects) {
// return Arrays.deepHashCode(objects);
// }
// }
| import static com.google.common.base.Objects.equal;
import java.io.Serializable;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.ForeignKey;
import com.wesabe.grendel.util.HashCode; | package com.wesabe.grendel.entities;
/**
* A composite primary key for {@link Document}, consisting of an owner (a
* {@link User}) and a name (a {@link String}.
*
* @author coda
*/
public class DocumentPK implements Serializable {
private static final long serialVersionUID = -4514388507586009635L;
private String name;
@ManyToOne(fetch=FetchType.LAZY)
@ForeignKey(name="FK_DOCUMENT_TO_OWNER")
@JoinColumn(name="owner_id", nullable=false)
private User owner;
@Deprecated
public DocumentPK() {
// for Hibernate usage only
}
@Override
public int hashCode() { | // Path: src/main/java/com/wesabe/grendel/util/HashCode.java
// public class HashCode {
// private HashCode() {}
//
// public static int calculate(Object... objects) {
// return Arrays.deepHashCode(objects);
// }
// }
// Path: src/main/java/com/wesabe/grendel/entities/DocumentPK.java
import static com.google.common.base.Objects.equal;
import java.io.Serializable;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.ForeignKey;
import com.wesabe.grendel.util.HashCode;
package com.wesabe.grendel.entities;
/**
* A composite primary key for {@link Document}, consisting of an owner (a
* {@link User}) and a name (a {@link String}.
*
* @author coda
*/
public class DocumentPK implements Serializable {
private static final long serialVersionUID = -4514388507586009635L;
private String name;
@ManyToOne(fetch=FetchType.LAZY)
@ForeignKey(name="FK_DOCUMENT_TO_OWNER")
@JoinColumn(name="owner_id", nullable=false)
private User owner;
@Deprecated
public DocumentPK() {
// for Hibernate usage only
}
@Override
public int hashCode() { | return HashCode.calculate(getClass(), name, owner); |
wesabe/grendel | src/test/java/com/wesabe/grendel/openpgp/tests/CompressionAlgorithmTest.java | // Path: src/main/java/com/wesabe/grendel/openpgp/CompressionAlgorithm.java
// public enum CompressionAlgorithm implements IntegerEquivalent {
// /**
// * Uncompressed
// *
// * @deprecated Leaves messages vulnerable to adaptive chosen-plaintext
// * attacks.
// * @see <a href="http://www.cs.umd.edu/~jkatz/papers/pgp-attack.pdf">Implementation of Chosen-Ciphertext Attacks against PGP and GnuPG</a>
// */
// @Deprecated
// NONE( "None", CompressionAlgorithmTags.UNCOMPRESSED),
//
// /**
// * ZLIB
// *
// * @see <a href="http://www.ietf.org/rfc/rfc1951.txt">RFC 1951</a>
// */
// ZLIB( "ZLIB", CompressionAlgorithmTags.ZLIB),
//
// /**
// * ZIP
// *
// * @see <a href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</a>
// */
// ZIP( "ZIP", CompressionAlgorithmTags.ZIP),
//
// /**
// * BZip2
// *
// * @see <a href="http://www.bzip.org/">bzip.org</a>
// */
// BZIP2( "BZIP2", CompressionAlgorithmTags.BZIP2);
//
// /**
// * The default compression algorithm to use.
// */
// public static final CompressionAlgorithm DEFAULT = ZLIB;
//
// private final String name;
// private final int value;
//
// private CompressionAlgorithm(String name, int value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * Returns the equivalent value of {@link CompressionAlgorithmTags}.
// *
// */
// @Override
// public int toInteger() {
// return value;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
| import static org.fest.assertions.Assertions.*;
import org.bouncycastle.bcpg.CompressionAlgorithmTags;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.CompressionAlgorithm; | package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class CompressionAlgorithmTest {
@SuppressWarnings("deprecation")
public static class None {
@Test
public void itHasTheSameValueAsTheBCTag() throws Exception { | // Path: src/main/java/com/wesabe/grendel/openpgp/CompressionAlgorithm.java
// public enum CompressionAlgorithm implements IntegerEquivalent {
// /**
// * Uncompressed
// *
// * @deprecated Leaves messages vulnerable to adaptive chosen-plaintext
// * attacks.
// * @see <a href="http://www.cs.umd.edu/~jkatz/papers/pgp-attack.pdf">Implementation of Chosen-Ciphertext Attacks against PGP and GnuPG</a>
// */
// @Deprecated
// NONE( "None", CompressionAlgorithmTags.UNCOMPRESSED),
//
// /**
// * ZLIB
// *
// * @see <a href="http://www.ietf.org/rfc/rfc1951.txt">RFC 1951</a>
// */
// ZLIB( "ZLIB", CompressionAlgorithmTags.ZLIB),
//
// /**
// * ZIP
// *
// * @see <a href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</a>
// */
// ZIP( "ZIP", CompressionAlgorithmTags.ZIP),
//
// /**
// * BZip2
// *
// * @see <a href="http://www.bzip.org/">bzip.org</a>
// */
// BZIP2( "BZIP2", CompressionAlgorithmTags.BZIP2);
//
// /**
// * The default compression algorithm to use.
// */
// public static final CompressionAlgorithm DEFAULT = ZLIB;
//
// private final String name;
// private final int value;
//
// private CompressionAlgorithm(String name, int value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * Returns the equivalent value of {@link CompressionAlgorithmTags}.
// *
// */
// @Override
// public int toInteger() {
// return value;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// Path: src/test/java/com/wesabe/grendel/openpgp/tests/CompressionAlgorithmTest.java
import static org.fest.assertions.Assertions.*;
import org.bouncycastle.bcpg.CompressionAlgorithmTags;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.CompressionAlgorithm;
package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class CompressionAlgorithmTest {
@SuppressWarnings("deprecation")
public static class None {
@Test
public void itHasTheSameValueAsTheBCTag() throws Exception { | assertThat(CompressionAlgorithm.NONE.toInteger()).isEqualTo(CompressionAlgorithmTags.UNCOMPRESSED); |
wesabe/grendel | src/main/java/com/wesabe/grendel/openpgp/KeySetGenerator.java | // Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalents.java
// public final class IntegerEquivalents {
// private IntegerEquivalents() {}
//
// /**
// * Returns the collection of {@code integerEquivs} as an array of {@code int}s.
// */
// public static int[] toIntArray(Collection<? extends IntegerEquivalent> integerEquivs) {
// final int[] values = new int[integerEquivs.size()];
// int i = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// values[i] = integerEquiv.toInteger();
// i++;
// }
// return values;
// }
//
// /**
// * Returns the set of {@code integerEquivs} as a bitmask {@code int}.
// */
// public static int toBitmask(Set<? extends IntegerEquivalent> integerEquivs) {
// int value = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// value |= integerEquiv.toInteger();
// }
// return value;
// }
//
// /**
// * Returns the instance of {@code enumType} which is equivalent to
// * {@code value}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> T fromInt(Class<T> enumType, int value) throws IllegalArgumentException {
// for (T constant : enumType.getEnumConstants()) {
// if (constant.toInteger() == value) {
// return constant;
// }
// }
// throw new IllegalArgumentException("No enum constant of " + enumType + " exists with value " + value);
// }
//
// /**
// * Returns the list of the instances of {@code enumType} which are equivalent
// * to {@code values}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> List<T> fromIntArray(Class<T> enumType, int[] values) throws IllegalArgumentException {
// final ImmutableList.Builder<T> builder = ImmutableList.builder();
// for (int value : values) {
// builder.add(fromInt(enumType, value));
// }
// return builder.build();
// }
//
// /**
// * Returns the {@code bitMask} as a set of {@link IntegerEquivalent}s.
// */
// public static <T extends IntegerEquivalent> Set<T> fromBitmask(Class<T> enumType, int bitMask) throws IllegalArgumentException {
// final ImmutableSet.Builder<T> builder = ImmutableSet.builder();
// for (T constant : enumType.getEnumConstants()) {
// if ((bitMask & constant.toInteger()) != 0) {
// builder.add(constant);
// }
// }
// return builder.build();
// }
// }
| import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPKeyPair;
import org.bouncycastle.openpgp.PGPKeyRingGenerator;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator;
import org.bouncycastle.openpgp.PGPSignatureSubpacketVector;
import org.joda.time.DateTime;
import com.google.inject.Inject;
import com.google.inject.internal.ImmutableList;
import com.wesabe.grendel.util.IntegerEquivalents; | generateMasterKeySettings(),
null, // don't store any key settings unhashed
random,
"BC"
);
final PGPKeyPair subPGPKeyPair = new PGPKeyPair(
AsymmetricAlgorithm.ENCRYPTION_DEFAULT.toInteger(),
subKeyPair.get(),
new DateTime().toDate()
);
generator.addSubKey(subPGPKeyPair, generateSubKeySettings(), null);
final PGPSecretKeyRing keyRing = generator.generateSecretKeyRing();
return KeySet.load(keyRing);
} catch (GeneralSecurityException e) {
throw new CryptographicException(e);
} catch (PGPException e) {
throw new CryptographicException(e);
} catch (InterruptedException e) {
throw new CryptographicException(e);
} catch (ExecutionException e) {
throw new CryptographicException(e);
}
}
private PGPSignatureSubpacketVector generateSubKeySettings() {
final PGPSignatureSubpacketGenerator settings = new PGPSignatureSubpacketGenerator(); | // Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalents.java
// public final class IntegerEquivalents {
// private IntegerEquivalents() {}
//
// /**
// * Returns the collection of {@code integerEquivs} as an array of {@code int}s.
// */
// public static int[] toIntArray(Collection<? extends IntegerEquivalent> integerEquivs) {
// final int[] values = new int[integerEquivs.size()];
// int i = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// values[i] = integerEquiv.toInteger();
// i++;
// }
// return values;
// }
//
// /**
// * Returns the set of {@code integerEquivs} as a bitmask {@code int}.
// */
// public static int toBitmask(Set<? extends IntegerEquivalent> integerEquivs) {
// int value = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// value |= integerEquiv.toInteger();
// }
// return value;
// }
//
// /**
// * Returns the instance of {@code enumType} which is equivalent to
// * {@code value}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> T fromInt(Class<T> enumType, int value) throws IllegalArgumentException {
// for (T constant : enumType.getEnumConstants()) {
// if (constant.toInteger() == value) {
// return constant;
// }
// }
// throw new IllegalArgumentException("No enum constant of " + enumType + " exists with value " + value);
// }
//
// /**
// * Returns the list of the instances of {@code enumType} which are equivalent
// * to {@code values}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> List<T> fromIntArray(Class<T> enumType, int[] values) throws IllegalArgumentException {
// final ImmutableList.Builder<T> builder = ImmutableList.builder();
// for (int value : values) {
// builder.add(fromInt(enumType, value));
// }
// return builder.build();
// }
//
// /**
// * Returns the {@code bitMask} as a set of {@link IntegerEquivalent}s.
// */
// public static <T extends IntegerEquivalent> Set<T> fromBitmask(Class<T> enumType, int bitMask) throws IllegalArgumentException {
// final ImmutableSet.Builder<T> builder = ImmutableSet.builder();
// for (T constant : enumType.getEnumConstants()) {
// if ((bitMask & constant.toInteger()) != 0) {
// builder.add(constant);
// }
// }
// return builder.build();
// }
// }
// Path: src/main/java/com/wesabe/grendel/openpgp/KeySetGenerator.java
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPKeyPair;
import org.bouncycastle.openpgp.PGPKeyRingGenerator;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator;
import org.bouncycastle.openpgp.PGPSignatureSubpacketVector;
import org.joda.time.DateTime;
import com.google.inject.Inject;
import com.google.inject.internal.ImmutableList;
import com.wesabe.grendel.util.IntegerEquivalents;
generateMasterKeySettings(),
null, // don't store any key settings unhashed
random,
"BC"
);
final PGPKeyPair subPGPKeyPair = new PGPKeyPair(
AsymmetricAlgorithm.ENCRYPTION_DEFAULT.toInteger(),
subKeyPair.get(),
new DateTime().toDate()
);
generator.addSubKey(subPGPKeyPair, generateSubKeySettings(), null);
final PGPSecretKeyRing keyRing = generator.generateSecretKeyRing();
return KeySet.load(keyRing);
} catch (GeneralSecurityException e) {
throw new CryptographicException(e);
} catch (PGPException e) {
throw new CryptographicException(e);
} catch (InterruptedException e) {
throw new CryptographicException(e);
} catch (ExecutionException e) {
throw new CryptographicException(e);
}
}
private PGPSignatureSubpacketVector generateSubKeySettings() {
final PGPSignatureSubpacketGenerator settings = new PGPSignatureSubpacketGenerator(); | settings.setKeyFlags(false, IntegerEquivalents.toBitmask(KeyFlag.SUB_KEY_DEFAULTS)); |
wesabe/grendel | src/test/java/com/wesabe/grendel/representations/tests/ValidationExceptionTest.java | // Path: src/main/java/com/wesabe/grendel/representations/ValidationException.java
// public class ValidationException extends WebApplicationException {
// private static final int UNPROCESSABLE_ENTITY = 422;
// private static final long serialVersionUID = -6730797215368434430L;
// private final StringBuilder msgBuilder;
// private boolean hasReasons = false;
//
// public ValidationException() {
// super();
// this.msgBuilder = new StringBuilder(
// "Grendel was unable to process your request for the following reason(s):\n\n"
// );
// }
//
// /**
// * Adds a reason for validation failure to the list.
// */
// public void addReason(String reason) {
// this.hasReasons = true;
// msgBuilder.append("* ").append(reason).append('\n');
// }
//
// /**
// * Adds a failure to include a required property to the list.
// */
// public void missingRequiredProperty(String propertyName) {
// addReason("missing required property: " + propertyName);
// }
//
// /**
// * Returns {@code true} if the exception has reasons, {@code false}
// * otherwise.
// */
// public boolean hasReasons() {
// return hasReasons;
// }
//
// @Override
// public Response getResponse() {
// return Response
// .status(UNPROCESSABLE_ENTITY)
// .type(MediaType.TEXT_PLAIN)
// .entity(msgBuilder.toString())
// .build();
// }
// }
| import static org.fest.assertions.Assertions.*;
import javax.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.representations.ValidationException; | package com.wesabe.grendel.representations.tests;
@RunWith(Enclosed.class)
public class ValidationExceptionTest {
public static class Throwing_A_Validation_Exception { | // Path: src/main/java/com/wesabe/grendel/representations/ValidationException.java
// public class ValidationException extends WebApplicationException {
// private static final int UNPROCESSABLE_ENTITY = 422;
// private static final long serialVersionUID = -6730797215368434430L;
// private final StringBuilder msgBuilder;
// private boolean hasReasons = false;
//
// public ValidationException() {
// super();
// this.msgBuilder = new StringBuilder(
// "Grendel was unable to process your request for the following reason(s):\n\n"
// );
// }
//
// /**
// * Adds a reason for validation failure to the list.
// */
// public void addReason(String reason) {
// this.hasReasons = true;
// msgBuilder.append("* ").append(reason).append('\n');
// }
//
// /**
// * Adds a failure to include a required property to the list.
// */
// public void missingRequiredProperty(String propertyName) {
// addReason("missing required property: " + propertyName);
// }
//
// /**
// * Returns {@code true} if the exception has reasons, {@code false}
// * otherwise.
// */
// public boolean hasReasons() {
// return hasReasons;
// }
//
// @Override
// public Response getResponse() {
// return Response
// .status(UNPROCESSABLE_ENTITY)
// .type(MediaType.TEXT_PLAIN)
// .entity(msgBuilder.toString())
// .build();
// }
// }
// Path: src/test/java/com/wesabe/grendel/representations/tests/ValidationExceptionTest.java
import static org.fest.assertions.Assertions.*;
import javax.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.representations.ValidationException;
package com.wesabe.grendel.representations.tests;
@RunWith(Enclosed.class)
public class ValidationExceptionTest {
public static class Throwing_A_Validation_Exception { | private ValidationException e; |
wesabe/grendel | src/test/java/com/wesabe/grendel/openpgp/tests/SymmetricAlgorithmTest.java | // Path: src/main/java/com/wesabe/grendel/openpgp/SymmetricAlgorithm.java
// public enum SymmetricAlgorithm implements IntegerEquivalent {
// /**
// * Plaintext or unencrypted data
// *
// * @deprecated Do not store unencrypted data.
// */
// @Deprecated
// PLAINTEXT( "Plaintext", SymmetricKeyAlgorithmTags.NULL),
//
// /**
// * IDEA
// *
// * @deprecated Encumbered by patents.
// */
// @Deprecated
// IDEA( "IDEA", SymmetricKeyAlgorithmTags.IDEA),
//
// /**
// * TripleDES (DES-EDE, 168 bit key derived from 192)
// *
// * @deprecated Replaced by AES.
// */
// @Deprecated
// TRIPLE_DES( "3DES", SymmetricKeyAlgorithmTags.TRIPLE_DES),
//
// /**
// * CAST-128 (also known as CAST5)
// *
// * @deprecated
// * @see <a href="http://www.ietf.org/rfc/rfc2144.txt">RFC 2144</a>
// */
// @Deprecated
// CAST_128( "CAST-128", SymmetricKeyAlgorithmTags.CAST5),
//
// /**
// * Blowfish (128 bit key, 16 rounds)
// *
// * @deprecated
// */
// @Deprecated
// BLOWFISH( "Blowfish", SymmetricKeyAlgorithmTags.BLOWFISH),
//
// /**
// * SAFER-SK (128 bit key, 13 rounds)
// *
// * @deprecated Not specified by RFC 4880.
// */
// @Deprecated
// SAFER_SK( "SAFER-SK", SymmetricKeyAlgorithmTags.SAFER),
//
// /**
// * DES (56 bit key)
// *
// * @deprecated Not specified by RFC 4880.
// */
// @Deprecated
// DES( "DES", SymmetricKeyAlgorithmTags.DES),
//
// /**
// * AES with 128-bit key
// */
// AES_128( "AES-128", SymmetricKeyAlgorithmTags.AES_128),
//
// /**
// * AES with 192-bit key
// */
// AES_192( "AES-192", SymmetricKeyAlgorithmTags.AES_192),
//
// /**
// * AES with 256-bit key
// */
// AES_256( "AES-256", SymmetricKeyAlgorithmTags.AES_256),
//
// /**
// * Twofish with 256-bit key
// *
// * @deprecated
// */
// @Deprecated
// TWOFISH( "Twofish", SymmetricKeyAlgorithmTags.TWOFISH);
//
// /**
// * The default symmetric algorithm to use.
// */
// public static final SymmetricAlgorithm DEFAULT = AES_256;
//
// /**
// * A list of symmetric algorithms which are acceptable for use in Grendel.
// */
// public static final List<SymmetricAlgorithm> ACCEPTABLE_ALGORITHMS = ImmutableList.of(AES_128, AES_192, AES_256);
//
// private final String name;
// private final int value;
//
// private SymmetricAlgorithm(String name, int value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * Returns the equivalent value of {@link SymmetricKeyAlgorithmTags}.
// */
// @Override
// public int toInteger() {
// return value;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
| import static org.fest.assertions.Assertions.*;
import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.google.common.collect.ImmutableList;
import com.wesabe.grendel.openpgp.SymmetricAlgorithm; | package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class SymmetricAlgorithmTest {
@SuppressWarnings("deprecation")
public static class Plaintext {
@Test
public void itHasTheSameValueAsTheBCTag() throws Exception { | // Path: src/main/java/com/wesabe/grendel/openpgp/SymmetricAlgorithm.java
// public enum SymmetricAlgorithm implements IntegerEquivalent {
// /**
// * Plaintext or unencrypted data
// *
// * @deprecated Do not store unencrypted data.
// */
// @Deprecated
// PLAINTEXT( "Plaintext", SymmetricKeyAlgorithmTags.NULL),
//
// /**
// * IDEA
// *
// * @deprecated Encumbered by patents.
// */
// @Deprecated
// IDEA( "IDEA", SymmetricKeyAlgorithmTags.IDEA),
//
// /**
// * TripleDES (DES-EDE, 168 bit key derived from 192)
// *
// * @deprecated Replaced by AES.
// */
// @Deprecated
// TRIPLE_DES( "3DES", SymmetricKeyAlgorithmTags.TRIPLE_DES),
//
// /**
// * CAST-128 (also known as CAST5)
// *
// * @deprecated
// * @see <a href="http://www.ietf.org/rfc/rfc2144.txt">RFC 2144</a>
// */
// @Deprecated
// CAST_128( "CAST-128", SymmetricKeyAlgorithmTags.CAST5),
//
// /**
// * Blowfish (128 bit key, 16 rounds)
// *
// * @deprecated
// */
// @Deprecated
// BLOWFISH( "Blowfish", SymmetricKeyAlgorithmTags.BLOWFISH),
//
// /**
// * SAFER-SK (128 bit key, 13 rounds)
// *
// * @deprecated Not specified by RFC 4880.
// */
// @Deprecated
// SAFER_SK( "SAFER-SK", SymmetricKeyAlgorithmTags.SAFER),
//
// /**
// * DES (56 bit key)
// *
// * @deprecated Not specified by RFC 4880.
// */
// @Deprecated
// DES( "DES", SymmetricKeyAlgorithmTags.DES),
//
// /**
// * AES with 128-bit key
// */
// AES_128( "AES-128", SymmetricKeyAlgorithmTags.AES_128),
//
// /**
// * AES with 192-bit key
// */
// AES_192( "AES-192", SymmetricKeyAlgorithmTags.AES_192),
//
// /**
// * AES with 256-bit key
// */
// AES_256( "AES-256", SymmetricKeyAlgorithmTags.AES_256),
//
// /**
// * Twofish with 256-bit key
// *
// * @deprecated
// */
// @Deprecated
// TWOFISH( "Twofish", SymmetricKeyAlgorithmTags.TWOFISH);
//
// /**
// * The default symmetric algorithm to use.
// */
// public static final SymmetricAlgorithm DEFAULT = AES_256;
//
// /**
// * A list of symmetric algorithms which are acceptable for use in Grendel.
// */
// public static final List<SymmetricAlgorithm> ACCEPTABLE_ALGORITHMS = ImmutableList.of(AES_128, AES_192, AES_256);
//
// private final String name;
// private final int value;
//
// private SymmetricAlgorithm(String name, int value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * Returns the equivalent value of {@link SymmetricKeyAlgorithmTags}.
// */
// @Override
// public int toInteger() {
// return value;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// Path: src/test/java/com/wesabe/grendel/openpgp/tests/SymmetricAlgorithmTest.java
import static org.fest.assertions.Assertions.*;
import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.google.common.collect.ImmutableList;
import com.wesabe.grendel.openpgp.SymmetricAlgorithm;
package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class SymmetricAlgorithmTest {
@SuppressWarnings("deprecation")
public static class Plaintext {
@Test
public void itHasTheSameValueAsTheBCTag() throws Exception { | assertThat(SymmetricAlgorithm.PLAINTEXT.toInteger()).isEqualTo(SymmetricKeyAlgorithmTags.NULL); |
wesabe/grendel | src/test/java/com/wesabe/grendel/util/tests/IntegerEquivalentsTest.java | // Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalent.java
// public interface IntegerEquivalent {
// /**
// * Returns the object as an integer.
// */
// public abstract int toInteger();
// }
//
// Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalents.java
// public final class IntegerEquivalents {
// private IntegerEquivalents() {}
//
// /**
// * Returns the collection of {@code integerEquivs} as an array of {@code int}s.
// */
// public static int[] toIntArray(Collection<? extends IntegerEquivalent> integerEquivs) {
// final int[] values = new int[integerEquivs.size()];
// int i = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// values[i] = integerEquiv.toInteger();
// i++;
// }
// return values;
// }
//
// /**
// * Returns the set of {@code integerEquivs} as a bitmask {@code int}.
// */
// public static int toBitmask(Set<? extends IntegerEquivalent> integerEquivs) {
// int value = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// value |= integerEquiv.toInteger();
// }
// return value;
// }
//
// /**
// * Returns the instance of {@code enumType} which is equivalent to
// * {@code value}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> T fromInt(Class<T> enumType, int value) throws IllegalArgumentException {
// for (T constant : enumType.getEnumConstants()) {
// if (constant.toInteger() == value) {
// return constant;
// }
// }
// throw new IllegalArgumentException("No enum constant of " + enumType + " exists with value " + value);
// }
//
// /**
// * Returns the list of the instances of {@code enumType} which are equivalent
// * to {@code values}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> List<T> fromIntArray(Class<T> enumType, int[] values) throws IllegalArgumentException {
// final ImmutableList.Builder<T> builder = ImmutableList.builder();
// for (int value : values) {
// builder.add(fromInt(enumType, value));
// }
// return builder.build();
// }
//
// /**
// * Returns the {@code bitMask} as a set of {@link IntegerEquivalent}s.
// */
// public static <T extends IntegerEquivalent> Set<T> fromBitmask(Class<T> enumType, int bitMask) throws IllegalArgumentException {
// final ImmutableSet.Builder<T> builder = ImmutableSet.builder();
// for (T constant : enumType.getEnumConstants()) {
// if ((bitMask & constant.toInteger()) != 0) {
// builder.add(constant);
// }
// }
// return builder.build();
// }
// }
| import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.google.common.collect.ImmutableSet;
import com.google.inject.internal.ImmutableList;
import com.wesabe.grendel.util.IntegerEquivalent;
import com.wesabe.grendel.util.IntegerEquivalents; | package com.wesabe.grendel.util.tests;
@RunWith(Enclosed.class)
public class IntegerEquivalentsTest {
@Ignore | // Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalent.java
// public interface IntegerEquivalent {
// /**
// * Returns the object as an integer.
// */
// public abstract int toInteger();
// }
//
// Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalents.java
// public final class IntegerEquivalents {
// private IntegerEquivalents() {}
//
// /**
// * Returns the collection of {@code integerEquivs} as an array of {@code int}s.
// */
// public static int[] toIntArray(Collection<? extends IntegerEquivalent> integerEquivs) {
// final int[] values = new int[integerEquivs.size()];
// int i = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// values[i] = integerEquiv.toInteger();
// i++;
// }
// return values;
// }
//
// /**
// * Returns the set of {@code integerEquivs} as a bitmask {@code int}.
// */
// public static int toBitmask(Set<? extends IntegerEquivalent> integerEquivs) {
// int value = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// value |= integerEquiv.toInteger();
// }
// return value;
// }
//
// /**
// * Returns the instance of {@code enumType} which is equivalent to
// * {@code value}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> T fromInt(Class<T> enumType, int value) throws IllegalArgumentException {
// for (T constant : enumType.getEnumConstants()) {
// if (constant.toInteger() == value) {
// return constant;
// }
// }
// throw new IllegalArgumentException("No enum constant of " + enumType + " exists with value " + value);
// }
//
// /**
// * Returns the list of the instances of {@code enumType} which are equivalent
// * to {@code values}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> List<T> fromIntArray(Class<T> enumType, int[] values) throws IllegalArgumentException {
// final ImmutableList.Builder<T> builder = ImmutableList.builder();
// for (int value : values) {
// builder.add(fromInt(enumType, value));
// }
// return builder.build();
// }
//
// /**
// * Returns the {@code bitMask} as a set of {@link IntegerEquivalent}s.
// */
// public static <T extends IntegerEquivalent> Set<T> fromBitmask(Class<T> enumType, int bitMask) throws IllegalArgumentException {
// final ImmutableSet.Builder<T> builder = ImmutableSet.builder();
// for (T constant : enumType.getEnumConstants()) {
// if ((bitMask & constant.toInteger()) != 0) {
// builder.add(constant);
// }
// }
// return builder.build();
// }
// }
// Path: src/test/java/com/wesabe/grendel/util/tests/IntegerEquivalentsTest.java
import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.google.common.collect.ImmutableSet;
import com.google.inject.internal.ImmutableList;
import com.wesabe.grendel.util.IntegerEquivalent;
import com.wesabe.grendel.util.IntegerEquivalents;
package com.wesabe.grendel.util.tests;
@RunWith(Enclosed.class)
public class IntegerEquivalentsTest {
@Ignore | public static enum Letter implements IntegerEquivalent { |
wesabe/grendel | src/test/java/com/wesabe/grendel/util/tests/IntegerEquivalentsTest.java | // Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalent.java
// public interface IntegerEquivalent {
// /**
// * Returns the object as an integer.
// */
// public abstract int toInteger();
// }
//
// Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalents.java
// public final class IntegerEquivalents {
// private IntegerEquivalents() {}
//
// /**
// * Returns the collection of {@code integerEquivs} as an array of {@code int}s.
// */
// public static int[] toIntArray(Collection<? extends IntegerEquivalent> integerEquivs) {
// final int[] values = new int[integerEquivs.size()];
// int i = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// values[i] = integerEquiv.toInteger();
// i++;
// }
// return values;
// }
//
// /**
// * Returns the set of {@code integerEquivs} as a bitmask {@code int}.
// */
// public static int toBitmask(Set<? extends IntegerEquivalent> integerEquivs) {
// int value = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// value |= integerEquiv.toInteger();
// }
// return value;
// }
//
// /**
// * Returns the instance of {@code enumType} which is equivalent to
// * {@code value}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> T fromInt(Class<T> enumType, int value) throws IllegalArgumentException {
// for (T constant : enumType.getEnumConstants()) {
// if (constant.toInteger() == value) {
// return constant;
// }
// }
// throw new IllegalArgumentException("No enum constant of " + enumType + " exists with value " + value);
// }
//
// /**
// * Returns the list of the instances of {@code enumType} which are equivalent
// * to {@code values}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> List<T> fromIntArray(Class<T> enumType, int[] values) throws IllegalArgumentException {
// final ImmutableList.Builder<T> builder = ImmutableList.builder();
// for (int value : values) {
// builder.add(fromInt(enumType, value));
// }
// return builder.build();
// }
//
// /**
// * Returns the {@code bitMask} as a set of {@link IntegerEquivalent}s.
// */
// public static <T extends IntegerEquivalent> Set<T> fromBitmask(Class<T> enumType, int bitMask) throws IllegalArgumentException {
// final ImmutableSet.Builder<T> builder = ImmutableSet.builder();
// for (T constant : enumType.getEnumConstants()) {
// if ((bitMask & constant.toInteger()) != 0) {
// builder.add(constant);
// }
// }
// return builder.build();
// }
// }
| import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.google.common.collect.ImmutableSet;
import com.google.inject.internal.ImmutableList;
import com.wesabe.grendel.util.IntegerEquivalent;
import com.wesabe.grendel.util.IntegerEquivalents; | package com.wesabe.grendel.util.tests;
@RunWith(Enclosed.class)
public class IntegerEquivalentsTest {
@Ignore
public static enum Letter implements IntegerEquivalent {
A(1), B(2), C(4);
private final int value;
private Letter(int value) {
this.value = value;
}
@Override
public int toInteger() {
return value;
}
}
public static class Converting_A_Collection_Of_Integer_Equivalents_To_An_Array_Of_Ints {
@Test
public void itReturnsAnArrayOfInts() throws Exception { | // Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalent.java
// public interface IntegerEquivalent {
// /**
// * Returns the object as an integer.
// */
// public abstract int toInteger();
// }
//
// Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalents.java
// public final class IntegerEquivalents {
// private IntegerEquivalents() {}
//
// /**
// * Returns the collection of {@code integerEquivs} as an array of {@code int}s.
// */
// public static int[] toIntArray(Collection<? extends IntegerEquivalent> integerEquivs) {
// final int[] values = new int[integerEquivs.size()];
// int i = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// values[i] = integerEquiv.toInteger();
// i++;
// }
// return values;
// }
//
// /**
// * Returns the set of {@code integerEquivs} as a bitmask {@code int}.
// */
// public static int toBitmask(Set<? extends IntegerEquivalent> integerEquivs) {
// int value = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// value |= integerEquiv.toInteger();
// }
// return value;
// }
//
// /**
// * Returns the instance of {@code enumType} which is equivalent to
// * {@code value}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> T fromInt(Class<T> enumType, int value) throws IllegalArgumentException {
// for (T constant : enumType.getEnumConstants()) {
// if (constant.toInteger() == value) {
// return constant;
// }
// }
// throw new IllegalArgumentException("No enum constant of " + enumType + " exists with value " + value);
// }
//
// /**
// * Returns the list of the instances of {@code enumType} which are equivalent
// * to {@code values}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> List<T> fromIntArray(Class<T> enumType, int[] values) throws IllegalArgumentException {
// final ImmutableList.Builder<T> builder = ImmutableList.builder();
// for (int value : values) {
// builder.add(fromInt(enumType, value));
// }
// return builder.build();
// }
//
// /**
// * Returns the {@code bitMask} as a set of {@link IntegerEquivalent}s.
// */
// public static <T extends IntegerEquivalent> Set<T> fromBitmask(Class<T> enumType, int bitMask) throws IllegalArgumentException {
// final ImmutableSet.Builder<T> builder = ImmutableSet.builder();
// for (T constant : enumType.getEnumConstants()) {
// if ((bitMask & constant.toInteger()) != 0) {
// builder.add(constant);
// }
// }
// return builder.build();
// }
// }
// Path: src/test/java/com/wesabe/grendel/util/tests/IntegerEquivalentsTest.java
import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.google.common.collect.ImmutableSet;
import com.google.inject.internal.ImmutableList;
import com.wesabe.grendel.util.IntegerEquivalent;
import com.wesabe.grendel.util.IntegerEquivalents;
package com.wesabe.grendel.util.tests;
@RunWith(Enclosed.class)
public class IntegerEquivalentsTest {
@Ignore
public static enum Letter implements IntegerEquivalent {
A(1), B(2), C(4);
private final int value;
private Letter(int value) {
this.value = value;
}
@Override
public int toInteger() {
return value;
}
}
public static class Converting_A_Collection_Of_Integer_Equivalents_To_An_Array_Of_Ints {
@Test
public void itReturnsAnArrayOfInts() throws Exception { | assertThat(IntegerEquivalents.toIntArray(ImmutableList.of(Letter.A, Letter.C))).isEqualTo(new int[] { 1, 4 }); |
wesabe/grendel | src/test/java/com/wesabe/grendel/util/tests/HashCodeTest.java | // Path: src/main/java/com/wesabe/grendel/util/HashCode.java
// public class HashCode {
// private HashCode() {}
//
// public static int calculate(Object... objects) {
// return Arrays.deepHashCode(objects);
// }
// }
| import static org.fest.assertions.Assertions.*;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.util.HashCode; | package com.wesabe.grendel.util.tests;
@RunWith(Enclosed.class)
public class HashCodeTest {
public static class Calculating_A_Hash_Code {
@Test
public void itHandlesNullValues() throws Exception { | // Path: src/main/java/com/wesabe/grendel/util/HashCode.java
// public class HashCode {
// private HashCode() {}
//
// public static int calculate(Object... objects) {
// return Arrays.deepHashCode(objects);
// }
// }
// Path: src/test/java/com/wesabe/grendel/util/tests/HashCodeTest.java
import static org.fest.assertions.Assertions.*;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.util.HashCode;
package com.wesabe.grendel.util.tests;
@RunWith(Enclosed.class)
public class HashCodeTest {
public static class Calculating_A_Hash_Code {
@Test
public void itHandlesNullValues() throws Exception { | assertThat(HashCode.calculate(null, null)).isEqualTo(961); |
wesabe/grendel | src/test/java/com/wesabe/grendel/auth/tests/BasicAuthProviderTest.java | // Path: src/main/java/com/wesabe/grendel/auth/BasicAuthProvider.java
// @Provider
// public class BasicAuthProvider extends AbstractInjectionProvider<Credentials> {
// private static final String HEADER_PREFIX = "Basic ";
// private static final char CREDENTIAL_DELIMITER = ':';
//
// public BasicAuthProvider() {
// super(Credentials.class);
// }
//
// @Override
// public Credentials getValue(HttpContext context) {
// String header = context.getRequest().getHeaderValue(HttpHeaders.AUTHORIZATION);
// try {
// try {
// if ((header != null) && header.startsWith(HEADER_PREFIX)) {
// final String encoded = header.substring(header.indexOf(' ') + 1);
// final String credentials = B64Code.decode(encoded, StringUtil.__ISO_8859_1);
// final int i = credentials.indexOf(CREDENTIAL_DELIMITER);
//
// final String username = credentials.substring(0, i);
// final String password = credentials.substring(i + 1);
//
// if ((username != null) && (password != null)) {
// return new Credentials(username, password);
// }
// }
// } catch (IllegalArgumentException e) {
// // fall through to sending an auth challenge
// } catch (StringIndexOutOfBoundsException e) {
// // fall through to sending an auth challenge
// }
//
// throw new WebApplicationException(Credentials.CHALLENGE);
// } catch (WebApplicationException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/auth/Credentials.java
// public class Credentials {
// /**
// * An authentication challenge {@link Response}. Use this when a client's
// * provided credentials are invalid.
// */
// public static final Response CHALLENGE =
// Response.status(Status.UNAUTHORIZED)
// .header(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Grendel\"")
// .build();
//
// private final String username;
// private final String password;
//
// /**
// * Creates a new set of credentials.
// *
// * @param username the client's provided username
// * @param password the client's provided password
// */
// public Credentials(String username, String password) {
// this.username = username;
// this.password = password;
// }
//
// /**
// * Returns the client's provided username.
// */
// public String getUsername() {
// return username;
// }
//
// /**
// * Returns the client's provided password.
// */
// public String getPassword() {
// return password;
// }
//
// /**
// * Given a {@link UserDAO}, finds the associated {@link User} and returns a
// * {@link Session}.
// *
// * @param userDAO
// * a {@link UserDAO}
// * @throws WebApplicationException
// * if the user can't be found, or if the user's password is
// * incorrect
// */
// public Session buildSession(UserDAO userDAO) throws WebApplicationException {
// final User user = userDAO.findById(username);
// if (user != null) {
// try {
// final UnlockedKeySet keySet = user.getKeySet().unlock(password.toCharArray());
// return new Session(user, keySet);
// } catch (CryptographicException e) {
// throw new WebApplicationException(CHALLENGE);
// }
// }
//
// throw new WebApplicationException(CHALLENGE);
// }
//
// /**
// * Given a {@link UserDAO} and an allowed {@link User} id, finds the
// * associated {@link User} and returns a {@link Session}.
// *
// * @param userDAO
// * a {@link UserDAO}
// * @param allowedId
// * the id of the only {@link User} which should be allowed access
// * to session context
// * @throws WebApplicationException
// * if the user can't be found, or if the user's password is
// * incorrect
// */
// public Session buildSession(UserDAO userDAO, String allowedId) {
// final Session session = buildSession(userDAO);
// if (session.getUser().getId().equals(allowedId)) {
// return session;
// }
//
// throw new WebApplicationException(Status.FORBIDDEN);
// }
// }
| import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.HttpHeaders;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.sun.jersey.api.core.HttpContext;
import com.sun.jersey.api.core.HttpRequestContext;
import com.wesabe.grendel.auth.BasicAuthProvider;
import com.wesabe.grendel.auth.Credentials; | package com.wesabe.grendel.auth.tests;
@RunWith(Enclosed.class)
public class BasicAuthProviderTest {
private static abstract class Context {
protected HttpContext context;
protected HttpRequestContext request; | // Path: src/main/java/com/wesabe/grendel/auth/BasicAuthProvider.java
// @Provider
// public class BasicAuthProvider extends AbstractInjectionProvider<Credentials> {
// private static final String HEADER_PREFIX = "Basic ";
// private static final char CREDENTIAL_DELIMITER = ':';
//
// public BasicAuthProvider() {
// super(Credentials.class);
// }
//
// @Override
// public Credentials getValue(HttpContext context) {
// String header = context.getRequest().getHeaderValue(HttpHeaders.AUTHORIZATION);
// try {
// try {
// if ((header != null) && header.startsWith(HEADER_PREFIX)) {
// final String encoded = header.substring(header.indexOf(' ') + 1);
// final String credentials = B64Code.decode(encoded, StringUtil.__ISO_8859_1);
// final int i = credentials.indexOf(CREDENTIAL_DELIMITER);
//
// final String username = credentials.substring(0, i);
// final String password = credentials.substring(i + 1);
//
// if ((username != null) && (password != null)) {
// return new Credentials(username, password);
// }
// }
// } catch (IllegalArgumentException e) {
// // fall through to sending an auth challenge
// } catch (StringIndexOutOfBoundsException e) {
// // fall through to sending an auth challenge
// }
//
// throw new WebApplicationException(Credentials.CHALLENGE);
// } catch (WebApplicationException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/auth/Credentials.java
// public class Credentials {
// /**
// * An authentication challenge {@link Response}. Use this when a client's
// * provided credentials are invalid.
// */
// public static final Response CHALLENGE =
// Response.status(Status.UNAUTHORIZED)
// .header(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Grendel\"")
// .build();
//
// private final String username;
// private final String password;
//
// /**
// * Creates a new set of credentials.
// *
// * @param username the client's provided username
// * @param password the client's provided password
// */
// public Credentials(String username, String password) {
// this.username = username;
// this.password = password;
// }
//
// /**
// * Returns the client's provided username.
// */
// public String getUsername() {
// return username;
// }
//
// /**
// * Returns the client's provided password.
// */
// public String getPassword() {
// return password;
// }
//
// /**
// * Given a {@link UserDAO}, finds the associated {@link User} and returns a
// * {@link Session}.
// *
// * @param userDAO
// * a {@link UserDAO}
// * @throws WebApplicationException
// * if the user can't be found, or if the user's password is
// * incorrect
// */
// public Session buildSession(UserDAO userDAO) throws WebApplicationException {
// final User user = userDAO.findById(username);
// if (user != null) {
// try {
// final UnlockedKeySet keySet = user.getKeySet().unlock(password.toCharArray());
// return new Session(user, keySet);
// } catch (CryptographicException e) {
// throw new WebApplicationException(CHALLENGE);
// }
// }
//
// throw new WebApplicationException(CHALLENGE);
// }
//
// /**
// * Given a {@link UserDAO} and an allowed {@link User} id, finds the
// * associated {@link User} and returns a {@link Session}.
// *
// * @param userDAO
// * a {@link UserDAO}
// * @param allowedId
// * the id of the only {@link User} which should be allowed access
// * to session context
// * @throws WebApplicationException
// * if the user can't be found, or if the user's password is
// * incorrect
// */
// public Session buildSession(UserDAO userDAO, String allowedId) {
// final Session session = buildSession(userDAO);
// if (session.getUser().getId().equals(allowedId)) {
// return session;
// }
//
// throw new WebApplicationException(Status.FORBIDDEN);
// }
// }
// Path: src/test/java/com/wesabe/grendel/auth/tests/BasicAuthProviderTest.java
import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.HttpHeaders;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.sun.jersey.api.core.HttpContext;
import com.sun.jersey.api.core.HttpRequestContext;
import com.wesabe.grendel.auth.BasicAuthProvider;
import com.wesabe.grendel.auth.Credentials;
package com.wesabe.grendel.auth.tests;
@RunWith(Enclosed.class)
public class BasicAuthProviderTest {
private static abstract class Context {
protected HttpContext context;
protected HttpRequestContext request; | protected BasicAuthProvider provider; |
wesabe/grendel | src/test/java/com/wesabe/grendel/auth/tests/BasicAuthProviderTest.java | // Path: src/main/java/com/wesabe/grendel/auth/BasicAuthProvider.java
// @Provider
// public class BasicAuthProvider extends AbstractInjectionProvider<Credentials> {
// private static final String HEADER_PREFIX = "Basic ";
// private static final char CREDENTIAL_DELIMITER = ':';
//
// public BasicAuthProvider() {
// super(Credentials.class);
// }
//
// @Override
// public Credentials getValue(HttpContext context) {
// String header = context.getRequest().getHeaderValue(HttpHeaders.AUTHORIZATION);
// try {
// try {
// if ((header != null) && header.startsWith(HEADER_PREFIX)) {
// final String encoded = header.substring(header.indexOf(' ') + 1);
// final String credentials = B64Code.decode(encoded, StringUtil.__ISO_8859_1);
// final int i = credentials.indexOf(CREDENTIAL_DELIMITER);
//
// final String username = credentials.substring(0, i);
// final String password = credentials.substring(i + 1);
//
// if ((username != null) && (password != null)) {
// return new Credentials(username, password);
// }
// }
// } catch (IllegalArgumentException e) {
// // fall through to sending an auth challenge
// } catch (StringIndexOutOfBoundsException e) {
// // fall through to sending an auth challenge
// }
//
// throw new WebApplicationException(Credentials.CHALLENGE);
// } catch (WebApplicationException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/auth/Credentials.java
// public class Credentials {
// /**
// * An authentication challenge {@link Response}. Use this when a client's
// * provided credentials are invalid.
// */
// public static final Response CHALLENGE =
// Response.status(Status.UNAUTHORIZED)
// .header(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Grendel\"")
// .build();
//
// private final String username;
// private final String password;
//
// /**
// * Creates a new set of credentials.
// *
// * @param username the client's provided username
// * @param password the client's provided password
// */
// public Credentials(String username, String password) {
// this.username = username;
// this.password = password;
// }
//
// /**
// * Returns the client's provided username.
// */
// public String getUsername() {
// return username;
// }
//
// /**
// * Returns the client's provided password.
// */
// public String getPassword() {
// return password;
// }
//
// /**
// * Given a {@link UserDAO}, finds the associated {@link User} and returns a
// * {@link Session}.
// *
// * @param userDAO
// * a {@link UserDAO}
// * @throws WebApplicationException
// * if the user can't be found, or if the user's password is
// * incorrect
// */
// public Session buildSession(UserDAO userDAO) throws WebApplicationException {
// final User user = userDAO.findById(username);
// if (user != null) {
// try {
// final UnlockedKeySet keySet = user.getKeySet().unlock(password.toCharArray());
// return new Session(user, keySet);
// } catch (CryptographicException e) {
// throw new WebApplicationException(CHALLENGE);
// }
// }
//
// throw new WebApplicationException(CHALLENGE);
// }
//
// /**
// * Given a {@link UserDAO} and an allowed {@link User} id, finds the
// * associated {@link User} and returns a {@link Session}.
// *
// * @param userDAO
// * a {@link UserDAO}
// * @param allowedId
// * the id of the only {@link User} which should be allowed access
// * to session context
// * @throws WebApplicationException
// * if the user can't be found, or if the user's password is
// * incorrect
// */
// public Session buildSession(UserDAO userDAO, String allowedId) {
// final Session session = buildSession(userDAO);
// if (session.getUser().getId().equals(allowedId)) {
// return session;
// }
//
// throw new WebApplicationException(Status.FORBIDDEN);
// }
// }
| import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.HttpHeaders;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.sun.jersey.api.core.HttpContext;
import com.sun.jersey.api.core.HttpRequestContext;
import com.wesabe.grendel.auth.BasicAuthProvider;
import com.wesabe.grendel.auth.Credentials; | package com.wesabe.grendel.auth.tests;
@RunWith(Enclosed.class)
public class BasicAuthProviderTest {
private static abstract class Context {
protected HttpContext context;
protected HttpRequestContext request;
protected BasicAuthProvider provider;
public void setup() throws Exception {
this.request = mock(HttpRequestContext.class);
when(request.getHeaderValue(HttpHeaders.AUTHORIZATION)).thenReturn(header());
this.context = mock(HttpContext.class);
when(context.getRequest()).thenReturn(request);
this.provider = new BasicAuthProvider();
}
protected abstract String header();
}
public static class Decoding_A_Valid_Auth_Header extends Context {
@Before
@Override
public void setup() throws Exception {
super.setup();
}
@Override
protected String header() {
return "Basic bXJwZWVwZXJzOmhhcHB5";
}
@Test
public void itReturnsASetOfCredentials() throws Exception { | // Path: src/main/java/com/wesabe/grendel/auth/BasicAuthProvider.java
// @Provider
// public class BasicAuthProvider extends AbstractInjectionProvider<Credentials> {
// private static final String HEADER_PREFIX = "Basic ";
// private static final char CREDENTIAL_DELIMITER = ':';
//
// public BasicAuthProvider() {
// super(Credentials.class);
// }
//
// @Override
// public Credentials getValue(HttpContext context) {
// String header = context.getRequest().getHeaderValue(HttpHeaders.AUTHORIZATION);
// try {
// try {
// if ((header != null) && header.startsWith(HEADER_PREFIX)) {
// final String encoded = header.substring(header.indexOf(' ') + 1);
// final String credentials = B64Code.decode(encoded, StringUtil.__ISO_8859_1);
// final int i = credentials.indexOf(CREDENTIAL_DELIMITER);
//
// final String username = credentials.substring(0, i);
// final String password = credentials.substring(i + 1);
//
// if ((username != null) && (password != null)) {
// return new Credentials(username, password);
// }
// }
// } catch (IllegalArgumentException e) {
// // fall through to sending an auth challenge
// } catch (StringIndexOutOfBoundsException e) {
// // fall through to sending an auth challenge
// }
//
// throw new WebApplicationException(Credentials.CHALLENGE);
// } catch (WebApplicationException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/auth/Credentials.java
// public class Credentials {
// /**
// * An authentication challenge {@link Response}. Use this when a client's
// * provided credentials are invalid.
// */
// public static final Response CHALLENGE =
// Response.status(Status.UNAUTHORIZED)
// .header(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Grendel\"")
// .build();
//
// private final String username;
// private final String password;
//
// /**
// * Creates a new set of credentials.
// *
// * @param username the client's provided username
// * @param password the client's provided password
// */
// public Credentials(String username, String password) {
// this.username = username;
// this.password = password;
// }
//
// /**
// * Returns the client's provided username.
// */
// public String getUsername() {
// return username;
// }
//
// /**
// * Returns the client's provided password.
// */
// public String getPassword() {
// return password;
// }
//
// /**
// * Given a {@link UserDAO}, finds the associated {@link User} and returns a
// * {@link Session}.
// *
// * @param userDAO
// * a {@link UserDAO}
// * @throws WebApplicationException
// * if the user can't be found, or if the user's password is
// * incorrect
// */
// public Session buildSession(UserDAO userDAO) throws WebApplicationException {
// final User user = userDAO.findById(username);
// if (user != null) {
// try {
// final UnlockedKeySet keySet = user.getKeySet().unlock(password.toCharArray());
// return new Session(user, keySet);
// } catch (CryptographicException e) {
// throw new WebApplicationException(CHALLENGE);
// }
// }
//
// throw new WebApplicationException(CHALLENGE);
// }
//
// /**
// * Given a {@link UserDAO} and an allowed {@link User} id, finds the
// * associated {@link User} and returns a {@link Session}.
// *
// * @param userDAO
// * a {@link UserDAO}
// * @param allowedId
// * the id of the only {@link User} which should be allowed access
// * to session context
// * @throws WebApplicationException
// * if the user can't be found, or if the user's password is
// * incorrect
// */
// public Session buildSession(UserDAO userDAO, String allowedId) {
// final Session session = buildSession(userDAO);
// if (session.getUser().getId().equals(allowedId)) {
// return session;
// }
//
// throw new WebApplicationException(Status.FORBIDDEN);
// }
// }
// Path: src/test/java/com/wesabe/grendel/auth/tests/BasicAuthProviderTest.java
import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.HttpHeaders;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.sun.jersey.api.core.HttpContext;
import com.sun.jersey.api.core.HttpRequestContext;
import com.wesabe.grendel.auth.BasicAuthProvider;
import com.wesabe.grendel.auth.Credentials;
package com.wesabe.grendel.auth.tests;
@RunWith(Enclosed.class)
public class BasicAuthProviderTest {
private static abstract class Context {
protected HttpContext context;
protected HttpRequestContext request;
protected BasicAuthProvider provider;
public void setup() throws Exception {
this.request = mock(HttpRequestContext.class);
when(request.getHeaderValue(HttpHeaders.AUTHORIZATION)).thenReturn(header());
this.context = mock(HttpContext.class);
when(context.getRequest()).thenReturn(request);
this.provider = new BasicAuthProvider();
}
protected abstract String header();
}
public static class Decoding_A_Valid_Auth_Header extends Context {
@Before
@Override
public void setup() throws Exception {
super.setup();
}
@Override
protected String header() {
return "Basic bXJwZWVwZXJzOmhhcHB5";
}
@Test
public void itReturnsASetOfCredentials() throws Exception { | final Credentials creds = provider.getValue(context); |
wesabe/grendel | src/test/java/com/wesabe/grendel/openpgp/tests/PregeneratedDHParameterSpecTest.java | // Path: src/main/java/com/wesabe/grendel/openpgp/PregeneratedDHParameterSpec.java
// public final class PregeneratedDHParameterSpec extends DHParameterSpec {
// private static final BigInteger G = new BigInteger(
// "v459uv2gxjbl1jqu7fhlvhe23oi1qtwqs6n8h635dkmc2o58kwa4jurbem9h9h87iq1k" +
// "6rqj5fxowbyvpeobz9k9ijcq03sue3o45506zmhw0husbxgwy8g14gzio6ct22k45zev" +
// "n6bwj7vpwq5eat72oervw0pccp9gg45qs9m6k4fn6vrp5avmmdbu91qlv075n4ojf8iv" +
// "9r7zc4mdvvb5akkwvl36hrqd3wei9e3p5ilk1z2vnenitzau40satbcx6eqfmivvsn7m" +
// "n8schdd4irr45yakbthfu3cw896r7ygx44r534sp7r5pkldeih6fp7cin6jysr4b7woe" +
// "aglyy167976n4eg1y99i1eb6561mg587hcf05j1woxzfi8m0565nvkpz",
// 36
// );
// private static final BigInteger P = new BigInteger(
// "1ikmyh3qcdgz825eegsk41g7msaustr13k16h06zxy6pwrh1bt2d7888nv77oybgmqok" +
// "8947twild1j14miwjfc9l0jr02a1dk6t1t5ynyeyh08dyisonl2fjlsp3eyz3936vtac" +
// "idp0pll9pr52crqoektouivzt4v3jk0jgp3dvux628zvrstd143zifw2dj3ed8kd4o37" +
// "0ze6qf53sx9nyv816kpihdw10723p7igep2fe5fe8fxpg8vqf4wyttnejwho4aa0eo15" +
// "q7noeeegck2h53q2o5e00myfdnn7y7dls52ixfr1wiyk2ovq1fg66jl382t0lb76usxj" +
// "5qifjs2hqioup6premvu6u1dwb8d0qucscfq3itqolmsdpkns5vu9rfsz",
// 36
// );
//
// public PregeneratedDHParameterSpec() {
// super(P, G);
// }
// }
| import static org.fest.assertions.Assertions.*;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import javax.crypto.Cipher;
import javax.crypto.spec.DHParameterSpec;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.PregeneratedDHParameterSpec; | package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class PregeneratedDHParameterSpecTest {
public static class A_Pregenerated_DHParameterSpec { | // Path: src/main/java/com/wesabe/grendel/openpgp/PregeneratedDHParameterSpec.java
// public final class PregeneratedDHParameterSpec extends DHParameterSpec {
// private static final BigInteger G = new BigInteger(
// "v459uv2gxjbl1jqu7fhlvhe23oi1qtwqs6n8h635dkmc2o58kwa4jurbem9h9h87iq1k" +
// "6rqj5fxowbyvpeobz9k9ijcq03sue3o45506zmhw0husbxgwy8g14gzio6ct22k45zev" +
// "n6bwj7vpwq5eat72oervw0pccp9gg45qs9m6k4fn6vrp5avmmdbu91qlv075n4ojf8iv" +
// "9r7zc4mdvvb5akkwvl36hrqd3wei9e3p5ilk1z2vnenitzau40satbcx6eqfmivvsn7m" +
// "n8schdd4irr45yakbthfu3cw896r7ygx44r534sp7r5pkldeih6fp7cin6jysr4b7woe" +
// "aglyy167976n4eg1y99i1eb6561mg587hcf05j1woxzfi8m0565nvkpz",
// 36
// );
// private static final BigInteger P = new BigInteger(
// "1ikmyh3qcdgz825eegsk41g7msaustr13k16h06zxy6pwrh1bt2d7888nv77oybgmqok" +
// "8947twild1j14miwjfc9l0jr02a1dk6t1t5ynyeyh08dyisonl2fjlsp3eyz3936vtac" +
// "idp0pll9pr52crqoektouivzt4v3jk0jgp3dvux628zvrstd143zifw2dj3ed8kd4o37" +
// "0ze6qf53sx9nyv816kpihdw10723p7igep2fe5fe8fxpg8vqf4wyttnejwho4aa0eo15" +
// "q7noeeegck2h53q2o5e00myfdnn7y7dls52ixfr1wiyk2ovq1fg66jl382t0lb76usxj" +
// "5qifjs2hqioup6premvu6u1dwb8d0qucscfq3itqolmsdpkns5vu9rfsz",
// 36
// );
//
// public PregeneratedDHParameterSpec() {
// super(P, G);
// }
// }
// Path: src/test/java/com/wesabe/grendel/openpgp/tests/PregeneratedDHParameterSpecTest.java
import static org.fest.assertions.Assertions.*;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import javax.crypto.Cipher;
import javax.crypto.spec.DHParameterSpec;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.PregeneratedDHParameterSpec;
package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class PregeneratedDHParameterSpecTest {
public static class A_Pregenerated_DHParameterSpec { | private DHParameterSpec spec = new PregeneratedDHParameterSpec(); |
wesabe/grendel | src/test/java/com/wesabe/grendel/openpgp/tests/KeyFlagTest.java | // Path: src/main/java/com/wesabe/grendel/openpgp/KeyFlag.java
// public enum KeyFlag implements IntegerEquivalent {
// // org.bouncycastle.openpgp.PGPKeyFlags is incomplete, and thus not
// // referenced here.
//
// /**
// * Indicates that the key can be used to certify other keys.
// */
// CERTIFICATION( 0x01, "certifying other keys"),
//
// /**
// * Indicates that the key can be used to sign other keys.
// */
// SIGNING( 0x02, "signing data"),
//
// /**
// * Indicates that the key can be used to encrypt communications and storage.
// *
// * <b>N.B.:</b> This includes both {@code 0x04}—"this key may be used to
// * encrypt communications"—and {@code 0x08}—"this key may be used to encrypt
// * storage."
// */
// ENCRYPTION( 0x04 | 0x08, "encrypting data"),
//
// /**
// * Indicates that the key may be split via a secret-sharing mechanism.
// */
// SPLIT( 0x10, "may be split via secret-sharing mechanism"),
//
// /**
// * Indicates that the key can be used for authentication.
// */
// AUTHENTICATION( 0x20, "authentication"),
//
// /**
// * Indicates that the private components of the key may be in the possession
// * of more than one person.
// */
// SHARED( 0x80, "may be in the possession of more than one person");
//
// /**
// * The default key flags for a master key.
// */
// public static final Set<KeyFlag> MASTER_KEY_DEFAULTS =
// ImmutableSet.of(SIGNING, AUTHENTICATION, SPLIT);
//
// /**
// * The default key flags for a sub key.
// */
// public static final Set<KeyFlag> SUB_KEY_DEFAULTS =
// ImmutableSet.of(ENCRYPTION, SPLIT);
//
// private final String name;
// private final int value;
//
// private KeyFlag(int value, String name) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public int toInteger() {
// return value;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
| import static org.fest.assertions.Assertions.*;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.google.common.collect.ImmutableSet;
import com.wesabe.grendel.openpgp.KeyFlag; | package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class KeyFlagTest {
public static class Certification {
@Test
public void itHasTheSameValueAsTheBCTag() throws Exception { | // Path: src/main/java/com/wesabe/grendel/openpgp/KeyFlag.java
// public enum KeyFlag implements IntegerEquivalent {
// // org.bouncycastle.openpgp.PGPKeyFlags is incomplete, and thus not
// // referenced here.
//
// /**
// * Indicates that the key can be used to certify other keys.
// */
// CERTIFICATION( 0x01, "certifying other keys"),
//
// /**
// * Indicates that the key can be used to sign other keys.
// */
// SIGNING( 0x02, "signing data"),
//
// /**
// * Indicates that the key can be used to encrypt communications and storage.
// *
// * <b>N.B.:</b> This includes both {@code 0x04}—"this key may be used to
// * encrypt communications"—and {@code 0x08}—"this key may be used to encrypt
// * storage."
// */
// ENCRYPTION( 0x04 | 0x08, "encrypting data"),
//
// /**
// * Indicates that the key may be split via a secret-sharing mechanism.
// */
// SPLIT( 0x10, "may be split via secret-sharing mechanism"),
//
// /**
// * Indicates that the key can be used for authentication.
// */
// AUTHENTICATION( 0x20, "authentication"),
//
// /**
// * Indicates that the private components of the key may be in the possession
// * of more than one person.
// */
// SHARED( 0x80, "may be in the possession of more than one person");
//
// /**
// * The default key flags for a master key.
// */
// public static final Set<KeyFlag> MASTER_KEY_DEFAULTS =
// ImmutableSet.of(SIGNING, AUTHENTICATION, SPLIT);
//
// /**
// * The default key flags for a sub key.
// */
// public static final Set<KeyFlag> SUB_KEY_DEFAULTS =
// ImmutableSet.of(ENCRYPTION, SPLIT);
//
// private final String name;
// private final int value;
//
// private KeyFlag(int value, String name) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public int toInteger() {
// return value;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// Path: src/test/java/com/wesabe/grendel/openpgp/tests/KeyFlagTest.java
import static org.fest.assertions.Assertions.*;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.google.common.collect.ImmutableSet;
import com.wesabe.grendel.openpgp.KeyFlag;
package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class KeyFlagTest {
public static class Certification {
@Test
public void itHasTheSameValueAsTheBCTag() throws Exception { | assertThat(KeyFlag.CERTIFICATION.toInteger()).isEqualTo(0x01); |
wesabe/grendel | src/test/java/com/wesabe/grendel/openpgp/tests/PregeneratedDSAParameterSpecTest.java | // Path: src/main/java/com/wesabe/grendel/openpgp/PregeneratedDSAParameterSpec.java
// public final class PregeneratedDSAParameterSpec extends DSAParameterSpec {
// private static final BigInteger G = new BigInteger(
// "42iz5oiscx7wtyascmwkesjh4socl98ex5y2kgmnl5xnc4ny2romijch7uk53qxtnq2k" +
// "grvbx4z5qclbkkz930by9iva1dk7o5s816nen7vdwtzo6bk7nnx40y2gu55wdyzirjct" +
// "5dzh0jqjjbl0vzqmzw2si1abrrrzfaskkpb7kyqne1qctmrt2j0ozls69boond",
// 36
// );
// private static final BigInteger Q = new BigInteger(
// "pcemwdiwzfzg7vw8n8el73hi1v3pelp",
// 36
// );
// private static final BigInteger P = new BigInteger(
// "pmqpa15uksb3tr1710v3m0ohs0i1utcoavzgk066lbp5rkvgjtjgqb0fj847osr54s23" +
// "w4g60p0a7v3yn0twefnvvqdqn29xpe9auvblylpirmeio1usdnxwdp9bcu9n1i9jtvty" +
// "glg49753mkd5wnyaztp3qo5sm6ussie7fsf2rss7jjbcj2trgnfq4sshdm6sp7",
// 36
// );
//
// public PregeneratedDSAParameterSpec() {
// super(P, Q, G);
// }
// }
| import static org.fest.assertions.Assertions.*;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.spec.DSAParameterSpec;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.PregeneratedDSAParameterSpec; | package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class PregeneratedDSAParameterSpecTest {
public static class A_Pregenerated_DSAParameterSpec { | // Path: src/main/java/com/wesabe/grendel/openpgp/PregeneratedDSAParameterSpec.java
// public final class PregeneratedDSAParameterSpec extends DSAParameterSpec {
// private static final BigInteger G = new BigInteger(
// "42iz5oiscx7wtyascmwkesjh4socl98ex5y2kgmnl5xnc4ny2romijch7uk53qxtnq2k" +
// "grvbx4z5qclbkkz930by9iva1dk7o5s816nen7vdwtzo6bk7nnx40y2gu55wdyzirjct" +
// "5dzh0jqjjbl0vzqmzw2si1abrrrzfaskkpb7kyqne1qctmrt2j0ozls69boond",
// 36
// );
// private static final BigInteger Q = new BigInteger(
// "pcemwdiwzfzg7vw8n8el73hi1v3pelp",
// 36
// );
// private static final BigInteger P = new BigInteger(
// "pmqpa15uksb3tr1710v3m0ohs0i1utcoavzgk066lbp5rkvgjtjgqb0fj847osr54s23" +
// "w4g60p0a7v3yn0twefnvvqdqn29xpe9auvblylpirmeio1usdnxwdp9bcu9n1i9jtvty" +
// "glg49753mkd5wnyaztp3qo5sm6ussie7fsf2rss7jjbcj2trgnfq4sshdm6sp7",
// 36
// );
//
// public PregeneratedDSAParameterSpec() {
// super(P, Q, G);
// }
// }
// Path: src/test/java/com/wesabe/grendel/openpgp/tests/PregeneratedDSAParameterSpecTest.java
import static org.fest.assertions.Assertions.*;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.spec.DSAParameterSpec;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.PregeneratedDSAParameterSpec;
package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class PregeneratedDSAParameterSpecTest {
public static class A_Pregenerated_DSAParameterSpec { | private DSAParameterSpec spec = new PregeneratedDSAParameterSpec(); |
wesabe/grendel | src/test/java/com/wesabe/grendel/representations/tests/CreateUserRepresentationTest.java | // Path: src/main/java/com/wesabe/grendel/representations/CreateUserRepresentation.java
// public class CreateUserRepresentation implements Validatable {
// private String id;
// private char[] password;
//
// @JsonGetter("password")
// public char[] getPassword() {
// return password;
// }
//
// @JsonGetter("id")
// public String getId() {
// return id;
// }
//
// @JsonSetter("password")
// public void setPassword(char[] password) {
// this.password = Arrays.copyOf(password, password.length);
// Arrays.fill(password, '\0');
// }
//
// @JsonSetter("id")
// public void setId(String username) {
// this.id = username;
// }
//
// public void sanitize() {
// Arrays.fill(password, '\0');
// }
//
// @Override
// public void validate() throws ValidationException {
// final ValidationException error = new ValidationException();
//
// if ((id == null) || id.isEmpty()) {
// error.missingRequiredProperty("id");
// }
//
// if ((password == null) || (password.length == 0)) {
// error.missingRequiredProperty("password");
// }
//
// if (error.hasReasons()) {
// throw error;
// }
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/representations/ValidationException.java
// public class ValidationException extends WebApplicationException {
// private static final int UNPROCESSABLE_ENTITY = 422;
// private static final long serialVersionUID = -6730797215368434430L;
// private final StringBuilder msgBuilder;
// private boolean hasReasons = false;
//
// public ValidationException() {
// super();
// this.msgBuilder = new StringBuilder(
// "Grendel was unable to process your request for the following reason(s):\n\n"
// );
// }
//
// /**
// * Adds a reason for validation failure to the list.
// */
// public void addReason(String reason) {
// this.hasReasons = true;
// msgBuilder.append("* ").append(reason).append('\n');
// }
//
// /**
// * Adds a failure to include a required property to the list.
// */
// public void missingRequiredProperty(String propertyName) {
// addReason("missing required property: " + propertyName);
// }
//
// /**
// * Returns {@code true} if the exception has reasons, {@code false}
// * otherwise.
// */
// public boolean hasReasons() {
// return hasReasons;
// }
//
// @Override
// public Response getResponse() {
// return Response
// .status(UNPROCESSABLE_ENTITY)
// .type(MediaType.TEXT_PLAIN)
// .entity(msgBuilder.toString())
// .build();
// }
// }
| import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.representations.CreateUserRepresentation;
import com.wesabe.grendel.representations.ValidationException; | package com.wesabe.grendel.representations.tests;
@RunWith(Enclosed.class)
public class CreateUserRepresentationTest {
public static class A_Valid_New_User_Request { | // Path: src/main/java/com/wesabe/grendel/representations/CreateUserRepresentation.java
// public class CreateUserRepresentation implements Validatable {
// private String id;
// private char[] password;
//
// @JsonGetter("password")
// public char[] getPassword() {
// return password;
// }
//
// @JsonGetter("id")
// public String getId() {
// return id;
// }
//
// @JsonSetter("password")
// public void setPassword(char[] password) {
// this.password = Arrays.copyOf(password, password.length);
// Arrays.fill(password, '\0');
// }
//
// @JsonSetter("id")
// public void setId(String username) {
// this.id = username;
// }
//
// public void sanitize() {
// Arrays.fill(password, '\0');
// }
//
// @Override
// public void validate() throws ValidationException {
// final ValidationException error = new ValidationException();
//
// if ((id == null) || id.isEmpty()) {
// error.missingRequiredProperty("id");
// }
//
// if ((password == null) || (password.length == 0)) {
// error.missingRequiredProperty("password");
// }
//
// if (error.hasReasons()) {
// throw error;
// }
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/representations/ValidationException.java
// public class ValidationException extends WebApplicationException {
// private static final int UNPROCESSABLE_ENTITY = 422;
// private static final long serialVersionUID = -6730797215368434430L;
// private final StringBuilder msgBuilder;
// private boolean hasReasons = false;
//
// public ValidationException() {
// super();
// this.msgBuilder = new StringBuilder(
// "Grendel was unable to process your request for the following reason(s):\n\n"
// );
// }
//
// /**
// * Adds a reason for validation failure to the list.
// */
// public void addReason(String reason) {
// this.hasReasons = true;
// msgBuilder.append("* ").append(reason).append('\n');
// }
//
// /**
// * Adds a failure to include a required property to the list.
// */
// public void missingRequiredProperty(String propertyName) {
// addReason("missing required property: " + propertyName);
// }
//
// /**
// * Returns {@code true} if the exception has reasons, {@code false}
// * otherwise.
// */
// public boolean hasReasons() {
// return hasReasons;
// }
//
// @Override
// public Response getResponse() {
// return Response
// .status(UNPROCESSABLE_ENTITY)
// .type(MediaType.TEXT_PLAIN)
// .entity(msgBuilder.toString())
// .build();
// }
// }
// Path: src/test/java/com/wesabe/grendel/representations/tests/CreateUserRepresentationTest.java
import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.representations.CreateUserRepresentation;
import com.wesabe.grendel.representations.ValidationException;
package com.wesabe.grendel.representations.tests;
@RunWith(Enclosed.class)
public class CreateUserRepresentationTest {
public static class A_Valid_New_User_Request { | private CreateUserRepresentation req; |
wesabe/grendel | src/test/java/com/wesabe/grendel/representations/tests/CreateUserRepresentationTest.java | // Path: src/main/java/com/wesabe/grendel/representations/CreateUserRepresentation.java
// public class CreateUserRepresentation implements Validatable {
// private String id;
// private char[] password;
//
// @JsonGetter("password")
// public char[] getPassword() {
// return password;
// }
//
// @JsonGetter("id")
// public String getId() {
// return id;
// }
//
// @JsonSetter("password")
// public void setPassword(char[] password) {
// this.password = Arrays.copyOf(password, password.length);
// Arrays.fill(password, '\0');
// }
//
// @JsonSetter("id")
// public void setId(String username) {
// this.id = username;
// }
//
// public void sanitize() {
// Arrays.fill(password, '\0');
// }
//
// @Override
// public void validate() throws ValidationException {
// final ValidationException error = new ValidationException();
//
// if ((id == null) || id.isEmpty()) {
// error.missingRequiredProperty("id");
// }
//
// if ((password == null) || (password.length == 0)) {
// error.missingRequiredProperty("password");
// }
//
// if (error.hasReasons()) {
// throw error;
// }
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/representations/ValidationException.java
// public class ValidationException extends WebApplicationException {
// private static final int UNPROCESSABLE_ENTITY = 422;
// private static final long serialVersionUID = -6730797215368434430L;
// private final StringBuilder msgBuilder;
// private boolean hasReasons = false;
//
// public ValidationException() {
// super();
// this.msgBuilder = new StringBuilder(
// "Grendel was unable to process your request for the following reason(s):\n\n"
// );
// }
//
// /**
// * Adds a reason for validation failure to the list.
// */
// public void addReason(String reason) {
// this.hasReasons = true;
// msgBuilder.append("* ").append(reason).append('\n');
// }
//
// /**
// * Adds a failure to include a required property to the list.
// */
// public void missingRequiredProperty(String propertyName) {
// addReason("missing required property: " + propertyName);
// }
//
// /**
// * Returns {@code true} if the exception has reasons, {@code false}
// * otherwise.
// */
// public boolean hasReasons() {
// return hasReasons;
// }
//
// @Override
// public Response getResponse() {
// return Response
// .status(UNPROCESSABLE_ENTITY)
// .type(MediaType.TEXT_PLAIN)
// .entity(msgBuilder.toString())
// .build();
// }
// }
| import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.representations.CreateUserRepresentation;
import com.wesabe.grendel.representations.ValidationException; | package com.wesabe.grendel.representations.tests;
@RunWith(Enclosed.class)
public class CreateUserRepresentationTest {
public static class A_Valid_New_User_Request {
private CreateUserRepresentation req;
@Before
public void setup() throws Exception {
this.req = new CreateUserRepresentation();
req.setId("dingo");
req.setPassword("happenstance".toCharArray());
}
@Test
public void itIsValid() throws Exception {
try {
req.validate();
assertThat(true).isTrue(); | // Path: src/main/java/com/wesabe/grendel/representations/CreateUserRepresentation.java
// public class CreateUserRepresentation implements Validatable {
// private String id;
// private char[] password;
//
// @JsonGetter("password")
// public char[] getPassword() {
// return password;
// }
//
// @JsonGetter("id")
// public String getId() {
// return id;
// }
//
// @JsonSetter("password")
// public void setPassword(char[] password) {
// this.password = Arrays.copyOf(password, password.length);
// Arrays.fill(password, '\0');
// }
//
// @JsonSetter("id")
// public void setId(String username) {
// this.id = username;
// }
//
// public void sanitize() {
// Arrays.fill(password, '\0');
// }
//
// @Override
// public void validate() throws ValidationException {
// final ValidationException error = new ValidationException();
//
// if ((id == null) || id.isEmpty()) {
// error.missingRequiredProperty("id");
// }
//
// if ((password == null) || (password.length == 0)) {
// error.missingRequiredProperty("password");
// }
//
// if (error.hasReasons()) {
// throw error;
// }
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/representations/ValidationException.java
// public class ValidationException extends WebApplicationException {
// private static final int UNPROCESSABLE_ENTITY = 422;
// private static final long serialVersionUID = -6730797215368434430L;
// private final StringBuilder msgBuilder;
// private boolean hasReasons = false;
//
// public ValidationException() {
// super();
// this.msgBuilder = new StringBuilder(
// "Grendel was unable to process your request for the following reason(s):\n\n"
// );
// }
//
// /**
// * Adds a reason for validation failure to the list.
// */
// public void addReason(String reason) {
// this.hasReasons = true;
// msgBuilder.append("* ").append(reason).append('\n');
// }
//
// /**
// * Adds a failure to include a required property to the list.
// */
// public void missingRequiredProperty(String propertyName) {
// addReason("missing required property: " + propertyName);
// }
//
// /**
// * Returns {@code true} if the exception has reasons, {@code false}
// * otherwise.
// */
// public boolean hasReasons() {
// return hasReasons;
// }
//
// @Override
// public Response getResponse() {
// return Response
// .status(UNPROCESSABLE_ENTITY)
// .type(MediaType.TEXT_PLAIN)
// .entity(msgBuilder.toString())
// .build();
// }
// }
// Path: src/test/java/com/wesabe/grendel/representations/tests/CreateUserRepresentationTest.java
import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.representations.CreateUserRepresentation;
import com.wesabe.grendel.representations.ValidationException;
package com.wesabe.grendel.representations.tests;
@RunWith(Enclosed.class)
public class CreateUserRepresentationTest {
public static class A_Valid_New_User_Request {
private CreateUserRepresentation req;
@Before
public void setup() throws Exception {
this.req = new CreateUserRepresentation();
req.setId("dingo");
req.setPassword("happenstance".toCharArray());
}
@Test
public void itIsValid() throws Exception {
try {
req.validate();
assertThat(true).isTrue(); | } catch (ValidationException e) { |
wesabe/grendel | src/test/java/com/wesabe/grendel/openpgp/tests/UnlockedMasterKeyTest.java | // Path: src/main/java/com/wesabe/grendel/openpgp/MasterKey.java
// public class MasterKey extends AbstractKey {
//
// /**
// * Loads a master key from a {@link PGPSecretKey} instance and verifies its
// * certification.
// *
// * @param key a {@link PGPSecretKey} instance
// * @return a {@link MasterKey} instance
// * @throws CryptographicException if the key is not a self-signed master key
// */
// public static MasterKey load(PGPSecretKey key) throws CryptographicException {
// final MasterKey masterKey = new MasterKey(key);
// if (verify(masterKey)) {
// return masterKey;
// }
// throw new CryptographicException("not a self-signed master key");
// }
//
// private static boolean verify(MasterKey key) {
// return (key.signature != null) && key.signature.verifyCertification(key);
// }
//
// protected MasterKey(PGPSecretKey secretKey) {
// super(secretKey, secretKey, SignatureType.POSITIVE_CERTIFICATION);
// }
//
// @Override
// public UnlockedMasterKey unlock(char[] passphrase) throws CryptographicException {
// try {
// final PGPPrivateKey privateKey = secretKey.extractPrivateKey(passphrase, "BC");
// return new UnlockedMasterKey(secretKey, privateKey);
// } catch (NoSuchProviderException e) {
// throw new CryptographicException(e);
// } catch (PGPException e) {
// throw new CryptographicException("incorrect passphrase");
// }
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/openpgp/UnlockedMasterKey.java
// public class UnlockedMasterKey extends MasterKey implements UnlockedKey {
// private final PGPPrivateKey privateKey;
//
// protected UnlockedMasterKey(PGPSecretKey secretKey, PGPPrivateKey privateKey) {
// super(secretKey);
// this.privateKey = privateKey;
// }
//
// @Override
// public UnlockedMasterKey unlock(char[] passphrase) {
// return this;
// }
//
// @Override
// public PGPPrivateKey getPrivateKey() {
// return privateKey;
// }
// }
| import static org.fest.assertions.Assertions.*;
import java.io.FileInputStream;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.MasterKey;
import com.wesabe.grendel.openpgp.UnlockedMasterKey; | package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class UnlockedMasterKeyTest {
public static class An_Unlocked_Master_Key { | // Path: src/main/java/com/wesabe/grendel/openpgp/MasterKey.java
// public class MasterKey extends AbstractKey {
//
// /**
// * Loads a master key from a {@link PGPSecretKey} instance and verifies its
// * certification.
// *
// * @param key a {@link PGPSecretKey} instance
// * @return a {@link MasterKey} instance
// * @throws CryptographicException if the key is not a self-signed master key
// */
// public static MasterKey load(PGPSecretKey key) throws CryptographicException {
// final MasterKey masterKey = new MasterKey(key);
// if (verify(masterKey)) {
// return masterKey;
// }
// throw new CryptographicException("not a self-signed master key");
// }
//
// private static boolean verify(MasterKey key) {
// return (key.signature != null) && key.signature.verifyCertification(key);
// }
//
// protected MasterKey(PGPSecretKey secretKey) {
// super(secretKey, secretKey, SignatureType.POSITIVE_CERTIFICATION);
// }
//
// @Override
// public UnlockedMasterKey unlock(char[] passphrase) throws CryptographicException {
// try {
// final PGPPrivateKey privateKey = secretKey.extractPrivateKey(passphrase, "BC");
// return new UnlockedMasterKey(secretKey, privateKey);
// } catch (NoSuchProviderException e) {
// throw new CryptographicException(e);
// } catch (PGPException e) {
// throw new CryptographicException("incorrect passphrase");
// }
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/openpgp/UnlockedMasterKey.java
// public class UnlockedMasterKey extends MasterKey implements UnlockedKey {
// private final PGPPrivateKey privateKey;
//
// protected UnlockedMasterKey(PGPSecretKey secretKey, PGPPrivateKey privateKey) {
// super(secretKey);
// this.privateKey = privateKey;
// }
//
// @Override
// public UnlockedMasterKey unlock(char[] passphrase) {
// return this;
// }
//
// @Override
// public PGPPrivateKey getPrivateKey() {
// return privateKey;
// }
// }
// Path: src/test/java/com/wesabe/grendel/openpgp/tests/UnlockedMasterKeyTest.java
import static org.fest.assertions.Assertions.*;
import java.io.FileInputStream;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.MasterKey;
import com.wesabe.grendel.openpgp.UnlockedMasterKey;
package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class UnlockedMasterKeyTest {
public static class An_Unlocked_Master_Key { | private UnlockedMasterKey key; |
wesabe/grendel | src/test/java/com/wesabe/grendel/openpgp/tests/UnlockedMasterKeyTest.java | // Path: src/main/java/com/wesabe/grendel/openpgp/MasterKey.java
// public class MasterKey extends AbstractKey {
//
// /**
// * Loads a master key from a {@link PGPSecretKey} instance and verifies its
// * certification.
// *
// * @param key a {@link PGPSecretKey} instance
// * @return a {@link MasterKey} instance
// * @throws CryptographicException if the key is not a self-signed master key
// */
// public static MasterKey load(PGPSecretKey key) throws CryptographicException {
// final MasterKey masterKey = new MasterKey(key);
// if (verify(masterKey)) {
// return masterKey;
// }
// throw new CryptographicException("not a self-signed master key");
// }
//
// private static boolean verify(MasterKey key) {
// return (key.signature != null) && key.signature.verifyCertification(key);
// }
//
// protected MasterKey(PGPSecretKey secretKey) {
// super(secretKey, secretKey, SignatureType.POSITIVE_CERTIFICATION);
// }
//
// @Override
// public UnlockedMasterKey unlock(char[] passphrase) throws CryptographicException {
// try {
// final PGPPrivateKey privateKey = secretKey.extractPrivateKey(passphrase, "BC");
// return new UnlockedMasterKey(secretKey, privateKey);
// } catch (NoSuchProviderException e) {
// throw new CryptographicException(e);
// } catch (PGPException e) {
// throw new CryptographicException("incorrect passphrase");
// }
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/openpgp/UnlockedMasterKey.java
// public class UnlockedMasterKey extends MasterKey implements UnlockedKey {
// private final PGPPrivateKey privateKey;
//
// protected UnlockedMasterKey(PGPSecretKey secretKey, PGPPrivateKey privateKey) {
// super(secretKey);
// this.privateKey = privateKey;
// }
//
// @Override
// public UnlockedMasterKey unlock(char[] passphrase) {
// return this;
// }
//
// @Override
// public PGPPrivateKey getPrivateKey() {
// return privateKey;
// }
// }
| import static org.fest.assertions.Assertions.*;
import java.io.FileInputStream;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.MasterKey;
import com.wesabe.grendel.openpgp.UnlockedMasterKey; | package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class UnlockedMasterKeyTest {
public static class An_Unlocked_Master_Key {
private UnlockedMasterKey key;
@Before
public void setup() throws Exception {
final FileInputStream keyRingFile = new FileInputStream("src/test/resources/secret-keyring.gpg");
final PGPSecretKeyRing keyRing = new PGPSecretKeyRing(keyRingFile);
keyRingFile.close();
| // Path: src/main/java/com/wesabe/grendel/openpgp/MasterKey.java
// public class MasterKey extends AbstractKey {
//
// /**
// * Loads a master key from a {@link PGPSecretKey} instance and verifies its
// * certification.
// *
// * @param key a {@link PGPSecretKey} instance
// * @return a {@link MasterKey} instance
// * @throws CryptographicException if the key is not a self-signed master key
// */
// public static MasterKey load(PGPSecretKey key) throws CryptographicException {
// final MasterKey masterKey = new MasterKey(key);
// if (verify(masterKey)) {
// return masterKey;
// }
// throw new CryptographicException("not a self-signed master key");
// }
//
// private static boolean verify(MasterKey key) {
// return (key.signature != null) && key.signature.verifyCertification(key);
// }
//
// protected MasterKey(PGPSecretKey secretKey) {
// super(secretKey, secretKey, SignatureType.POSITIVE_CERTIFICATION);
// }
//
// @Override
// public UnlockedMasterKey unlock(char[] passphrase) throws CryptographicException {
// try {
// final PGPPrivateKey privateKey = secretKey.extractPrivateKey(passphrase, "BC");
// return new UnlockedMasterKey(secretKey, privateKey);
// } catch (NoSuchProviderException e) {
// throw new CryptographicException(e);
// } catch (PGPException e) {
// throw new CryptographicException("incorrect passphrase");
// }
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/openpgp/UnlockedMasterKey.java
// public class UnlockedMasterKey extends MasterKey implements UnlockedKey {
// private final PGPPrivateKey privateKey;
//
// protected UnlockedMasterKey(PGPSecretKey secretKey, PGPPrivateKey privateKey) {
// super(secretKey);
// this.privateKey = privateKey;
// }
//
// @Override
// public UnlockedMasterKey unlock(char[] passphrase) {
// return this;
// }
//
// @Override
// public PGPPrivateKey getPrivateKey() {
// return privateKey;
// }
// }
// Path: src/test/java/com/wesabe/grendel/openpgp/tests/UnlockedMasterKeyTest.java
import static org.fest.assertions.Assertions.*;
import java.io.FileInputStream;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.MasterKey;
import com.wesabe.grendel.openpgp.UnlockedMasterKey;
package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class UnlockedMasterKeyTest {
public static class An_Unlocked_Master_Key {
private UnlockedMasterKey key;
@Before
public void setup() throws Exception {
final FileInputStream keyRingFile = new FileInputStream("src/test/resources/secret-keyring.gpg");
final PGPSecretKeyRing keyRing = new PGPSecretKeyRing(keyRingFile);
keyRingFile.close();
| this.key = MasterKey.load(keyRing.getSecretKey(0x8C7035EF8838238CL)).unlock("test".toCharArray()); |
wesabe/grendel | src/main/java/com/wesabe/grendel/openpgp/MessageReader.java | // Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalents.java
// public final class IntegerEquivalents {
// private IntegerEquivalents() {}
//
// /**
// * Returns the collection of {@code integerEquivs} as an array of {@code int}s.
// */
// public static int[] toIntArray(Collection<? extends IntegerEquivalent> integerEquivs) {
// final int[] values = new int[integerEquivs.size()];
// int i = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// values[i] = integerEquiv.toInteger();
// i++;
// }
// return values;
// }
//
// /**
// * Returns the set of {@code integerEquivs} as a bitmask {@code int}.
// */
// public static int toBitmask(Set<? extends IntegerEquivalent> integerEquivs) {
// int value = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// value |= integerEquiv.toInteger();
// }
// return value;
// }
//
// /**
// * Returns the instance of {@code enumType} which is equivalent to
// * {@code value}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> T fromInt(Class<T> enumType, int value) throws IllegalArgumentException {
// for (T constant : enumType.getEnumConstants()) {
// if (constant.toInteger() == value) {
// return constant;
// }
// }
// throw new IllegalArgumentException("No enum constant of " + enumType + " exists with value " + value);
// }
//
// /**
// * Returns the list of the instances of {@code enumType} which are equivalent
// * to {@code values}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> List<T> fromIntArray(Class<T> enumType, int[] values) throws IllegalArgumentException {
// final ImmutableList.Builder<T> builder = ImmutableList.builder();
// for (int value : values) {
// builder.add(fromInt(enumType, value));
// }
// return builder.build();
// }
//
// /**
// * Returns the {@code bitMask} as a set of {@link IntegerEquivalent}s.
// */
// public static <T extends IntegerEquivalent> Set<T> fromBitmask(Class<T> enumType, int bitMask) throws IllegalArgumentException {
// final ImmutableSet.Builder<T> builder = ImmutableSet.builder();
// for (T constant : enumType.getEnumConstants()) {
// if ((bitMask & constant.toInteger()) != 0) {
// builder.add(constant);
// }
// }
// return builder.build();
// }
// }
| import com.wesabe.grendel.util.IntegerEquivalents;
import org.bouncycastle.openpgp.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.NoSuchProviderException; | while ((r = body.read(b)) >= 0) {
output.write(b, 0, r);
signature.update(b, 0, r);
}
if (!signature.verify(getSignature(signer, factory))) {
throw new CryptographicException("Invalid signature");
}
if (!encryptedData.verify()) {
throw new CryptographicException("Integrity check failed");
}
return output.toByteArray();
} catch (IOException e) {
throw new CryptographicException(e);
} catch (ClassCastException e) {
throw new CryptographicException(e);
} catch (GeneralSecurityException e) {
throw new CryptographicException(e);
} catch (PGPException e) {
throw new CryptographicException(e);
}
}
private PGPSignature getSignature(KeySet owner, PGPObjectFactory factory) throws CryptographicException, IOException {
final PGPSignatureList signatures = (PGPSignatureList) factory.nextObject();
for (int i = 0, size = signatures.size(); i < size; i++) {
final PGPSignature signature = signatures.get(i);
if (signature.getKeyID() == owner.getMasterKey().getKeyID()) { | // Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalents.java
// public final class IntegerEquivalents {
// private IntegerEquivalents() {}
//
// /**
// * Returns the collection of {@code integerEquivs} as an array of {@code int}s.
// */
// public static int[] toIntArray(Collection<? extends IntegerEquivalent> integerEquivs) {
// final int[] values = new int[integerEquivs.size()];
// int i = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// values[i] = integerEquiv.toInteger();
// i++;
// }
// return values;
// }
//
// /**
// * Returns the set of {@code integerEquivs} as a bitmask {@code int}.
// */
// public static int toBitmask(Set<? extends IntegerEquivalent> integerEquivs) {
// int value = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// value |= integerEquiv.toInteger();
// }
// return value;
// }
//
// /**
// * Returns the instance of {@code enumType} which is equivalent to
// * {@code value}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> T fromInt(Class<T> enumType, int value) throws IllegalArgumentException {
// for (T constant : enumType.getEnumConstants()) {
// if (constant.toInteger() == value) {
// return constant;
// }
// }
// throw new IllegalArgumentException("No enum constant of " + enumType + " exists with value " + value);
// }
//
// /**
// * Returns the list of the instances of {@code enumType} which are equivalent
// * to {@code values}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> List<T> fromIntArray(Class<T> enumType, int[] values) throws IllegalArgumentException {
// final ImmutableList.Builder<T> builder = ImmutableList.builder();
// for (int value : values) {
// builder.add(fromInt(enumType, value));
// }
// return builder.build();
// }
//
// /**
// * Returns the {@code bitMask} as a set of {@link IntegerEquivalent}s.
// */
// public static <T extends IntegerEquivalent> Set<T> fromBitmask(Class<T> enumType, int bitMask) throws IllegalArgumentException {
// final ImmutableSet.Builder<T> builder = ImmutableSet.builder();
// for (T constant : enumType.getEnumConstants()) {
// if ((bitMask & constant.toInteger()) != 0) {
// builder.add(constant);
// }
// }
// return builder.build();
// }
// }
// Path: src/main/java/com/wesabe/grendel/openpgp/MessageReader.java
import com.wesabe.grendel.util.IntegerEquivalents;
import org.bouncycastle.openpgp.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.NoSuchProviderException;
while ((r = body.read(b)) >= 0) {
output.write(b, 0, r);
signature.update(b, 0, r);
}
if (!signature.verify(getSignature(signer, factory))) {
throw new CryptographicException("Invalid signature");
}
if (!encryptedData.verify()) {
throw new CryptographicException("Integrity check failed");
}
return output.toByteArray();
} catch (IOException e) {
throw new CryptographicException(e);
} catch (ClassCastException e) {
throw new CryptographicException(e);
} catch (GeneralSecurityException e) {
throw new CryptographicException(e);
} catch (PGPException e) {
throw new CryptographicException(e);
}
}
private PGPSignature getSignature(KeySet owner, PGPObjectFactory factory) throws CryptographicException, IOException {
final PGPSignatureList signatures = (PGPSignatureList) factory.nextObject();
for (int i = 0, size = signatures.size(); i < size; i++) {
final PGPSignature signature = signatures.get(i);
if (signature.getKeyID() == owner.getMasterKey().getKeyID()) { | final HashAlgorithm hashAlgorithm = IntegerEquivalents.fromInt( |
wesabe/grendel | src/test/java/com/wesabe/grendel/openpgp/tests/CryptographicExceptionTest.java | // Path: src/main/java/com/wesabe/grendel/openpgp/CryptographicException.java
// public class CryptographicException extends Exception {
// private static final long serialVersionUID = 7018291212808057570L;
//
// public CryptographicException(String message) {
// super(message);
// }
//
// public CryptographicException(Throwable cause) {
// super(cause);
// }
//
// public CryptographicException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import static org.fest.assertions.Assertions.*;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.CryptographicException; | package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class CryptographicExceptionTest {
public static class A_Cryptographic_Exception_With_A_Message { | // Path: src/main/java/com/wesabe/grendel/openpgp/CryptographicException.java
// public class CryptographicException extends Exception {
// private static final long serialVersionUID = 7018291212808057570L;
//
// public CryptographicException(String message) {
// super(message);
// }
//
// public CryptographicException(Throwable cause) {
// super(cause);
// }
//
// public CryptographicException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: src/test/java/com/wesabe/grendel/openpgp/tests/CryptographicExceptionTest.java
import static org.fest.assertions.Assertions.*;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.CryptographicException;
package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class CryptographicExceptionTest {
public static class A_Cryptographic_Exception_With_A_Message { | private CryptographicException e = new CryptographicException("message"); |
wesabe/grendel | src/main/java/com/wesabe/grendel/openpgp/KeySet.java | // Path: src/main/java/com/wesabe/grendel/util/Iterators.java
// public final class Iterators {
// private Iterators() {}
//
// /**
// * Returns the items available via {@code iterator} as a {@link List}.
// */
// @SuppressWarnings("unchecked")
// public static <T> List<T> toList(Iterator<?> iterator) {
// return ImmutableList.copyOf((Iterator<T>) iterator);
// }
//
// /**
// * Returns the items available via {@code iterator} as a {@link Set}.
// */
// @SuppressWarnings("unchecked")
// public static <T> Set<T> toSet(Iterator<?> iterator) {
// return ImmutableSet.copyOf((Iterator<T>) iterator);
// }
// }
| import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import com.wesabe.grendel.util.Iterators; | package com.wesabe.grendel.openpgp;
/**
* A {@link MasterKey} and {@link SubKey} pair.
*
* @author coda
*/
public class KeySet {
private final MasterKey masterKey;
private final SubKey subKey;
/**
* Loads a {@link KeySet} from an array of bytes.
*
* @throws CryptographicException if the encoded {@link KeySet} is malformed
*/
public static KeySet load(byte[] encoded) throws CryptographicException {
return load(new ByteArrayInputStream(encoded));
}
/**
* Loads a {@link KeySet} from a {@link PGPSecretKeyRing}.
*/
public static KeySet load(PGPSecretKeyRing keyRing) throws CryptographicException { | // Path: src/main/java/com/wesabe/grendel/util/Iterators.java
// public final class Iterators {
// private Iterators() {}
//
// /**
// * Returns the items available via {@code iterator} as a {@link List}.
// */
// @SuppressWarnings("unchecked")
// public static <T> List<T> toList(Iterator<?> iterator) {
// return ImmutableList.copyOf((Iterator<T>) iterator);
// }
//
// /**
// * Returns the items available via {@code iterator} as a {@link Set}.
// */
// @SuppressWarnings("unchecked")
// public static <T> Set<T> toSet(Iterator<?> iterator) {
// return ImmutableSet.copyOf((Iterator<T>) iterator);
// }
// }
// Path: src/main/java/com/wesabe/grendel/openpgp/KeySet.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import com.wesabe.grendel.util.Iterators;
package com.wesabe.grendel.openpgp;
/**
* A {@link MasterKey} and {@link SubKey} pair.
*
* @author coda
*/
public class KeySet {
private final MasterKey masterKey;
private final SubKey subKey;
/**
* Loads a {@link KeySet} from an array of bytes.
*
* @throws CryptographicException if the encoded {@link KeySet} is malformed
*/
public static KeySet load(byte[] encoded) throws CryptographicException {
return load(new ByteArrayInputStream(encoded));
}
/**
* Loads a {@link KeySet} from a {@link PGPSecretKeyRing}.
*/
public static KeySet load(PGPSecretKeyRing keyRing) throws CryptographicException { | final List<PGPSecretKey> secretKeys = Iterators.toList(keyRing.getSecretKeys()); |
wesabe/grendel | src/test/java/com/wesabe/grendel/openpgp/tests/KeySetTest.java | // Path: src/main/java/com/wesabe/grendel/openpgp/KeySet.java
// public class KeySet {
// private final MasterKey masterKey;
// private final SubKey subKey;
//
// /**
// * Loads a {@link KeySet} from an array of bytes.
// *
// * @throws CryptographicException if the encoded {@link KeySet} is malformed
// */
// public static KeySet load(byte[] encoded) throws CryptographicException {
// return load(new ByteArrayInputStream(encoded));
// }
//
// /**
// * Loads a {@link KeySet} from a {@link PGPSecretKeyRing}.
// */
// public static KeySet load(PGPSecretKeyRing keyRing) throws CryptographicException {
// final List<PGPSecretKey> secretKeys = Iterators.toList(keyRing.getSecretKeys());
// final MasterKey masterKey = MasterKey.load(secretKeys.get(0));
// final SubKey subKey = SubKey.load(secretKeys.get(1), masterKey);
//
// return new KeySet(masterKey, subKey);
// }
//
// /**
// * Loads a {@link KeySet} from an {@link InputStream}.
// */
// public static KeySet load(InputStream input) throws CryptographicException {
// try {
// final PGPSecretKeyRing keyRing = new PGPSecretKeyRing(input);
// input.close();
// return load(keyRing);
// } catch (IOException e) {
// throw new CryptographicException(e);
// } catch (PGPException e) {
// throw new CryptographicException(e);
// }
// }
//
// protected KeySet(MasterKey masterKey, SubKey subKey) {
// this.masterKey = masterKey;
// this.subKey = subKey;
// }
//
// /**
// * Returns the keyset's {@link MasterKey}.
// */
// public MasterKey getMasterKey() {
// return masterKey;
// }
//
// /**
// * Returns the keyset's {@link SubKey}.
// */
// public SubKey getSubKey() {
// return subKey;
// }
//
// /**
// * Returns the keyset's user ID.
// */
// public String getUserID() {
// return masterKey.getUserID();
// }
//
// /**
// * Writes the keyset in encoded form, to {@code output}.
// *
// * @param output an {@link OutputStream}
// * @throws IOException if there is an error writing to {@code output}
// */
// public void encode(OutputStream output) throws IOException {
// masterKey.getSecretKey().encode(output);
// subKey.getSecretKey().encode(output);
// }
//
// /**
// * Returns the keyset in encoded form.
// */
// public byte[] getEncoded() {
// final ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// encode(output);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// return output.toByteArray();
// }
//
// @Override
// public String toString() {
// return String.format("[%s, %s]", masterKey, subKey);
// }
//
// /**
// * Given the keyset's passphrase, unlocks the secret keys and returns an
// * {@link UnlockedKeySet} equivalent of {@code this}.
// *
// * @param passphrase the key's passphrase
// * @return a {@link UnlockedKeySet} equivalent of {@code this}
// * @throws CryptographicException if {@code passphrase} is incorrect
// */
// public UnlockedKeySet unlock(char[] passphrase) throws CryptographicException {
// final UnlockedMasterKey unlockedMasterKey = masterKey.unlock(passphrase);
// final UnlockedSubKey unlockedSubKey = subKey.unlock(passphrase);
// return new UnlockedKeySet(unlockedMasterKey, unlockedSubKey);
// }
// }
| import static org.fest.assertions.Assertions.*;
import java.io.FileInputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.KeySet; | package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class KeySetTest {
public static class A_Key_Set { | // Path: src/main/java/com/wesabe/grendel/openpgp/KeySet.java
// public class KeySet {
// private final MasterKey masterKey;
// private final SubKey subKey;
//
// /**
// * Loads a {@link KeySet} from an array of bytes.
// *
// * @throws CryptographicException if the encoded {@link KeySet} is malformed
// */
// public static KeySet load(byte[] encoded) throws CryptographicException {
// return load(new ByteArrayInputStream(encoded));
// }
//
// /**
// * Loads a {@link KeySet} from a {@link PGPSecretKeyRing}.
// */
// public static KeySet load(PGPSecretKeyRing keyRing) throws CryptographicException {
// final List<PGPSecretKey> secretKeys = Iterators.toList(keyRing.getSecretKeys());
// final MasterKey masterKey = MasterKey.load(secretKeys.get(0));
// final SubKey subKey = SubKey.load(secretKeys.get(1), masterKey);
//
// return new KeySet(masterKey, subKey);
// }
//
// /**
// * Loads a {@link KeySet} from an {@link InputStream}.
// */
// public static KeySet load(InputStream input) throws CryptographicException {
// try {
// final PGPSecretKeyRing keyRing = new PGPSecretKeyRing(input);
// input.close();
// return load(keyRing);
// } catch (IOException e) {
// throw new CryptographicException(e);
// } catch (PGPException e) {
// throw new CryptographicException(e);
// }
// }
//
// protected KeySet(MasterKey masterKey, SubKey subKey) {
// this.masterKey = masterKey;
// this.subKey = subKey;
// }
//
// /**
// * Returns the keyset's {@link MasterKey}.
// */
// public MasterKey getMasterKey() {
// return masterKey;
// }
//
// /**
// * Returns the keyset's {@link SubKey}.
// */
// public SubKey getSubKey() {
// return subKey;
// }
//
// /**
// * Returns the keyset's user ID.
// */
// public String getUserID() {
// return masterKey.getUserID();
// }
//
// /**
// * Writes the keyset in encoded form, to {@code output}.
// *
// * @param output an {@link OutputStream}
// * @throws IOException if there is an error writing to {@code output}
// */
// public void encode(OutputStream output) throws IOException {
// masterKey.getSecretKey().encode(output);
// subKey.getSecretKey().encode(output);
// }
//
// /**
// * Returns the keyset in encoded form.
// */
// public byte[] getEncoded() {
// final ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// encode(output);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// return output.toByteArray();
// }
//
// @Override
// public String toString() {
// return String.format("[%s, %s]", masterKey, subKey);
// }
//
// /**
// * Given the keyset's passphrase, unlocks the secret keys and returns an
// * {@link UnlockedKeySet} equivalent of {@code this}.
// *
// * @param passphrase the key's passphrase
// * @return a {@link UnlockedKeySet} equivalent of {@code this}
// * @throws CryptographicException if {@code passphrase} is incorrect
// */
// public UnlockedKeySet unlock(char[] passphrase) throws CryptographicException {
// final UnlockedMasterKey unlockedMasterKey = masterKey.unlock(passphrase);
// final UnlockedSubKey unlockedSubKey = subKey.unlock(passphrase);
// return new UnlockedKeySet(unlockedMasterKey, unlockedSubKey);
// }
// }
// Path: src/test/java/com/wesabe/grendel/openpgp/tests/KeySetTest.java
import static org.fest.assertions.Assertions.*;
import java.io.FileInputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.KeySet;
package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class KeySetTest {
public static class A_Key_Set { | private KeySet keySet; |
wesabe/grendel | src/test/java/com/wesabe/grendel/modules/tests/SecureRandomProviderTest.java | // Path: src/main/java/com/wesabe/grendel/modules/SecureRandomProvider.java
// public class SecureRandomProvider implements Provider<SecureRandom> {
// private static final int ENTROPY_UPDATE_SIZE = 64;
//
// /**
// * A scheduled, asynchronous task which generates additional entropy and
// * adds it to the PRNG's entropy pool.
// */
// private static class UpdateTask implements Runnable {
// private final SecureRandom random;
// private final Logger logger;
//
// public UpdateTask(SecureRandom random, Logger logger) {
// this.random = random;
// this.logger = logger;
// }
//
// @Override
// public void run() {
// logger.info("Generating new PRNG seed");
// final byte[] seed = SecureRandom.getSeed(ENTROPY_UPDATE_SIZE);
// logger.info("Updating PRNG seed");
// random.setSeed(seed);
// }
// }
//
// private static final Logger LOGGER = LoggerFactory.getLogger(SecureRandomProvider.class);
// private static final String PRNG_ALGORITHM = "SHA1PRNG";
// private static final String PRNG_PROVIDER = "SUN";
//
// private final SecureRandom random;
// private final ScheduledExecutorService pool;
//
// public SecureRandomProvider() {
// this.pool = Executors.newSingleThreadScheduledExecutor();
//
// LOGGER.info("Creating PRNG");
// try {
// this.random = SecureRandom.getInstance(PRNG_ALGORITHM, PRNG_PROVIDER);
// } catch (GeneralSecurityException e) {
// throw new IllegalStateException(e);
// }
// LOGGER.info("Seeding PRNG");
// random.nextInt(); // force seeding
//
// // update the PRNG every hour, starting in an hour
// pool.scheduleAtFixedRate(new UpdateTask(random, LOGGER), 1, 1, TimeUnit.HOURS);
// }
//
// @Override
// public SecureRandom get() {
// return random;
// }
// }
| import static org.fest.assertions.Assertions.*;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.modules.SecureRandomProvider; | package com.wesabe.grendel.modules.tests;
@RunWith(Enclosed.class)
public class SecureRandomProviderTest {
public static class Providing_A_CSPRNG { | // Path: src/main/java/com/wesabe/grendel/modules/SecureRandomProvider.java
// public class SecureRandomProvider implements Provider<SecureRandom> {
// private static final int ENTROPY_UPDATE_SIZE = 64;
//
// /**
// * A scheduled, asynchronous task which generates additional entropy and
// * adds it to the PRNG's entropy pool.
// */
// private static class UpdateTask implements Runnable {
// private final SecureRandom random;
// private final Logger logger;
//
// public UpdateTask(SecureRandom random, Logger logger) {
// this.random = random;
// this.logger = logger;
// }
//
// @Override
// public void run() {
// logger.info("Generating new PRNG seed");
// final byte[] seed = SecureRandom.getSeed(ENTROPY_UPDATE_SIZE);
// logger.info("Updating PRNG seed");
// random.setSeed(seed);
// }
// }
//
// private static final Logger LOGGER = LoggerFactory.getLogger(SecureRandomProvider.class);
// private static final String PRNG_ALGORITHM = "SHA1PRNG";
// private static final String PRNG_PROVIDER = "SUN";
//
// private final SecureRandom random;
// private final ScheduledExecutorService pool;
//
// public SecureRandomProvider() {
// this.pool = Executors.newSingleThreadScheduledExecutor();
//
// LOGGER.info("Creating PRNG");
// try {
// this.random = SecureRandom.getInstance(PRNG_ALGORITHM, PRNG_PROVIDER);
// } catch (GeneralSecurityException e) {
// throw new IllegalStateException(e);
// }
// LOGGER.info("Seeding PRNG");
// random.nextInt(); // force seeding
//
// // update the PRNG every hour, starting in an hour
// pool.scheduleAtFixedRate(new UpdateTask(random, LOGGER), 1, 1, TimeUnit.HOURS);
// }
//
// @Override
// public SecureRandom get() {
// return random;
// }
// }
// Path: src/test/java/com/wesabe/grendel/modules/tests/SecureRandomProviderTest.java
import static org.fest.assertions.Assertions.*;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.modules.SecureRandomProvider;
package com.wesabe.grendel.modules.tests;
@RunWith(Enclosed.class)
public class SecureRandomProviderTest {
public static class Providing_A_CSPRNG { | private SecureRandomProvider provider; |
wesabe/grendel | src/main/java/com/wesabe/grendel/Configuration.java | // Path: src/main/java/com/wesabe/grendel/modules/SecureRandomProvider.java
// public class SecureRandomProvider implements Provider<SecureRandom> {
// private static final int ENTROPY_UPDATE_SIZE = 64;
//
// /**
// * A scheduled, asynchronous task which generates additional entropy and
// * adds it to the PRNG's entropy pool.
// */
// private static class UpdateTask implements Runnable {
// private final SecureRandom random;
// private final Logger logger;
//
// public UpdateTask(SecureRandom random, Logger logger) {
// this.random = random;
// this.logger = logger;
// }
//
// @Override
// public void run() {
// logger.info("Generating new PRNG seed");
// final byte[] seed = SecureRandom.getSeed(ENTROPY_UPDATE_SIZE);
// logger.info("Updating PRNG seed");
// random.setSeed(seed);
// }
// }
//
// private static final Logger LOGGER = LoggerFactory.getLogger(SecureRandomProvider.class);
// private static final String PRNG_ALGORITHM = "SHA1PRNG";
// private static final String PRNG_PROVIDER = "SUN";
//
// private final SecureRandom random;
// private final ScheduledExecutorService pool;
//
// public SecureRandomProvider() {
// this.pool = Executors.newSingleThreadScheduledExecutor();
//
// LOGGER.info("Creating PRNG");
// try {
// this.random = SecureRandom.getInstance(PRNG_ALGORITHM, PRNG_PROVIDER);
// } catch (GeneralSecurityException e) {
// throw new IllegalStateException(e);
// }
// LOGGER.info("Seeding PRNG");
// random.nextInt(); // force seeding
//
// // update the PRNG every hour, starting in an hour
// pool.scheduleAtFixedRate(new UpdateTask(random, LOGGER), 1, 1, TimeUnit.HOURS);
// }
//
// @Override
// public SecureRandom get() {
// return random;
// }
// }
| import java.security.SecureRandom;
import org.eclipse.jetty.server.NCSARequestLog;
import org.eclipse.jetty.server.RequestLog;
import com.codahale.shore.AbstractConfiguration;
import com.google.inject.AbstractModule;
import com.google.inject.Stage;
import com.wesabe.grendel.modules.SecureRandomProvider; | package com.wesabe.grendel;
/**
* The Shore configuration class.
*
* @author coda
*/
public class Configuration extends AbstractConfiguration {
@Override
protected void configure() {
addEntityPackage("com.wesabe.grendel.entities");
addResourcePackage("org.codehaus.jackson.jaxrs");
addResourcePackage("com.wesabe.grendel.auth");
addResourcePackage("com.wesabe.grendel.resources");
addModule(new AbstractModule() {
@Override
protected void configure() { | // Path: src/main/java/com/wesabe/grendel/modules/SecureRandomProvider.java
// public class SecureRandomProvider implements Provider<SecureRandom> {
// private static final int ENTROPY_UPDATE_SIZE = 64;
//
// /**
// * A scheduled, asynchronous task which generates additional entropy and
// * adds it to the PRNG's entropy pool.
// */
// private static class UpdateTask implements Runnable {
// private final SecureRandom random;
// private final Logger logger;
//
// public UpdateTask(SecureRandom random, Logger logger) {
// this.random = random;
// this.logger = logger;
// }
//
// @Override
// public void run() {
// logger.info("Generating new PRNG seed");
// final byte[] seed = SecureRandom.getSeed(ENTROPY_UPDATE_SIZE);
// logger.info("Updating PRNG seed");
// random.setSeed(seed);
// }
// }
//
// private static final Logger LOGGER = LoggerFactory.getLogger(SecureRandomProvider.class);
// private static final String PRNG_ALGORITHM = "SHA1PRNG";
// private static final String PRNG_PROVIDER = "SUN";
//
// private final SecureRandom random;
// private final ScheduledExecutorService pool;
//
// public SecureRandomProvider() {
// this.pool = Executors.newSingleThreadScheduledExecutor();
//
// LOGGER.info("Creating PRNG");
// try {
// this.random = SecureRandom.getInstance(PRNG_ALGORITHM, PRNG_PROVIDER);
// } catch (GeneralSecurityException e) {
// throw new IllegalStateException(e);
// }
// LOGGER.info("Seeding PRNG");
// random.nextInt(); // force seeding
//
// // update the PRNG every hour, starting in an hour
// pool.scheduleAtFixedRate(new UpdateTask(random, LOGGER), 1, 1, TimeUnit.HOURS);
// }
//
// @Override
// public SecureRandom get() {
// return random;
// }
// }
// Path: src/main/java/com/wesabe/grendel/Configuration.java
import java.security.SecureRandom;
import org.eclipse.jetty.server.NCSARequestLog;
import org.eclipse.jetty.server.RequestLog;
import com.codahale.shore.AbstractConfiguration;
import com.google.inject.AbstractModule;
import com.google.inject.Stage;
import com.wesabe.grendel.modules.SecureRandomProvider;
package com.wesabe.grendel;
/**
* The Shore configuration class.
*
* @author coda
*/
public class Configuration extends AbstractConfiguration {
@Override
protected void configure() {
addEntityPackage("com.wesabe.grendel.entities");
addResourcePackage("org.codehaus.jackson.jaxrs");
addResourcePackage("com.wesabe.grendel.auth");
addResourcePackage("com.wesabe.grendel.resources");
addModule(new AbstractModule() {
@Override
protected void configure() { | bind(SecureRandom.class).toProvider(new SecureRandomProvider()); |
wesabe/grendel | src/test/java/com/wesabe/grendel/util/tests/IteratorsTest.java | // Path: src/main/java/com/wesabe/grendel/util/Iterators.java
// public final class Iterators {
// private Iterators() {}
//
// /**
// * Returns the items available via {@code iterator} as a {@link List}.
// */
// @SuppressWarnings("unchecked")
// public static <T> List<T> toList(Iterator<?> iterator) {
// return ImmutableList.copyOf((Iterator<T>) iterator);
// }
//
// /**
// * Returns the items available via {@code iterator} as a {@link Set}.
// */
// @SuppressWarnings("unchecked")
// public static <T> Set<T> toSet(Iterator<?> iterator) {
// return ImmutableSet.copyOf((Iterator<T>) iterator);
// }
// }
| import static org.fest.assertions.Assertions.*;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.wesabe.grendel.util.Iterators; | package com.wesabe.grendel.util.tests;
@RunWith(Enclosed.class)
public class IteratorsTest {
public static class Converting_An_Iterator_Into_A_List {
@Test
public void itReturnsAList() throws Exception {
final List<String> numbers = ImmutableList.of("one", "two", "three"); | // Path: src/main/java/com/wesabe/grendel/util/Iterators.java
// public final class Iterators {
// private Iterators() {}
//
// /**
// * Returns the items available via {@code iterator} as a {@link List}.
// */
// @SuppressWarnings("unchecked")
// public static <T> List<T> toList(Iterator<?> iterator) {
// return ImmutableList.copyOf((Iterator<T>) iterator);
// }
//
// /**
// * Returns the items available via {@code iterator} as a {@link Set}.
// */
// @SuppressWarnings("unchecked")
// public static <T> Set<T> toSet(Iterator<?> iterator) {
// return ImmutableSet.copyOf((Iterator<T>) iterator);
// }
// }
// Path: src/test/java/com/wesabe/grendel/util/tests/IteratorsTest.java
import static org.fest.assertions.Assertions.*;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.wesabe.grendel.util.Iterators;
package com.wesabe.grendel.util.tests;
@RunWith(Enclosed.class)
public class IteratorsTest {
public static class Converting_An_Iterator_Into_A_List {
@Test
public void itReturnsAList() throws Exception {
final List<String> numbers = ImmutableList.of("one", "two", "three"); | final List<String> otherNumbers = Iterators.toList(numbers.iterator()); |
wesabe/grendel | src/test/java/com/wesabe/grendel/openpgp/tests/HashAlgorithmTest.java | // Path: src/main/java/com/wesabe/grendel/openpgp/HashAlgorithm.java
// public enum HashAlgorithm implements IntegerEquivalent {
// /**
// * MD5
// *
// * @deprecated Prohibited by RFC 4880, thoroughly broken.
// * @see <a href="http://www.ietf.org/rfc/rfc4880.txt">Section 14, RFC 4880</a>
// * @see <a href="http://eprint.iacr.org/2006/105">Tunnels in Hash Functions: MD5 Collisions Within a Minute</a>
// */
// @Deprecated
// MD5( "MD5", HashAlgorithmTags.MD5),
//
// /**
// * SHA-1
// * @deprecated Unsuitable for usage in new systems.
// * @see <a href="http://eurocrypt2009rump.cr.yp.to/837a0a8086fa6ca714249409ddfae43d.pdf">SHA-1 collisions now 2⁵²</a>
// */
// @Deprecated
// SHA_1( "SHA-1", HashAlgorithmTags.SHA1),
//
// /**
// * RIPEMD-160
// *
// * @deprecated Based on same design as {@link #MD5} and {@link #SHA_1}.
// */
// @Deprecated
// RIPEMD_160( "RIPEMD-160", HashAlgorithmTags.RIPEMD160),
//
// /**
// * Double-width SHA-1
// *
// * @deprecated Not specified by RFC 4880. Only used by CKT builds of PGP.
// * @see <a href="http://www.ietf.org/rfc/rfc2440.txt">RFC 2440</a>
// */
// @Deprecated
// DOUBLE_SHA( "2xSHA-1", HashAlgorithmTags.DOUBLE_SHA),
//
// /**
// * MD2
// *
// * @deprecated Not specified by RFC 4880. Only used by CKT builds of PGP.
// * @see <a href="http://www.ietf.org/rfc/rfc2440.txt">RFC 2440</a>
// */
// @Deprecated
// MD2( "MD2", HashAlgorithmTags.MD2),
//
// /**
// * TIGER-192
// *
// * @deprecated Not specified by RFC 4880. Only used by CKT builds of PGP.
// * @see <a href="http://www.ietf.org/rfc/rfc2440.txt">RFC 2440</a>
// */
// @Deprecated
// TIGER_192( "TIGER-192", HashAlgorithmTags.TIGER_192),
//
// /**
// * HAVAL-5-160
// *
// * @deprecated Not specified by RFC 4880. Only used by CKT builds of PGP.
// * @see <a href="http://www.ietf.org/rfc/rfc2440.txt">RFC 2440</a>
// */
// @Deprecated
// HAVAL_5_160( "HAVAL-5-160", HashAlgorithmTags.HAVAL_5_160),
//
// /**
// * SHA-224
// *
// * Use only for DSS compatibility.
// */
// SHA_224( "SHA-224", HashAlgorithmTags.SHA224),
//
// /**
// * SHA-256
// */
// SHA_256( "SHA-256", HashAlgorithmTags.SHA256),
//
// /**
// * SHA-384
// *
// * Use only for DSS compatibility.
// */
// SHA_384( "SHA-384", HashAlgorithmTags.SHA384),
//
// /**
// * SHA-512
// */
// SHA_512( "SHA-512", HashAlgorithmTags.SHA512);
//
// /**
// * The default hash algorithm to use.
// */
// public static final HashAlgorithm DEFAULT = SHA_512;
//
// /**
// * A list of hash algorithms which are acceptable for use in Grendel.
// */
// public static final List<HashAlgorithm> ACCEPTABLE_ALGORITHMS =
// ImmutableList.of(SHA_224, SHA_256, SHA_384, SHA_512, SHA_1);
//
// private final int value;
// private final String name;
//
// private HashAlgorithm(String name, int value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * Returns the equivalent value of {@link HashAlgorithmTags}.
// */
// @Override
// public int toInteger() {
// return value;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
| import static org.fest.assertions.Assertions.*;
import org.bouncycastle.bcpg.HashAlgorithmTags;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.google.inject.internal.ImmutableList;
import com.wesabe.grendel.openpgp.HashAlgorithm; | package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class HashAlgorithmTest {
@SuppressWarnings("deprecation")
public static class MD5 {
@Test
public void itHasTheSameValueAsTheBCTag() throws Exception { | // Path: src/main/java/com/wesabe/grendel/openpgp/HashAlgorithm.java
// public enum HashAlgorithm implements IntegerEquivalent {
// /**
// * MD5
// *
// * @deprecated Prohibited by RFC 4880, thoroughly broken.
// * @see <a href="http://www.ietf.org/rfc/rfc4880.txt">Section 14, RFC 4880</a>
// * @see <a href="http://eprint.iacr.org/2006/105">Tunnels in Hash Functions: MD5 Collisions Within a Minute</a>
// */
// @Deprecated
// MD5( "MD5", HashAlgorithmTags.MD5),
//
// /**
// * SHA-1
// * @deprecated Unsuitable for usage in new systems.
// * @see <a href="http://eurocrypt2009rump.cr.yp.to/837a0a8086fa6ca714249409ddfae43d.pdf">SHA-1 collisions now 2⁵²</a>
// */
// @Deprecated
// SHA_1( "SHA-1", HashAlgorithmTags.SHA1),
//
// /**
// * RIPEMD-160
// *
// * @deprecated Based on same design as {@link #MD5} and {@link #SHA_1}.
// */
// @Deprecated
// RIPEMD_160( "RIPEMD-160", HashAlgorithmTags.RIPEMD160),
//
// /**
// * Double-width SHA-1
// *
// * @deprecated Not specified by RFC 4880. Only used by CKT builds of PGP.
// * @see <a href="http://www.ietf.org/rfc/rfc2440.txt">RFC 2440</a>
// */
// @Deprecated
// DOUBLE_SHA( "2xSHA-1", HashAlgorithmTags.DOUBLE_SHA),
//
// /**
// * MD2
// *
// * @deprecated Not specified by RFC 4880. Only used by CKT builds of PGP.
// * @see <a href="http://www.ietf.org/rfc/rfc2440.txt">RFC 2440</a>
// */
// @Deprecated
// MD2( "MD2", HashAlgorithmTags.MD2),
//
// /**
// * TIGER-192
// *
// * @deprecated Not specified by RFC 4880. Only used by CKT builds of PGP.
// * @see <a href="http://www.ietf.org/rfc/rfc2440.txt">RFC 2440</a>
// */
// @Deprecated
// TIGER_192( "TIGER-192", HashAlgorithmTags.TIGER_192),
//
// /**
// * HAVAL-5-160
// *
// * @deprecated Not specified by RFC 4880. Only used by CKT builds of PGP.
// * @see <a href="http://www.ietf.org/rfc/rfc2440.txt">RFC 2440</a>
// */
// @Deprecated
// HAVAL_5_160( "HAVAL-5-160", HashAlgorithmTags.HAVAL_5_160),
//
// /**
// * SHA-224
// *
// * Use only for DSS compatibility.
// */
// SHA_224( "SHA-224", HashAlgorithmTags.SHA224),
//
// /**
// * SHA-256
// */
// SHA_256( "SHA-256", HashAlgorithmTags.SHA256),
//
// /**
// * SHA-384
// *
// * Use only for DSS compatibility.
// */
// SHA_384( "SHA-384", HashAlgorithmTags.SHA384),
//
// /**
// * SHA-512
// */
// SHA_512( "SHA-512", HashAlgorithmTags.SHA512);
//
// /**
// * The default hash algorithm to use.
// */
// public static final HashAlgorithm DEFAULT = SHA_512;
//
// /**
// * A list of hash algorithms which are acceptable for use in Grendel.
// */
// public static final List<HashAlgorithm> ACCEPTABLE_ALGORITHMS =
// ImmutableList.of(SHA_224, SHA_256, SHA_384, SHA_512, SHA_1);
//
// private final int value;
// private final String name;
//
// private HashAlgorithm(String name, int value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * Returns the equivalent value of {@link HashAlgorithmTags}.
// */
// @Override
// public int toInteger() {
// return value;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// Path: src/test/java/com/wesabe/grendel/openpgp/tests/HashAlgorithmTest.java
import static org.fest.assertions.Assertions.*;
import org.bouncycastle.bcpg.HashAlgorithmTags;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.google.inject.internal.ImmutableList;
import com.wesabe.grendel.openpgp.HashAlgorithm;
package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class HashAlgorithmTest {
@SuppressWarnings("deprecation")
public static class MD5 {
@Test
public void itHasTheSameValueAsTheBCTag() throws Exception { | assertThat(HashAlgorithm.MD5.toInteger()).isEqualTo(HashAlgorithmTags.MD5); |
wesabe/grendel | src/test/java/com/wesabe/grendel/openpgp/tests/SignatureTypeTest.java | // Path: src/main/java/com/wesabe/grendel/openpgp/SignatureType.java
// public enum SignatureType implements IntegerEquivalent {
// /**
// * A signature of a binary document.
// *
// * This means the signer owns it, created it, or certifies that it has not
// * been modified.
// */
// BINARY_DOCUMENT( "binary document", PGPSignature.BINARY_DOCUMENT),
//
// /**
// * A signature of a canonical text document.
// *
// * This means the signer owns it, created it, or certifies that it has not
// * been modified. The signature is calculated over the text data with its
// * line endings converted to {@code 0x0D 0x0A} ({@code CR+LF}).
// */
// TEXT_DOCUMENT( "text document", PGPSignature.CANONICAL_TEXT_DOCUMENT),
//
// /**
// * A signature of only its own subpacket contents.
// */
// STANDALONE( "standalone", PGPSignature.STAND_ALONE),
//
// /**
// * A signature indicating the signer does not make any particular assertion
// * as to how well the signer has checked that the owner of the key is in
// * fact the person described by the User ID.
// */
// DEFAULT_CERTIFICATION( "default certification", PGPSignature.DEFAULT_CERTIFICATION),
//
// /**
// * A signature indicating the signer has not done any verification of
// * the signed key's claim of identity.
// */
// NO_CERTIFICATION( "no certification", PGPSignature.NO_CERTIFICATION),
//
// /**
// * A signature indicating the signer has done some casual verification of
// * the signed key's claim of identity.
// */
// CASUAL_CERTIFICATION( "casual certification", PGPSignature.CASUAL_CERTIFICATION),
//
// /**
// * A signature indicating the signer has done substantial verification of
// * the signed key's claim of identity.
// */
// POSITIVE_CERTIFICATION( "positive certification", PGPSignature.POSITIVE_CERTIFICATION),
//
// /**
// * A signature by the top-level signing key indicating that it owns the
// * signed subkey.
// */
// SUBKEY_BINDING( "subkey binding", PGPSignature.SUBKEY_BINDING),
//
// /**
// * A signature by a signing subkey, indicating that it is owned by the
// * signed primary key.
// */
// PRIMARY_KEY_BINDING( "primary key binding", PGPSignature.PRIMARYKEY_BINDING),
//
// /**
// * A signature calculated directly on a key.
// *
// * It binds the information in the Signature subpackets to the key, and is
// * appropriate to be used for subpackets that provide information about the
// * key, such as the Revocation Key subpacket. It is also appropriate for
// * statements that non-self certifiers want to make about the key itself,
// * rather than the binding between a key and a name.
// */
// DIRECT_KEY( "direct key", PGPSignature.DIRECT_KEY),
//
// /**
// * A signature calculated directly on the key being revoked.
// *
// * A revoked key is not to be used. Only revocation signatures by the key
// * being revoked, or by an authorized revocation key, should be considered
// * valid revocation signatures.
// */
// KEY_REVOCATION( "key revocation", PGPSignature.KEY_REVOCATION),
//
// /**
// * A signature calculated directly on the subkey being revoked.
// *
// * A revoked subkey is not to be used. Only revocation signatures by the
// * top-level signature key that is bound to this subkey, or by an authorized
// * revocation key, should be considered valid revocation signatures.
// */
// SUBKEY_REVOCATION( "subkey revocation", PGPSignature.SUBKEY_REVOCATION),
//
// /**
// * A signature revoking an earlier {@link #DEFAULT_CERTIFICATION},
// * {@link #NO_CERTIFICATION}, {@link #CASUAL_CERTIFICATION},
// * {@link #POSITIVE_CERTIFICATION} or {@link #DIRECT_KEY} signature.
// */
// CERTIFICATION_REVOCATION( "certificate revocation", PGPSignature.CERTIFICATION_REVOCATION),
//
// /**
// * A timestamp signature.
// *
// * This signature is only meaningful for the timestamp contained in it.
// */
// TIMESTAMP( "timestamp", PGPSignature.TIMESTAMP),
//
// /**
// * A signature over some other OpenPGP Signature packet(s).
// *
// * It is analogous to a notary seal on the signed data.
// */
// // this value isn't included as a constant in PGPSignature
// THIRD_PARTY( "third-party confirmation", 0x50);
//
// private final String name;
// private final int value;
//
// private SignatureType(String name, int value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public int toInteger() {
// return value;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
| import static org.fest.assertions.Assertions.*;
import org.bouncycastle.openpgp.PGPSignature;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.SignatureType; | package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class SignatureTypeTest {
public static class Binary_Document {
@Test
public void itHasTheSameValueAsTheBCTag() throws Exception { | // Path: src/main/java/com/wesabe/grendel/openpgp/SignatureType.java
// public enum SignatureType implements IntegerEquivalent {
// /**
// * A signature of a binary document.
// *
// * This means the signer owns it, created it, or certifies that it has not
// * been modified.
// */
// BINARY_DOCUMENT( "binary document", PGPSignature.BINARY_DOCUMENT),
//
// /**
// * A signature of a canonical text document.
// *
// * This means the signer owns it, created it, or certifies that it has not
// * been modified. The signature is calculated over the text data with its
// * line endings converted to {@code 0x0D 0x0A} ({@code CR+LF}).
// */
// TEXT_DOCUMENT( "text document", PGPSignature.CANONICAL_TEXT_DOCUMENT),
//
// /**
// * A signature of only its own subpacket contents.
// */
// STANDALONE( "standalone", PGPSignature.STAND_ALONE),
//
// /**
// * A signature indicating the signer does not make any particular assertion
// * as to how well the signer has checked that the owner of the key is in
// * fact the person described by the User ID.
// */
// DEFAULT_CERTIFICATION( "default certification", PGPSignature.DEFAULT_CERTIFICATION),
//
// /**
// * A signature indicating the signer has not done any verification of
// * the signed key's claim of identity.
// */
// NO_CERTIFICATION( "no certification", PGPSignature.NO_CERTIFICATION),
//
// /**
// * A signature indicating the signer has done some casual verification of
// * the signed key's claim of identity.
// */
// CASUAL_CERTIFICATION( "casual certification", PGPSignature.CASUAL_CERTIFICATION),
//
// /**
// * A signature indicating the signer has done substantial verification of
// * the signed key's claim of identity.
// */
// POSITIVE_CERTIFICATION( "positive certification", PGPSignature.POSITIVE_CERTIFICATION),
//
// /**
// * A signature by the top-level signing key indicating that it owns the
// * signed subkey.
// */
// SUBKEY_BINDING( "subkey binding", PGPSignature.SUBKEY_BINDING),
//
// /**
// * A signature by a signing subkey, indicating that it is owned by the
// * signed primary key.
// */
// PRIMARY_KEY_BINDING( "primary key binding", PGPSignature.PRIMARYKEY_BINDING),
//
// /**
// * A signature calculated directly on a key.
// *
// * It binds the information in the Signature subpackets to the key, and is
// * appropriate to be used for subpackets that provide information about the
// * key, such as the Revocation Key subpacket. It is also appropriate for
// * statements that non-self certifiers want to make about the key itself,
// * rather than the binding between a key and a name.
// */
// DIRECT_KEY( "direct key", PGPSignature.DIRECT_KEY),
//
// /**
// * A signature calculated directly on the key being revoked.
// *
// * A revoked key is not to be used. Only revocation signatures by the key
// * being revoked, or by an authorized revocation key, should be considered
// * valid revocation signatures.
// */
// KEY_REVOCATION( "key revocation", PGPSignature.KEY_REVOCATION),
//
// /**
// * A signature calculated directly on the subkey being revoked.
// *
// * A revoked subkey is not to be used. Only revocation signatures by the
// * top-level signature key that is bound to this subkey, or by an authorized
// * revocation key, should be considered valid revocation signatures.
// */
// SUBKEY_REVOCATION( "subkey revocation", PGPSignature.SUBKEY_REVOCATION),
//
// /**
// * A signature revoking an earlier {@link #DEFAULT_CERTIFICATION},
// * {@link #NO_CERTIFICATION}, {@link #CASUAL_CERTIFICATION},
// * {@link #POSITIVE_CERTIFICATION} or {@link #DIRECT_KEY} signature.
// */
// CERTIFICATION_REVOCATION( "certificate revocation", PGPSignature.CERTIFICATION_REVOCATION),
//
// /**
// * A timestamp signature.
// *
// * This signature is only meaningful for the timestamp contained in it.
// */
// TIMESTAMP( "timestamp", PGPSignature.TIMESTAMP),
//
// /**
// * A signature over some other OpenPGP Signature packet(s).
// *
// * It is analogous to a notary seal on the signed data.
// */
// // this value isn't included as a constant in PGPSignature
// THIRD_PARTY( "third-party confirmation", 0x50);
//
// private final String name;
// private final int value;
//
// private SignatureType(String name, int value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public int toInteger() {
// return value;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// Path: src/test/java/com/wesabe/grendel/openpgp/tests/SignatureTypeTest.java
import static org.fest.assertions.Assertions.*;
import org.bouncycastle.openpgp.PGPSignature;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.openpgp.SignatureType;
package com.wesabe.grendel.openpgp.tests;
@RunWith(Enclosed.class)
public class SignatureTypeTest {
public static class Binary_Document {
@Test
public void itHasTheSameValueAsTheBCTag() throws Exception { | assertThat(SignatureType.BINARY_DOCUMENT.toInteger()).isEqualTo(PGPSignature.BINARY_DOCUMENT); |
wesabe/grendel | src/test/java/com/wesabe/grendel/representations/tests/UpdateUserRepresentationTest.java | // Path: src/main/java/com/wesabe/grendel/representations/UpdateUserRepresentation.java
// public class UpdateUserRepresentation implements Validatable {
// private char[] password;
//
// @JsonGetter("password")
// public char[] getPassword() {
// return password;
// }
//
// @JsonSetter("password")
// public void setPassword(char[] password) {
// this.password = Arrays.copyOf(password, password.length);
// Arrays.fill(password, '\0');
// }
//
// @Override
// public void validate() throws ValidationException {
// final ValidationException error = new ValidationException();
//
// if ((password == null) || (password.length == 0)) {
// error.missingRequiredProperty("password");
// }
//
// if (error.hasReasons()) {
// throw error;
// }
// }
//
// public void sanitize() {
// Arrays.fill(password, '\0');
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/representations/ValidationException.java
// public class ValidationException extends WebApplicationException {
// private static final int UNPROCESSABLE_ENTITY = 422;
// private static final long serialVersionUID = -6730797215368434430L;
// private final StringBuilder msgBuilder;
// private boolean hasReasons = false;
//
// public ValidationException() {
// super();
// this.msgBuilder = new StringBuilder(
// "Grendel was unable to process your request for the following reason(s):\n\n"
// );
// }
//
// /**
// * Adds a reason for validation failure to the list.
// */
// public void addReason(String reason) {
// this.hasReasons = true;
// msgBuilder.append("* ").append(reason).append('\n');
// }
//
// /**
// * Adds a failure to include a required property to the list.
// */
// public void missingRequiredProperty(String propertyName) {
// addReason("missing required property: " + propertyName);
// }
//
// /**
// * Returns {@code true} if the exception has reasons, {@code false}
// * otherwise.
// */
// public boolean hasReasons() {
// return hasReasons;
// }
//
// @Override
// public Response getResponse() {
// return Response
// .status(UNPROCESSABLE_ENTITY)
// .type(MediaType.TEXT_PLAIN)
// .entity(msgBuilder.toString())
// .build();
// }
// }
| import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.representations.UpdateUserRepresentation;
import com.wesabe.grendel.representations.ValidationException; | package com.wesabe.grendel.representations.tests;
@RunWith(Enclosed.class)
public class UpdateUserRepresentationTest {
public static class A_Valid_New_User_Request { | // Path: src/main/java/com/wesabe/grendel/representations/UpdateUserRepresentation.java
// public class UpdateUserRepresentation implements Validatable {
// private char[] password;
//
// @JsonGetter("password")
// public char[] getPassword() {
// return password;
// }
//
// @JsonSetter("password")
// public void setPassword(char[] password) {
// this.password = Arrays.copyOf(password, password.length);
// Arrays.fill(password, '\0');
// }
//
// @Override
// public void validate() throws ValidationException {
// final ValidationException error = new ValidationException();
//
// if ((password == null) || (password.length == 0)) {
// error.missingRequiredProperty("password");
// }
//
// if (error.hasReasons()) {
// throw error;
// }
// }
//
// public void sanitize() {
// Arrays.fill(password, '\0');
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/representations/ValidationException.java
// public class ValidationException extends WebApplicationException {
// private static final int UNPROCESSABLE_ENTITY = 422;
// private static final long serialVersionUID = -6730797215368434430L;
// private final StringBuilder msgBuilder;
// private boolean hasReasons = false;
//
// public ValidationException() {
// super();
// this.msgBuilder = new StringBuilder(
// "Grendel was unable to process your request for the following reason(s):\n\n"
// );
// }
//
// /**
// * Adds a reason for validation failure to the list.
// */
// public void addReason(String reason) {
// this.hasReasons = true;
// msgBuilder.append("* ").append(reason).append('\n');
// }
//
// /**
// * Adds a failure to include a required property to the list.
// */
// public void missingRequiredProperty(String propertyName) {
// addReason("missing required property: " + propertyName);
// }
//
// /**
// * Returns {@code true} if the exception has reasons, {@code false}
// * otherwise.
// */
// public boolean hasReasons() {
// return hasReasons;
// }
//
// @Override
// public Response getResponse() {
// return Response
// .status(UNPROCESSABLE_ENTITY)
// .type(MediaType.TEXT_PLAIN)
// .entity(msgBuilder.toString())
// .build();
// }
// }
// Path: src/test/java/com/wesabe/grendel/representations/tests/UpdateUserRepresentationTest.java
import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.representations.UpdateUserRepresentation;
import com.wesabe.grendel.representations.ValidationException;
package com.wesabe.grendel.representations.tests;
@RunWith(Enclosed.class)
public class UpdateUserRepresentationTest {
public static class A_Valid_New_User_Request { | private UpdateUserRepresentation req; |
wesabe/grendel | src/test/java/com/wesabe/grendel/representations/tests/UpdateUserRepresentationTest.java | // Path: src/main/java/com/wesabe/grendel/representations/UpdateUserRepresentation.java
// public class UpdateUserRepresentation implements Validatable {
// private char[] password;
//
// @JsonGetter("password")
// public char[] getPassword() {
// return password;
// }
//
// @JsonSetter("password")
// public void setPassword(char[] password) {
// this.password = Arrays.copyOf(password, password.length);
// Arrays.fill(password, '\0');
// }
//
// @Override
// public void validate() throws ValidationException {
// final ValidationException error = new ValidationException();
//
// if ((password == null) || (password.length == 0)) {
// error.missingRequiredProperty("password");
// }
//
// if (error.hasReasons()) {
// throw error;
// }
// }
//
// public void sanitize() {
// Arrays.fill(password, '\0');
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/representations/ValidationException.java
// public class ValidationException extends WebApplicationException {
// private static final int UNPROCESSABLE_ENTITY = 422;
// private static final long serialVersionUID = -6730797215368434430L;
// private final StringBuilder msgBuilder;
// private boolean hasReasons = false;
//
// public ValidationException() {
// super();
// this.msgBuilder = new StringBuilder(
// "Grendel was unable to process your request for the following reason(s):\n\n"
// );
// }
//
// /**
// * Adds a reason for validation failure to the list.
// */
// public void addReason(String reason) {
// this.hasReasons = true;
// msgBuilder.append("* ").append(reason).append('\n');
// }
//
// /**
// * Adds a failure to include a required property to the list.
// */
// public void missingRequiredProperty(String propertyName) {
// addReason("missing required property: " + propertyName);
// }
//
// /**
// * Returns {@code true} if the exception has reasons, {@code false}
// * otherwise.
// */
// public boolean hasReasons() {
// return hasReasons;
// }
//
// @Override
// public Response getResponse() {
// return Response
// .status(UNPROCESSABLE_ENTITY)
// .type(MediaType.TEXT_PLAIN)
// .entity(msgBuilder.toString())
// .build();
// }
// }
| import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.representations.UpdateUserRepresentation;
import com.wesabe.grendel.representations.ValidationException; | package com.wesabe.grendel.representations.tests;
@RunWith(Enclosed.class)
public class UpdateUserRepresentationTest {
public static class A_Valid_New_User_Request {
private UpdateUserRepresentation req;
@Before
public void setup() throws Exception {
this.req = new UpdateUserRepresentation();
req.setPassword("happenstance".toCharArray());
}
@Test
public void itIsValid() throws Exception {
try {
req.validate();
assertThat(true).isTrue(); | // Path: src/main/java/com/wesabe/grendel/representations/UpdateUserRepresentation.java
// public class UpdateUserRepresentation implements Validatable {
// private char[] password;
//
// @JsonGetter("password")
// public char[] getPassword() {
// return password;
// }
//
// @JsonSetter("password")
// public void setPassword(char[] password) {
// this.password = Arrays.copyOf(password, password.length);
// Arrays.fill(password, '\0');
// }
//
// @Override
// public void validate() throws ValidationException {
// final ValidationException error = new ValidationException();
//
// if ((password == null) || (password.length == 0)) {
// error.missingRequiredProperty("password");
// }
//
// if (error.hasReasons()) {
// throw error;
// }
// }
//
// public void sanitize() {
// Arrays.fill(password, '\0');
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/representations/ValidationException.java
// public class ValidationException extends WebApplicationException {
// private static final int UNPROCESSABLE_ENTITY = 422;
// private static final long serialVersionUID = -6730797215368434430L;
// private final StringBuilder msgBuilder;
// private boolean hasReasons = false;
//
// public ValidationException() {
// super();
// this.msgBuilder = new StringBuilder(
// "Grendel was unable to process your request for the following reason(s):\n\n"
// );
// }
//
// /**
// * Adds a reason for validation failure to the list.
// */
// public void addReason(String reason) {
// this.hasReasons = true;
// msgBuilder.append("* ").append(reason).append('\n');
// }
//
// /**
// * Adds a failure to include a required property to the list.
// */
// public void missingRequiredProperty(String propertyName) {
// addReason("missing required property: " + propertyName);
// }
//
// /**
// * Returns {@code true} if the exception has reasons, {@code false}
// * otherwise.
// */
// public boolean hasReasons() {
// return hasReasons;
// }
//
// @Override
// public Response getResponse() {
// return Response
// .status(UNPROCESSABLE_ENTITY)
// .type(MediaType.TEXT_PLAIN)
// .entity(msgBuilder.toString())
// .build();
// }
// }
// Path: src/test/java/com/wesabe/grendel/representations/tests/UpdateUserRepresentationTest.java
import static org.fest.assertions.Assertions.*;
import static org.junit.Assert.*;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.wesabe.grendel.representations.UpdateUserRepresentation;
import com.wesabe.grendel.representations.ValidationException;
package com.wesabe.grendel.representations.tests;
@RunWith(Enclosed.class)
public class UpdateUserRepresentationTest {
public static class A_Valid_New_User_Request {
private UpdateUserRepresentation req;
@Before
public void setup() throws Exception {
this.req = new UpdateUserRepresentation();
req.setPassword("happenstance".toCharArray());
}
@Test
public void itIsValid() throws Exception {
try {
req.validate();
assertThat(true).isTrue(); | } catch (ValidationException e) { |
wesabe/grendel | src/main/java/com/wesabe/grendel/openpgp/KeySignature.java | // Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalents.java
// public final class IntegerEquivalents {
// private IntegerEquivalents() {}
//
// /**
// * Returns the collection of {@code integerEquivs} as an array of {@code int}s.
// */
// public static int[] toIntArray(Collection<? extends IntegerEquivalent> integerEquivs) {
// final int[] values = new int[integerEquivs.size()];
// int i = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// values[i] = integerEquiv.toInteger();
// i++;
// }
// return values;
// }
//
// /**
// * Returns the set of {@code integerEquivs} as a bitmask {@code int}.
// */
// public static int toBitmask(Set<? extends IntegerEquivalent> integerEquivs) {
// int value = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// value |= integerEquiv.toInteger();
// }
// return value;
// }
//
// /**
// * Returns the instance of {@code enumType} which is equivalent to
// * {@code value}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> T fromInt(Class<T> enumType, int value) throws IllegalArgumentException {
// for (T constant : enumType.getEnumConstants()) {
// if (constant.toInteger() == value) {
// return constant;
// }
// }
// throw new IllegalArgumentException("No enum constant of " + enumType + " exists with value " + value);
// }
//
// /**
// * Returns the list of the instances of {@code enumType} which are equivalent
// * to {@code values}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> List<T> fromIntArray(Class<T> enumType, int[] values) throws IllegalArgumentException {
// final ImmutableList.Builder<T> builder = ImmutableList.builder();
// for (int value : values) {
// builder.add(fromInt(enumType, value));
// }
// return builder.build();
// }
//
// /**
// * Returns the {@code bitMask} as a set of {@link IntegerEquivalent}s.
// */
// public static <T extends IntegerEquivalent> Set<T> fromBitmask(Class<T> enumType, int bitMask) throws IllegalArgumentException {
// final ImmutableSet.Builder<T> builder = ImmutableSet.builder();
// for (T constant : enumType.getEnumConstants()) {
// if ((bitMask & constant.toInteger()) != 0) {
// builder.add(constant);
// }
// }
// return builder.build();
// }
// }
| import java.security.SignatureException;
import java.util.List;
import java.util.Set;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureSubpacketVector;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.wesabe.grendel.util.IntegerEquivalents; | package com.wesabe.grendel.openpgp;
/**
* A signature on a {@link MasterKey} or {@link SubKey}.
*
* @author coda
*/
public class KeySignature {
private final PGPSignature signature;
private final PGPSignatureSubpacketVector subpackets;
/**
* Creates a new {@link KeySignature} given a {@link PGPSignature}.
*
* @param signature a {@link PGPSignature} instance
*/
public KeySignature(PGPSignature signature) {
this.signature = signature;
this.subpackets = signature.getHashedSubPackets();
}
/**
* Returns the type of signature {@code this} is.
*/
public SignatureType getSignatureType() { | // Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalents.java
// public final class IntegerEquivalents {
// private IntegerEquivalents() {}
//
// /**
// * Returns the collection of {@code integerEquivs} as an array of {@code int}s.
// */
// public static int[] toIntArray(Collection<? extends IntegerEquivalent> integerEquivs) {
// final int[] values = new int[integerEquivs.size()];
// int i = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// values[i] = integerEquiv.toInteger();
// i++;
// }
// return values;
// }
//
// /**
// * Returns the set of {@code integerEquivs} as a bitmask {@code int}.
// */
// public static int toBitmask(Set<? extends IntegerEquivalent> integerEquivs) {
// int value = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// value |= integerEquiv.toInteger();
// }
// return value;
// }
//
// /**
// * Returns the instance of {@code enumType} which is equivalent to
// * {@code value}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> T fromInt(Class<T> enumType, int value) throws IllegalArgumentException {
// for (T constant : enumType.getEnumConstants()) {
// if (constant.toInteger() == value) {
// return constant;
// }
// }
// throw new IllegalArgumentException("No enum constant of " + enumType + " exists with value " + value);
// }
//
// /**
// * Returns the list of the instances of {@code enumType} which are equivalent
// * to {@code values}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> List<T> fromIntArray(Class<T> enumType, int[] values) throws IllegalArgumentException {
// final ImmutableList.Builder<T> builder = ImmutableList.builder();
// for (int value : values) {
// builder.add(fromInt(enumType, value));
// }
// return builder.build();
// }
//
// /**
// * Returns the {@code bitMask} as a set of {@link IntegerEquivalent}s.
// */
// public static <T extends IntegerEquivalent> Set<T> fromBitmask(Class<T> enumType, int bitMask) throws IllegalArgumentException {
// final ImmutableSet.Builder<T> builder = ImmutableSet.builder();
// for (T constant : enumType.getEnumConstants()) {
// if ((bitMask & constant.toInteger()) != 0) {
// builder.add(constant);
// }
// }
// return builder.build();
// }
// }
// Path: src/main/java/com/wesabe/grendel/openpgp/KeySignature.java
import java.security.SignatureException;
import java.util.List;
import java.util.Set;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureSubpacketVector;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.wesabe.grendel.util.IntegerEquivalents;
package com.wesabe.grendel.openpgp;
/**
* A signature on a {@link MasterKey} or {@link SubKey}.
*
* @author coda
*/
public class KeySignature {
private final PGPSignature signature;
private final PGPSignatureSubpacketVector subpackets;
/**
* Creates a new {@link KeySignature} given a {@link PGPSignature}.
*
* @param signature a {@link PGPSignature} instance
*/
public KeySignature(PGPSignature signature) {
this.signature = signature;
this.subpackets = signature.getHashedSubPackets();
}
/**
* Returns the type of signature {@code this} is.
*/
public SignatureType getSignatureType() { | return IntegerEquivalents.fromInt(SignatureType.class, signature.getSignatureType()); |
wesabe/grendel | src/main/java/com/wesabe/grendel/openpgp/AbstractKey.java | // Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalents.java
// public final class IntegerEquivalents {
// private IntegerEquivalents() {}
//
// /**
// * Returns the collection of {@code integerEquivs} as an array of {@code int}s.
// */
// public static int[] toIntArray(Collection<? extends IntegerEquivalent> integerEquivs) {
// final int[] values = new int[integerEquivs.size()];
// int i = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// values[i] = integerEquiv.toInteger();
// i++;
// }
// return values;
// }
//
// /**
// * Returns the set of {@code integerEquivs} as a bitmask {@code int}.
// */
// public static int toBitmask(Set<? extends IntegerEquivalent> integerEquivs) {
// int value = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// value |= integerEquiv.toInteger();
// }
// return value;
// }
//
// /**
// * Returns the instance of {@code enumType} which is equivalent to
// * {@code value}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> T fromInt(Class<T> enumType, int value) throws IllegalArgumentException {
// for (T constant : enumType.getEnumConstants()) {
// if (constant.toInteger() == value) {
// return constant;
// }
// }
// throw new IllegalArgumentException("No enum constant of " + enumType + " exists with value " + value);
// }
//
// /**
// * Returns the list of the instances of {@code enumType} which are equivalent
// * to {@code values}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> List<T> fromIntArray(Class<T> enumType, int[] values) throws IllegalArgumentException {
// final ImmutableList.Builder<T> builder = ImmutableList.builder();
// for (int value : values) {
// builder.add(fromInt(enumType, value));
// }
// return builder.build();
// }
//
// /**
// * Returns the {@code bitMask} as a set of {@link IntegerEquivalent}s.
// */
// public static <T extends IntegerEquivalent> Set<T> fromBitmask(Class<T> enumType, int bitMask) throws IllegalArgumentException {
// final ImmutableSet.Builder<T> builder = ImmutableSet.builder();
// for (T constant : enumType.getEnumConstants()) {
// if ((bitMask & constant.toInteger()) != 0) {
// builder.add(constant);
// }
// }
// return builder.build();
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/util/Iterators.java
// public final class Iterators {
// private Iterators() {}
//
// /**
// * Returns the items available via {@code iterator} as a {@link List}.
// */
// @SuppressWarnings("unchecked")
// public static <T> List<T> toList(Iterator<?> iterator) {
// return ImmutableList.copyOf((Iterator<T>) iterator);
// }
//
// /**
// * Returns the items available via {@code iterator} as a {@link Set}.
// */
// @SuppressWarnings("unchecked")
// public static <T> Set<T> toSet(Iterator<?> iterator) {
// return ImmutableSet.copyOf((Iterator<T>) iterator);
// }
// }
| import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSignature;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.google.common.collect.ImmutableSet;
import com.wesabe.grendel.util.IntegerEquivalents;
import com.wesabe.grendel.util.Iterators; | package com.wesabe.grendel.openpgp;
/**
* An abstract base class for asymmetric PGP public keys and their corresponding
* secret keys.
*
* @author coda
*/
public abstract class AbstractKey {
protected final PGPSecretKey secretKey;
protected final PGPPublicKey publicKey;
protected final KeySignature signature;
protected final Set<KeyFlag> flags;
/**
* Instatiates a new {@link AbstractKey}.
*
* @param key the PGP secret key, with public key included
* @param signingKey the signing key
* @param requiredSignatureType the type of signature required
*/
protected AbstractKey(PGPSecretKey key, PGPSecretKey signingKey,
SignatureType requiredSignatureType) {
this.secretKey = key;
this.publicKey = secretKey.getPublicKey();
this.signature = getSignature(signingKey, requiredSignatureType);
if (signature == null) {
this.flags = ImmutableSet.of();
} else {
this.flags = signature.getKeyFlags();
}
}
/**
* Given the key's passphrase, unlocks the secret key and returns an
* {@link UnlockedKey} equivalent of {@code this}.
*
* @param passphrase the key's passphrase
* @return a {@link UnlockedKey} equivalent of {@code this}
* @throws CryptographicException if {@code passphrase} is incorrect
*/
public abstract UnlockedKey unlock(char[] passphrase) throws CryptographicException;
/**
* Returns this key's public key component.
*/
/* default */ PGPPublicKey getPublicKey() {
return publicKey;
}
/**
* Returns this key's secret key component.
* @return
*/
/* default */ PGPSecretKey getSecretKey() {
return secretKey;
}
/**
* Returns this key's user ID, usually in the form of
* {@code First Last <email@example.com>}.
*/
public String getUserID() {
return getUserIDs().get(0);
}
/**
* Returns a list of all user IDs attached to this key.
*
* @see #getUserID()
*/
public List<String> getUserIDs() { | // Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalents.java
// public final class IntegerEquivalents {
// private IntegerEquivalents() {}
//
// /**
// * Returns the collection of {@code integerEquivs} as an array of {@code int}s.
// */
// public static int[] toIntArray(Collection<? extends IntegerEquivalent> integerEquivs) {
// final int[] values = new int[integerEquivs.size()];
// int i = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// values[i] = integerEquiv.toInteger();
// i++;
// }
// return values;
// }
//
// /**
// * Returns the set of {@code integerEquivs} as a bitmask {@code int}.
// */
// public static int toBitmask(Set<? extends IntegerEquivalent> integerEquivs) {
// int value = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// value |= integerEquiv.toInteger();
// }
// return value;
// }
//
// /**
// * Returns the instance of {@code enumType} which is equivalent to
// * {@code value}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> T fromInt(Class<T> enumType, int value) throws IllegalArgumentException {
// for (T constant : enumType.getEnumConstants()) {
// if (constant.toInteger() == value) {
// return constant;
// }
// }
// throw new IllegalArgumentException("No enum constant of " + enumType + " exists with value " + value);
// }
//
// /**
// * Returns the list of the instances of {@code enumType} which are equivalent
// * to {@code values}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> List<T> fromIntArray(Class<T> enumType, int[] values) throws IllegalArgumentException {
// final ImmutableList.Builder<T> builder = ImmutableList.builder();
// for (int value : values) {
// builder.add(fromInt(enumType, value));
// }
// return builder.build();
// }
//
// /**
// * Returns the {@code bitMask} as a set of {@link IntegerEquivalent}s.
// */
// public static <T extends IntegerEquivalent> Set<T> fromBitmask(Class<T> enumType, int bitMask) throws IllegalArgumentException {
// final ImmutableSet.Builder<T> builder = ImmutableSet.builder();
// for (T constant : enumType.getEnumConstants()) {
// if ((bitMask & constant.toInteger()) != 0) {
// builder.add(constant);
// }
// }
// return builder.build();
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/util/Iterators.java
// public final class Iterators {
// private Iterators() {}
//
// /**
// * Returns the items available via {@code iterator} as a {@link List}.
// */
// @SuppressWarnings("unchecked")
// public static <T> List<T> toList(Iterator<?> iterator) {
// return ImmutableList.copyOf((Iterator<T>) iterator);
// }
//
// /**
// * Returns the items available via {@code iterator} as a {@link Set}.
// */
// @SuppressWarnings("unchecked")
// public static <T> Set<T> toSet(Iterator<?> iterator) {
// return ImmutableSet.copyOf((Iterator<T>) iterator);
// }
// }
// Path: src/main/java/com/wesabe/grendel/openpgp/AbstractKey.java
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSignature;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.google.common.collect.ImmutableSet;
import com.wesabe.grendel.util.IntegerEquivalents;
import com.wesabe.grendel.util.Iterators;
package com.wesabe.grendel.openpgp;
/**
* An abstract base class for asymmetric PGP public keys and their corresponding
* secret keys.
*
* @author coda
*/
public abstract class AbstractKey {
protected final PGPSecretKey secretKey;
protected final PGPPublicKey publicKey;
protected final KeySignature signature;
protected final Set<KeyFlag> flags;
/**
* Instatiates a new {@link AbstractKey}.
*
* @param key the PGP secret key, with public key included
* @param signingKey the signing key
* @param requiredSignatureType the type of signature required
*/
protected AbstractKey(PGPSecretKey key, PGPSecretKey signingKey,
SignatureType requiredSignatureType) {
this.secretKey = key;
this.publicKey = secretKey.getPublicKey();
this.signature = getSignature(signingKey, requiredSignatureType);
if (signature == null) {
this.flags = ImmutableSet.of();
} else {
this.flags = signature.getKeyFlags();
}
}
/**
* Given the key's passphrase, unlocks the secret key and returns an
* {@link UnlockedKey} equivalent of {@code this}.
*
* @param passphrase the key's passphrase
* @return a {@link UnlockedKey} equivalent of {@code this}
* @throws CryptographicException if {@code passphrase} is incorrect
*/
public abstract UnlockedKey unlock(char[] passphrase) throws CryptographicException;
/**
* Returns this key's public key component.
*/
/* default */ PGPPublicKey getPublicKey() {
return publicKey;
}
/**
* Returns this key's secret key component.
* @return
*/
/* default */ PGPSecretKey getSecretKey() {
return secretKey;
}
/**
* Returns this key's user ID, usually in the form of
* {@code First Last <email@example.com>}.
*/
public String getUserID() {
return getUserIDs().get(0);
}
/**
* Returns a list of all user IDs attached to this key.
*
* @see #getUserID()
*/
public List<String> getUserIDs() { | return Iterators.toList(secretKey.getUserIDs()); |
wesabe/grendel | src/main/java/com/wesabe/grendel/openpgp/AbstractKey.java | // Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalents.java
// public final class IntegerEquivalents {
// private IntegerEquivalents() {}
//
// /**
// * Returns the collection of {@code integerEquivs} as an array of {@code int}s.
// */
// public static int[] toIntArray(Collection<? extends IntegerEquivalent> integerEquivs) {
// final int[] values = new int[integerEquivs.size()];
// int i = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// values[i] = integerEquiv.toInteger();
// i++;
// }
// return values;
// }
//
// /**
// * Returns the set of {@code integerEquivs} as a bitmask {@code int}.
// */
// public static int toBitmask(Set<? extends IntegerEquivalent> integerEquivs) {
// int value = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// value |= integerEquiv.toInteger();
// }
// return value;
// }
//
// /**
// * Returns the instance of {@code enumType} which is equivalent to
// * {@code value}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> T fromInt(Class<T> enumType, int value) throws IllegalArgumentException {
// for (T constant : enumType.getEnumConstants()) {
// if (constant.toInteger() == value) {
// return constant;
// }
// }
// throw new IllegalArgumentException("No enum constant of " + enumType + " exists with value " + value);
// }
//
// /**
// * Returns the list of the instances of {@code enumType} which are equivalent
// * to {@code values}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> List<T> fromIntArray(Class<T> enumType, int[] values) throws IllegalArgumentException {
// final ImmutableList.Builder<T> builder = ImmutableList.builder();
// for (int value : values) {
// builder.add(fromInt(enumType, value));
// }
// return builder.build();
// }
//
// /**
// * Returns the {@code bitMask} as a set of {@link IntegerEquivalent}s.
// */
// public static <T extends IntegerEquivalent> Set<T> fromBitmask(Class<T> enumType, int bitMask) throws IllegalArgumentException {
// final ImmutableSet.Builder<T> builder = ImmutableSet.builder();
// for (T constant : enumType.getEnumConstants()) {
// if ((bitMask & constant.toInteger()) != 0) {
// builder.add(constant);
// }
// }
// return builder.build();
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/util/Iterators.java
// public final class Iterators {
// private Iterators() {}
//
// /**
// * Returns the items available via {@code iterator} as a {@link List}.
// */
// @SuppressWarnings("unchecked")
// public static <T> List<T> toList(Iterator<?> iterator) {
// return ImmutableList.copyOf((Iterator<T>) iterator);
// }
//
// /**
// * Returns the items available via {@code iterator} as a {@link Set}.
// */
// @SuppressWarnings("unchecked")
// public static <T> Set<T> toSet(Iterator<?> iterator) {
// return ImmutableSet.copyOf((Iterator<T>) iterator);
// }
// }
| import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSignature;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.google.common.collect.ImmutableSet;
import com.wesabe.grendel.util.IntegerEquivalents;
import com.wesabe.grendel.util.Iterators; |
/**
* Returns a list of all user IDs attached to this key.
*
* @see #getUserID()
*/
public List<String> getUserIDs() {
return Iterators.toList(secretKey.getUserIDs());
}
/**
* Returns the key's ID.
*/
public long getKeyID() {
return secretKey.getKeyID();
}
/**
* Returns a human-readable version of {@link #getKeyID()}.
*
* <b>N.B.:</b> This returns a truncated version of the key ID.
*/
public String getHumanKeyID() {
return String.format("%08X", (int) secretKey.getKeyID());
}
/**
* Returns the key's {@link AsymmetricAlgorithm}.
*/
public AsymmetricAlgorithm getAlgorithm() { | // Path: src/main/java/com/wesabe/grendel/util/IntegerEquivalents.java
// public final class IntegerEquivalents {
// private IntegerEquivalents() {}
//
// /**
// * Returns the collection of {@code integerEquivs} as an array of {@code int}s.
// */
// public static int[] toIntArray(Collection<? extends IntegerEquivalent> integerEquivs) {
// final int[] values = new int[integerEquivs.size()];
// int i = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// values[i] = integerEquiv.toInteger();
// i++;
// }
// return values;
// }
//
// /**
// * Returns the set of {@code integerEquivs} as a bitmask {@code int}.
// */
// public static int toBitmask(Set<? extends IntegerEquivalent> integerEquivs) {
// int value = 0;
// for (IntegerEquivalent integerEquiv : integerEquivs) {
// value |= integerEquiv.toInteger();
// }
// return value;
// }
//
// /**
// * Returns the instance of {@code enumType} which is equivalent to
// * {@code value}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> T fromInt(Class<T> enumType, int value) throws IllegalArgumentException {
// for (T constant : enumType.getEnumConstants()) {
// if (constant.toInteger() == value) {
// return constant;
// }
// }
// throw new IllegalArgumentException("No enum constant of " + enumType + " exists with value " + value);
// }
//
// /**
// * Returns the list of the instances of {@code enumType} which are equivalent
// * to {@code values}.
// *
// * @throws IllegalArgumentException if {@code value} has no equivalent
// */
// public static <T extends IntegerEquivalent> List<T> fromIntArray(Class<T> enumType, int[] values) throws IllegalArgumentException {
// final ImmutableList.Builder<T> builder = ImmutableList.builder();
// for (int value : values) {
// builder.add(fromInt(enumType, value));
// }
// return builder.build();
// }
//
// /**
// * Returns the {@code bitMask} as a set of {@link IntegerEquivalent}s.
// */
// public static <T extends IntegerEquivalent> Set<T> fromBitmask(Class<T> enumType, int bitMask) throws IllegalArgumentException {
// final ImmutableSet.Builder<T> builder = ImmutableSet.builder();
// for (T constant : enumType.getEnumConstants()) {
// if ((bitMask & constant.toInteger()) != 0) {
// builder.add(constant);
// }
// }
// return builder.build();
// }
// }
//
// Path: src/main/java/com/wesabe/grendel/util/Iterators.java
// public final class Iterators {
// private Iterators() {}
//
// /**
// * Returns the items available via {@code iterator} as a {@link List}.
// */
// @SuppressWarnings("unchecked")
// public static <T> List<T> toList(Iterator<?> iterator) {
// return ImmutableList.copyOf((Iterator<T>) iterator);
// }
//
// /**
// * Returns the items available via {@code iterator} as a {@link Set}.
// */
// @SuppressWarnings("unchecked")
// public static <T> Set<T> toSet(Iterator<?> iterator) {
// return ImmutableSet.copyOf((Iterator<T>) iterator);
// }
// }
// Path: src/main/java/com/wesabe/grendel/openpgp/AbstractKey.java
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSignature;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.google.common.collect.ImmutableSet;
import com.wesabe.grendel.util.IntegerEquivalents;
import com.wesabe.grendel.util.Iterators;
/**
* Returns a list of all user IDs attached to this key.
*
* @see #getUserID()
*/
public List<String> getUserIDs() {
return Iterators.toList(secretKey.getUserIDs());
}
/**
* Returns the key's ID.
*/
public long getKeyID() {
return secretKey.getKeyID();
}
/**
* Returns a human-readable version of {@link #getKeyID()}.
*
* <b>N.B.:</b> This returns a truncated version of the key ID.
*/
public String getHumanKeyID() {
return String.format("%08X", (int) secretKey.getKeyID());
}
/**
* Returns the key's {@link AsymmetricAlgorithm}.
*/
public AsymmetricAlgorithm getAlgorithm() { | return IntegerEquivalents.fromInt( |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/items/ItemPixelGlasses.java | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: com/bafomdad/uniquecrops/init/UCKeys.java
// @SideOnly(Side.CLIENT)
// public class UCKeys {
//
// public static KeyBinding pixelKey;
//
// public static void init() {
//
// pixelKey = new KeyBinding("key.uniquecrops.pixelglasses", Keyboard.KEY_V, "key.categories.uniquecrops");
// ClientRegistry.registerKeyBinding(pixelKey);
// }
// }
| import java.util.List;
import org.lwjgl.input.Keyboard;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.common.registry.GameRegistry;
import com.bafomdad.uniquecrops.UniqueCrops;
import com.bafomdad.uniquecrops.init.UCKeys; | package com.bafomdad.uniquecrops.items;
public class ItemPixelGlasses extends ItemArmor {
public ItemPixelGlasses(ArmorMaterial material, int renderindex, EntityEquipmentSlot slot) {
super(material, renderindex, slot);
setRegistryName("pixelglasses"); | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: com/bafomdad/uniquecrops/init/UCKeys.java
// @SideOnly(Side.CLIENT)
// public class UCKeys {
//
// public static KeyBinding pixelKey;
//
// public static void init() {
//
// pixelKey = new KeyBinding("key.uniquecrops.pixelglasses", Keyboard.KEY_V, "key.categories.uniquecrops");
// ClientRegistry.registerKeyBinding(pixelKey);
// }
// }
// Path: com/bafomdad/uniquecrops/items/ItemPixelGlasses.java
import java.util.List;
import org.lwjgl.input.Keyboard;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.common.registry.GameRegistry;
import com.bafomdad.uniquecrops.UniqueCrops;
import com.bafomdad.uniquecrops.init.UCKeys;
package com.bafomdad.uniquecrops.items;
public class ItemPixelGlasses extends ItemArmor {
public ItemPixelGlasses(ArmorMaterial material, int renderindex, EntityEquipmentSlot slot) {
super(material, renderindex, slot);
setRegistryName("pixelglasses"); | setUnlocalizedName(UniqueCrops.MOD_ID + ".pixelglasses"); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/items/ItemPixelGlasses.java | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: com/bafomdad/uniquecrops/init/UCKeys.java
// @SideOnly(Side.CLIENT)
// public class UCKeys {
//
// public static KeyBinding pixelKey;
//
// public static void init() {
//
// pixelKey = new KeyBinding("key.uniquecrops.pixelglasses", Keyboard.KEY_V, "key.categories.uniquecrops");
// ClientRegistry.registerKeyBinding(pixelKey);
// }
// }
| import java.util.List;
import org.lwjgl.input.Keyboard;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.common.registry.GameRegistry;
import com.bafomdad.uniquecrops.UniqueCrops;
import com.bafomdad.uniquecrops.init.UCKeys; | package com.bafomdad.uniquecrops.items;
public class ItemPixelGlasses extends ItemArmor {
public ItemPixelGlasses(ArmorMaterial material, int renderindex, EntityEquipmentSlot slot) {
super(material, renderindex, slot);
setRegistryName("pixelglasses");
setUnlocalizedName(UniqueCrops.MOD_ID + ".pixelglasses");
setCreativeTab(UniqueCrops.TAB);
setMaxDamage(200);
GameRegistry.register(this);
}
@Override
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean whatisthis) {
| // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: com/bafomdad/uniquecrops/init/UCKeys.java
// @SideOnly(Side.CLIENT)
// public class UCKeys {
//
// public static KeyBinding pixelKey;
//
// public static void init() {
//
// pixelKey = new KeyBinding("key.uniquecrops.pixelglasses", Keyboard.KEY_V, "key.categories.uniquecrops");
// ClientRegistry.registerKeyBinding(pixelKey);
// }
// }
// Path: com/bafomdad/uniquecrops/items/ItemPixelGlasses.java
import java.util.List;
import org.lwjgl.input.Keyboard;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.common.registry.GameRegistry;
import com.bafomdad.uniquecrops.UniqueCrops;
import com.bafomdad.uniquecrops.init.UCKeys;
package com.bafomdad.uniquecrops.items;
public class ItemPixelGlasses extends ItemArmor {
public ItemPixelGlasses(ArmorMaterial material, int renderindex, EntityEquipmentSlot slot) {
super(material, renderindex, slot);
setRegistryName("pixelglasses");
setUnlocalizedName(UniqueCrops.MOD_ID + ".pixelglasses");
setCreativeTab(UniqueCrops.TAB);
setMaxDamage(200);
GameRegistry.register(this);
}
@Override
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean whatisthis) {
| list.add(TextFormatting.GOLD + "Press Key " + Keyboard.getKeyName(UCKeys.pixelKey.getKeyCode()) + " to toggle."); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/entities/EntityItemWeepingEye.java | // Path: com/bafomdad/uniquecrops/network/PacketUCEffect.java
// public class PacketUCEffect implements IMessage {
//
// EnumParticleTypes type;
// private double x;
// private double y;
// private double z;
// private int loopSize;
//
// public PacketUCEffect() {}
//
// public PacketUCEffect(EnumParticleTypes type, double x, double y, double z, int loopSize) {
//
// this.type = type;
// this.x = x;
// this.y = y;
// this.z = z;
// this.loopSize = loopSize;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
//
// type = EnumParticleTypes.values()[buf.readShort()];
// x = buf.readDouble();
// y = buf.readDouble();
// z = buf.readDouble();
// loopSize = buf.readInt();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
//
// buf.writeShort(type.ordinal());
// buf.writeDouble(x);
// buf.writeDouble(y);
// buf.writeDouble(z);
// buf.writeInt(loopSize);
// }
//
// public static class Handler implements IMessageHandler<PacketUCEffect, IMessage> {
//
// @Override
// public IMessage onMessage(PacketUCEffect message, MessageContext ctx) {
//
// World world = Minecraft.getMinecraft().theWorld;
// double x = message.x + 0.5D;
// double y = message.y;
// double z = message.z + 0.5D;
//
// if (message.loopSize > 0) {
// for (int i = 0; i < message.loopSize; i++)
// world.spawnParticle(message.type, x + world.rand.nextFloat(), y, z + world.rand.nextFloat(), 0, 0, 0);
// }
// else
// world.spawnParticle(message.type, x, y, z, 0, 0, 0);
//
// return null;
// }
// }
// }
//
// Path: com/bafomdad/uniquecrops/network/UCPacketHandler.java
// public class UCPacketHandler {
//
// public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel("UniqueCrops".toLowerCase());
//
// public static void initClient() {
//
// INSTANCE.registerMessage(PacketUCEffect.Handler.class, PacketUCEffect.class, 0, Side.CLIENT);
// }
//
// public static void initServer() {
//
// INSTANCE.registerMessage(PacketSendKey.Handler.class, PacketSendKey.class, 1, Side.SERVER);
// }
//
// public static void sendToNearbyPlayers(World world, BlockPos pos, IMessage toSend) {
//
// if (world instanceof WorldServer) {
// WorldServer ws = ((WorldServer)world);
//
// for (EntityPlayer player : ws.playerEntities) {
// EntityPlayerMP ep = ((EntityPlayerMP)player);
//
// if (ep.getDistanceSq(pos) < 64 * 64 && ws.getPlayerChunkMap().isPlayerWatchingChunk(ep, pos.getX() >> 4, pos.getZ() >> 4))
// INSTANCE.sendTo(toSend, ep);
// }
// }
// }
// }
| import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.monster.EntitySlime;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.init.MobEffects;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World;
import com.bafomdad.uniquecrops.network.PacketUCEffect;
import com.bafomdad.uniquecrops.network.UCPacketHandler; | package com.bafomdad.uniquecrops.entities;
public class EntityItemWeepingEye extends EntityThrowable {
public EntityItemWeepingEye(World world) {
super(world);
}
public EntityItemWeepingEye(World worldIn, double x, double y, double z) {
super(worldIn, x, y, z);
}
@Override
protected void onImpact(RayTraceResult result) {
if (!worldObj.isRemote) {
BlockPos pos;
if (result.typeOfHit == RayTraceResult.Type.BLOCK)
pos = new BlockPos(result.hitVec).offset(result.sideHit);
else
pos = new BlockPos(result.hitVec);
List<Entity> entities = worldObj.getEntitiesWithinAABBExcludingEntity(this, new AxisAlignedBB(pos.add(-10, -5, -10), pos.add(10, 5, 10)));
for (Entity ent : entities) {
if (!ent.isDead && (ent instanceof EntityMob || ent instanceof EntitySlime))
{
((EntityLiving)ent).addPotionEffect(new PotionEffect(MobEffects.GLOWING, 300));
}
} | // Path: com/bafomdad/uniquecrops/network/PacketUCEffect.java
// public class PacketUCEffect implements IMessage {
//
// EnumParticleTypes type;
// private double x;
// private double y;
// private double z;
// private int loopSize;
//
// public PacketUCEffect() {}
//
// public PacketUCEffect(EnumParticleTypes type, double x, double y, double z, int loopSize) {
//
// this.type = type;
// this.x = x;
// this.y = y;
// this.z = z;
// this.loopSize = loopSize;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
//
// type = EnumParticleTypes.values()[buf.readShort()];
// x = buf.readDouble();
// y = buf.readDouble();
// z = buf.readDouble();
// loopSize = buf.readInt();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
//
// buf.writeShort(type.ordinal());
// buf.writeDouble(x);
// buf.writeDouble(y);
// buf.writeDouble(z);
// buf.writeInt(loopSize);
// }
//
// public static class Handler implements IMessageHandler<PacketUCEffect, IMessage> {
//
// @Override
// public IMessage onMessage(PacketUCEffect message, MessageContext ctx) {
//
// World world = Minecraft.getMinecraft().theWorld;
// double x = message.x + 0.5D;
// double y = message.y;
// double z = message.z + 0.5D;
//
// if (message.loopSize > 0) {
// for (int i = 0; i < message.loopSize; i++)
// world.spawnParticle(message.type, x + world.rand.nextFloat(), y, z + world.rand.nextFloat(), 0, 0, 0);
// }
// else
// world.spawnParticle(message.type, x, y, z, 0, 0, 0);
//
// return null;
// }
// }
// }
//
// Path: com/bafomdad/uniquecrops/network/UCPacketHandler.java
// public class UCPacketHandler {
//
// public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel("UniqueCrops".toLowerCase());
//
// public static void initClient() {
//
// INSTANCE.registerMessage(PacketUCEffect.Handler.class, PacketUCEffect.class, 0, Side.CLIENT);
// }
//
// public static void initServer() {
//
// INSTANCE.registerMessage(PacketSendKey.Handler.class, PacketSendKey.class, 1, Side.SERVER);
// }
//
// public static void sendToNearbyPlayers(World world, BlockPos pos, IMessage toSend) {
//
// if (world instanceof WorldServer) {
// WorldServer ws = ((WorldServer)world);
//
// for (EntityPlayer player : ws.playerEntities) {
// EntityPlayerMP ep = ((EntityPlayerMP)player);
//
// if (ep.getDistanceSq(pos) < 64 * 64 && ws.getPlayerChunkMap().isPlayerWatchingChunk(ep, pos.getX() >> 4, pos.getZ() >> 4))
// INSTANCE.sendTo(toSend, ep);
// }
// }
// }
// }
// Path: com/bafomdad/uniquecrops/entities/EntityItemWeepingEye.java
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.monster.EntitySlime;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.init.MobEffects;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World;
import com.bafomdad.uniquecrops.network.PacketUCEffect;
import com.bafomdad.uniquecrops.network.UCPacketHandler;
package com.bafomdad.uniquecrops.entities;
public class EntityItemWeepingEye extends EntityThrowable {
public EntityItemWeepingEye(World world) {
super(world);
}
public EntityItemWeepingEye(World worldIn, double x, double y, double z) {
super(worldIn, x, y, z);
}
@Override
protected void onImpact(RayTraceResult result) {
if (!worldObj.isRemote) {
BlockPos pos;
if (result.typeOfHit == RayTraceResult.Type.BLOCK)
pos = new BlockPos(result.hitVec).offset(result.sideHit);
else
pos = new BlockPos(result.hitVec);
List<Entity> entities = worldObj.getEntitiesWithinAABBExcludingEntity(this, new AxisAlignedBB(pos.add(-10, -5, -10), pos.add(10, 5, 10)));
for (Entity ent : entities) {
if (!ent.isDead && (ent instanceof EntityMob || ent instanceof EntitySlime))
{
((EntityLiving)ent).addPotionEffect(new PotionEffect(MobEffects.GLOWING, 300));
}
} | UCPacketHandler.sendToNearbyPlayers(worldObj, pos, new PacketUCEffect(EnumParticleTypes.CLOUD, pos.getX(), pos.getY(), pos.getZ(), 5)); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/entities/EntityItemWeepingEye.java | // Path: com/bafomdad/uniquecrops/network/PacketUCEffect.java
// public class PacketUCEffect implements IMessage {
//
// EnumParticleTypes type;
// private double x;
// private double y;
// private double z;
// private int loopSize;
//
// public PacketUCEffect() {}
//
// public PacketUCEffect(EnumParticleTypes type, double x, double y, double z, int loopSize) {
//
// this.type = type;
// this.x = x;
// this.y = y;
// this.z = z;
// this.loopSize = loopSize;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
//
// type = EnumParticleTypes.values()[buf.readShort()];
// x = buf.readDouble();
// y = buf.readDouble();
// z = buf.readDouble();
// loopSize = buf.readInt();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
//
// buf.writeShort(type.ordinal());
// buf.writeDouble(x);
// buf.writeDouble(y);
// buf.writeDouble(z);
// buf.writeInt(loopSize);
// }
//
// public static class Handler implements IMessageHandler<PacketUCEffect, IMessage> {
//
// @Override
// public IMessage onMessage(PacketUCEffect message, MessageContext ctx) {
//
// World world = Minecraft.getMinecraft().theWorld;
// double x = message.x + 0.5D;
// double y = message.y;
// double z = message.z + 0.5D;
//
// if (message.loopSize > 0) {
// for (int i = 0; i < message.loopSize; i++)
// world.spawnParticle(message.type, x + world.rand.nextFloat(), y, z + world.rand.nextFloat(), 0, 0, 0);
// }
// else
// world.spawnParticle(message.type, x, y, z, 0, 0, 0);
//
// return null;
// }
// }
// }
//
// Path: com/bafomdad/uniquecrops/network/UCPacketHandler.java
// public class UCPacketHandler {
//
// public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel("UniqueCrops".toLowerCase());
//
// public static void initClient() {
//
// INSTANCE.registerMessage(PacketUCEffect.Handler.class, PacketUCEffect.class, 0, Side.CLIENT);
// }
//
// public static void initServer() {
//
// INSTANCE.registerMessage(PacketSendKey.Handler.class, PacketSendKey.class, 1, Side.SERVER);
// }
//
// public static void sendToNearbyPlayers(World world, BlockPos pos, IMessage toSend) {
//
// if (world instanceof WorldServer) {
// WorldServer ws = ((WorldServer)world);
//
// for (EntityPlayer player : ws.playerEntities) {
// EntityPlayerMP ep = ((EntityPlayerMP)player);
//
// if (ep.getDistanceSq(pos) < 64 * 64 && ws.getPlayerChunkMap().isPlayerWatchingChunk(ep, pos.getX() >> 4, pos.getZ() >> 4))
// INSTANCE.sendTo(toSend, ep);
// }
// }
// }
// }
| import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.monster.EntitySlime;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.init.MobEffects;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World;
import com.bafomdad.uniquecrops.network.PacketUCEffect;
import com.bafomdad.uniquecrops.network.UCPacketHandler; | package com.bafomdad.uniquecrops.entities;
public class EntityItemWeepingEye extends EntityThrowable {
public EntityItemWeepingEye(World world) {
super(world);
}
public EntityItemWeepingEye(World worldIn, double x, double y, double z) {
super(worldIn, x, y, z);
}
@Override
protected void onImpact(RayTraceResult result) {
if (!worldObj.isRemote) {
BlockPos pos;
if (result.typeOfHit == RayTraceResult.Type.BLOCK)
pos = new BlockPos(result.hitVec).offset(result.sideHit);
else
pos = new BlockPos(result.hitVec);
List<Entity> entities = worldObj.getEntitiesWithinAABBExcludingEntity(this, new AxisAlignedBB(pos.add(-10, -5, -10), pos.add(10, 5, 10)));
for (Entity ent : entities) {
if (!ent.isDead && (ent instanceof EntityMob || ent instanceof EntitySlime))
{
((EntityLiving)ent).addPotionEffect(new PotionEffect(MobEffects.GLOWING, 300));
}
} | // Path: com/bafomdad/uniquecrops/network/PacketUCEffect.java
// public class PacketUCEffect implements IMessage {
//
// EnumParticleTypes type;
// private double x;
// private double y;
// private double z;
// private int loopSize;
//
// public PacketUCEffect() {}
//
// public PacketUCEffect(EnumParticleTypes type, double x, double y, double z, int loopSize) {
//
// this.type = type;
// this.x = x;
// this.y = y;
// this.z = z;
// this.loopSize = loopSize;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
//
// type = EnumParticleTypes.values()[buf.readShort()];
// x = buf.readDouble();
// y = buf.readDouble();
// z = buf.readDouble();
// loopSize = buf.readInt();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
//
// buf.writeShort(type.ordinal());
// buf.writeDouble(x);
// buf.writeDouble(y);
// buf.writeDouble(z);
// buf.writeInt(loopSize);
// }
//
// public static class Handler implements IMessageHandler<PacketUCEffect, IMessage> {
//
// @Override
// public IMessage onMessage(PacketUCEffect message, MessageContext ctx) {
//
// World world = Minecraft.getMinecraft().theWorld;
// double x = message.x + 0.5D;
// double y = message.y;
// double z = message.z + 0.5D;
//
// if (message.loopSize > 0) {
// for (int i = 0; i < message.loopSize; i++)
// world.spawnParticle(message.type, x + world.rand.nextFloat(), y, z + world.rand.nextFloat(), 0, 0, 0);
// }
// else
// world.spawnParticle(message.type, x, y, z, 0, 0, 0);
//
// return null;
// }
// }
// }
//
// Path: com/bafomdad/uniquecrops/network/UCPacketHandler.java
// public class UCPacketHandler {
//
// public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel("UniqueCrops".toLowerCase());
//
// public static void initClient() {
//
// INSTANCE.registerMessage(PacketUCEffect.Handler.class, PacketUCEffect.class, 0, Side.CLIENT);
// }
//
// public static void initServer() {
//
// INSTANCE.registerMessage(PacketSendKey.Handler.class, PacketSendKey.class, 1, Side.SERVER);
// }
//
// public static void sendToNearbyPlayers(World world, BlockPos pos, IMessage toSend) {
//
// if (world instanceof WorldServer) {
// WorldServer ws = ((WorldServer)world);
//
// for (EntityPlayer player : ws.playerEntities) {
// EntityPlayerMP ep = ((EntityPlayerMP)player);
//
// if (ep.getDistanceSq(pos) < 64 * 64 && ws.getPlayerChunkMap().isPlayerWatchingChunk(ep, pos.getX() >> 4, pos.getZ() >> 4))
// INSTANCE.sendTo(toSend, ep);
// }
// }
// }
// }
// Path: com/bafomdad/uniquecrops/entities/EntityItemWeepingEye.java
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.monster.EntitySlime;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.init.MobEffects;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World;
import com.bafomdad.uniquecrops.network.PacketUCEffect;
import com.bafomdad.uniquecrops.network.UCPacketHandler;
package com.bafomdad.uniquecrops.entities;
public class EntityItemWeepingEye extends EntityThrowable {
public EntityItemWeepingEye(World world) {
super(world);
}
public EntityItemWeepingEye(World worldIn, double x, double y, double z) {
super(worldIn, x, y, z);
}
@Override
protected void onImpact(RayTraceResult result) {
if (!worldObj.isRemote) {
BlockPos pos;
if (result.typeOfHit == RayTraceResult.Type.BLOCK)
pos = new BlockPos(result.hitVec).offset(result.sideHit);
else
pos = new BlockPos(result.hitVec);
List<Entity> entities = worldObj.getEntitiesWithinAABBExcludingEntity(this, new AxisAlignedBB(pos.add(-10, -5, -10), pos.add(10, 5, 10)));
for (Entity ent : entities) {
if (!ent.isDead && (ent instanceof EntityMob || ent instanceof EntitySlime))
{
((EntityLiving)ent).addPotionEffect(new PotionEffect(MobEffects.GLOWING, 300));
}
} | UCPacketHandler.sendToNearbyPlayers(worldObj, pos, new PacketUCEffect(EnumParticleTypes.CLOUD, pos.getX(), pos.getY(), pos.getZ(), 5)); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/entities/EntityItemPlum.java | // Path: com/bafomdad/uniquecrops/network/PacketUCEffect.java
// public class PacketUCEffect implements IMessage {
//
// EnumParticleTypes type;
// private double x;
// private double y;
// private double z;
// private int loopSize;
//
// public PacketUCEffect() {}
//
// public PacketUCEffect(EnumParticleTypes type, double x, double y, double z, int loopSize) {
//
// this.type = type;
// this.x = x;
// this.y = y;
// this.z = z;
// this.loopSize = loopSize;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
//
// type = EnumParticleTypes.values()[buf.readShort()];
// x = buf.readDouble();
// y = buf.readDouble();
// z = buf.readDouble();
// loopSize = buf.readInt();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
//
// buf.writeShort(type.ordinal());
// buf.writeDouble(x);
// buf.writeDouble(y);
// buf.writeDouble(z);
// buf.writeInt(loopSize);
// }
//
// public static class Handler implements IMessageHandler<PacketUCEffect, IMessage> {
//
// @Override
// public IMessage onMessage(PacketUCEffect message, MessageContext ctx) {
//
// World world = Minecraft.getMinecraft().theWorld;
// double x = message.x + 0.5D;
// double y = message.y;
// double z = message.z + 0.5D;
//
// if (message.loopSize > 0) {
// for (int i = 0; i < message.loopSize; i++)
// world.spawnParticle(message.type, x + world.rand.nextFloat(), y, z + world.rand.nextFloat(), 0, 0, 0);
// }
// else
// world.spawnParticle(message.type, x, y, z, 0, 0, 0);
//
// return null;
// }
// }
// }
//
// Path: com/bafomdad/uniquecrops/network/UCPacketHandler.java
// public class UCPacketHandler {
//
// public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel("UniqueCrops".toLowerCase());
//
// public static void initClient() {
//
// INSTANCE.registerMessage(PacketUCEffect.Handler.class, PacketUCEffect.class, 0, Side.CLIENT);
// }
//
// public static void initServer() {
//
// INSTANCE.registerMessage(PacketSendKey.Handler.class, PacketSendKey.class, 1, Side.SERVER);
// }
//
// public static void sendToNearbyPlayers(World world, BlockPos pos, IMessage toSend) {
//
// if (world instanceof WorldServer) {
// WorldServer ws = ((WorldServer)world);
//
// for (EntityPlayer player : ws.playerEntities) {
// EntityPlayerMP ep = ((EntityPlayerMP)player);
//
// if (ep.getDistanceSq(pos) < 64 * 64 && ws.getPlayerChunkMap().isPlayerWatchingChunk(ep, pos.getX() >> 4, pos.getZ() >> 4))
// INSTANCE.sendTo(toSend, ep);
// }
// }
// }
// }
| import com.bafomdad.uniquecrops.network.PacketUCEffect;
import com.bafomdad.uniquecrops.network.UCPacketHandler;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.world.World; | package com.bafomdad.uniquecrops.entities;
public class EntityItemPlum extends EntityItem {
public EntityItemPlum(World world) {
super(world);
}
public EntityItemPlum(World world, EntityItem oldEntity, ItemStack stack) {
super(world, oldEntity.posX, oldEntity.posY, oldEntity.posZ, stack);
this.motionX = oldEntity.motionX;
this.motionY = oldEntity.motionY;
this.motionZ = oldEntity.motionZ;
this.lifespan = oldEntity.lifespan;
this.setDefaultPickupDelay();
}
@Override
public void onUpdate() {
super.onUpdate();
double velY = 0;
if (this.ticksExisted > 40)
{
velY = 0.0625D;
if (this.posY >= 256) {
this.setDead();
}
this.addVelocity(0, velY, 0);
if (this.ticksExisted % 10 == 0 && this.isCollided)
{ | // Path: com/bafomdad/uniquecrops/network/PacketUCEffect.java
// public class PacketUCEffect implements IMessage {
//
// EnumParticleTypes type;
// private double x;
// private double y;
// private double z;
// private int loopSize;
//
// public PacketUCEffect() {}
//
// public PacketUCEffect(EnumParticleTypes type, double x, double y, double z, int loopSize) {
//
// this.type = type;
// this.x = x;
// this.y = y;
// this.z = z;
// this.loopSize = loopSize;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
//
// type = EnumParticleTypes.values()[buf.readShort()];
// x = buf.readDouble();
// y = buf.readDouble();
// z = buf.readDouble();
// loopSize = buf.readInt();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
//
// buf.writeShort(type.ordinal());
// buf.writeDouble(x);
// buf.writeDouble(y);
// buf.writeDouble(z);
// buf.writeInt(loopSize);
// }
//
// public static class Handler implements IMessageHandler<PacketUCEffect, IMessage> {
//
// @Override
// public IMessage onMessage(PacketUCEffect message, MessageContext ctx) {
//
// World world = Minecraft.getMinecraft().theWorld;
// double x = message.x + 0.5D;
// double y = message.y;
// double z = message.z + 0.5D;
//
// if (message.loopSize > 0) {
// for (int i = 0; i < message.loopSize; i++)
// world.spawnParticle(message.type, x + world.rand.nextFloat(), y, z + world.rand.nextFloat(), 0, 0, 0);
// }
// else
// world.spawnParticle(message.type, x, y, z, 0, 0, 0);
//
// return null;
// }
// }
// }
//
// Path: com/bafomdad/uniquecrops/network/UCPacketHandler.java
// public class UCPacketHandler {
//
// public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel("UniqueCrops".toLowerCase());
//
// public static void initClient() {
//
// INSTANCE.registerMessage(PacketUCEffect.Handler.class, PacketUCEffect.class, 0, Side.CLIENT);
// }
//
// public static void initServer() {
//
// INSTANCE.registerMessage(PacketSendKey.Handler.class, PacketSendKey.class, 1, Side.SERVER);
// }
//
// public static void sendToNearbyPlayers(World world, BlockPos pos, IMessage toSend) {
//
// if (world instanceof WorldServer) {
// WorldServer ws = ((WorldServer)world);
//
// for (EntityPlayer player : ws.playerEntities) {
// EntityPlayerMP ep = ((EntityPlayerMP)player);
//
// if (ep.getDistanceSq(pos) < 64 * 64 && ws.getPlayerChunkMap().isPlayerWatchingChunk(ep, pos.getX() >> 4, pos.getZ() >> 4))
// INSTANCE.sendTo(toSend, ep);
// }
// }
// }
// }
// Path: com/bafomdad/uniquecrops/entities/EntityItemPlum.java
import com.bafomdad.uniquecrops.network.PacketUCEffect;
import com.bafomdad.uniquecrops.network.UCPacketHandler;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.world.World;
package com.bafomdad.uniquecrops.entities;
public class EntityItemPlum extends EntityItem {
public EntityItemPlum(World world) {
super(world);
}
public EntityItemPlum(World world, EntityItem oldEntity, ItemStack stack) {
super(world, oldEntity.posX, oldEntity.posY, oldEntity.posZ, stack);
this.motionX = oldEntity.motionX;
this.motionY = oldEntity.motionY;
this.motionZ = oldEntity.motionZ;
this.lifespan = oldEntity.lifespan;
this.setDefaultPickupDelay();
}
@Override
public void onUpdate() {
super.onUpdate();
double velY = 0;
if (this.ticksExisted > 40)
{
velY = 0.0625D;
if (this.posY >= 256) {
this.setDead();
}
this.addVelocity(0, velY, 0);
if (this.ticksExisted % 10 == 0 && this.isCollided)
{ | UCPacketHandler.sendToNearbyPlayers(worldObj, getPosition(), new PacketUCEffect(EnumParticleTypes.EXPLOSION_NORMAL, this.posX, this.posY, this.posZ, 3)); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/entities/EntityItemPlum.java | // Path: com/bafomdad/uniquecrops/network/PacketUCEffect.java
// public class PacketUCEffect implements IMessage {
//
// EnumParticleTypes type;
// private double x;
// private double y;
// private double z;
// private int loopSize;
//
// public PacketUCEffect() {}
//
// public PacketUCEffect(EnumParticleTypes type, double x, double y, double z, int loopSize) {
//
// this.type = type;
// this.x = x;
// this.y = y;
// this.z = z;
// this.loopSize = loopSize;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
//
// type = EnumParticleTypes.values()[buf.readShort()];
// x = buf.readDouble();
// y = buf.readDouble();
// z = buf.readDouble();
// loopSize = buf.readInt();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
//
// buf.writeShort(type.ordinal());
// buf.writeDouble(x);
// buf.writeDouble(y);
// buf.writeDouble(z);
// buf.writeInt(loopSize);
// }
//
// public static class Handler implements IMessageHandler<PacketUCEffect, IMessage> {
//
// @Override
// public IMessage onMessage(PacketUCEffect message, MessageContext ctx) {
//
// World world = Minecraft.getMinecraft().theWorld;
// double x = message.x + 0.5D;
// double y = message.y;
// double z = message.z + 0.5D;
//
// if (message.loopSize > 0) {
// for (int i = 0; i < message.loopSize; i++)
// world.spawnParticle(message.type, x + world.rand.nextFloat(), y, z + world.rand.nextFloat(), 0, 0, 0);
// }
// else
// world.spawnParticle(message.type, x, y, z, 0, 0, 0);
//
// return null;
// }
// }
// }
//
// Path: com/bafomdad/uniquecrops/network/UCPacketHandler.java
// public class UCPacketHandler {
//
// public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel("UniqueCrops".toLowerCase());
//
// public static void initClient() {
//
// INSTANCE.registerMessage(PacketUCEffect.Handler.class, PacketUCEffect.class, 0, Side.CLIENT);
// }
//
// public static void initServer() {
//
// INSTANCE.registerMessage(PacketSendKey.Handler.class, PacketSendKey.class, 1, Side.SERVER);
// }
//
// public static void sendToNearbyPlayers(World world, BlockPos pos, IMessage toSend) {
//
// if (world instanceof WorldServer) {
// WorldServer ws = ((WorldServer)world);
//
// for (EntityPlayer player : ws.playerEntities) {
// EntityPlayerMP ep = ((EntityPlayerMP)player);
//
// if (ep.getDistanceSq(pos) < 64 * 64 && ws.getPlayerChunkMap().isPlayerWatchingChunk(ep, pos.getX() >> 4, pos.getZ() >> 4))
// INSTANCE.sendTo(toSend, ep);
// }
// }
// }
// }
| import com.bafomdad.uniquecrops.network.PacketUCEffect;
import com.bafomdad.uniquecrops.network.UCPacketHandler;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.world.World; | package com.bafomdad.uniquecrops.entities;
public class EntityItemPlum extends EntityItem {
public EntityItemPlum(World world) {
super(world);
}
public EntityItemPlum(World world, EntityItem oldEntity, ItemStack stack) {
super(world, oldEntity.posX, oldEntity.posY, oldEntity.posZ, stack);
this.motionX = oldEntity.motionX;
this.motionY = oldEntity.motionY;
this.motionZ = oldEntity.motionZ;
this.lifespan = oldEntity.lifespan;
this.setDefaultPickupDelay();
}
@Override
public void onUpdate() {
super.onUpdate();
double velY = 0;
if (this.ticksExisted > 40)
{
velY = 0.0625D;
if (this.posY >= 256) {
this.setDead();
}
this.addVelocity(0, velY, 0);
if (this.ticksExisted % 10 == 0 && this.isCollided)
{ | // Path: com/bafomdad/uniquecrops/network/PacketUCEffect.java
// public class PacketUCEffect implements IMessage {
//
// EnumParticleTypes type;
// private double x;
// private double y;
// private double z;
// private int loopSize;
//
// public PacketUCEffect() {}
//
// public PacketUCEffect(EnumParticleTypes type, double x, double y, double z, int loopSize) {
//
// this.type = type;
// this.x = x;
// this.y = y;
// this.z = z;
// this.loopSize = loopSize;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
//
// type = EnumParticleTypes.values()[buf.readShort()];
// x = buf.readDouble();
// y = buf.readDouble();
// z = buf.readDouble();
// loopSize = buf.readInt();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
//
// buf.writeShort(type.ordinal());
// buf.writeDouble(x);
// buf.writeDouble(y);
// buf.writeDouble(z);
// buf.writeInt(loopSize);
// }
//
// public static class Handler implements IMessageHandler<PacketUCEffect, IMessage> {
//
// @Override
// public IMessage onMessage(PacketUCEffect message, MessageContext ctx) {
//
// World world = Minecraft.getMinecraft().theWorld;
// double x = message.x + 0.5D;
// double y = message.y;
// double z = message.z + 0.5D;
//
// if (message.loopSize > 0) {
// for (int i = 0; i < message.loopSize; i++)
// world.spawnParticle(message.type, x + world.rand.nextFloat(), y, z + world.rand.nextFloat(), 0, 0, 0);
// }
// else
// world.spawnParticle(message.type, x, y, z, 0, 0, 0);
//
// return null;
// }
// }
// }
//
// Path: com/bafomdad/uniquecrops/network/UCPacketHandler.java
// public class UCPacketHandler {
//
// public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel("UniqueCrops".toLowerCase());
//
// public static void initClient() {
//
// INSTANCE.registerMessage(PacketUCEffect.Handler.class, PacketUCEffect.class, 0, Side.CLIENT);
// }
//
// public static void initServer() {
//
// INSTANCE.registerMessage(PacketSendKey.Handler.class, PacketSendKey.class, 1, Side.SERVER);
// }
//
// public static void sendToNearbyPlayers(World world, BlockPos pos, IMessage toSend) {
//
// if (world instanceof WorldServer) {
// WorldServer ws = ((WorldServer)world);
//
// for (EntityPlayer player : ws.playerEntities) {
// EntityPlayerMP ep = ((EntityPlayerMP)player);
//
// if (ep.getDistanceSq(pos) < 64 * 64 && ws.getPlayerChunkMap().isPlayerWatchingChunk(ep, pos.getX() >> 4, pos.getZ() >> 4))
// INSTANCE.sendTo(toSend, ep);
// }
// }
// }
// }
// Path: com/bafomdad/uniquecrops/entities/EntityItemPlum.java
import com.bafomdad.uniquecrops.network.PacketUCEffect;
import com.bafomdad.uniquecrops.network.UCPacketHandler;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.world.World;
package com.bafomdad.uniquecrops.entities;
public class EntityItemPlum extends EntityItem {
public EntityItemPlum(World world) {
super(world);
}
public EntityItemPlum(World world, EntityItem oldEntity, ItemStack stack) {
super(world, oldEntity.posX, oldEntity.posY, oldEntity.posZ, stack);
this.motionX = oldEntity.motionX;
this.motionY = oldEntity.motionY;
this.motionZ = oldEntity.motionZ;
this.lifespan = oldEntity.lifespan;
this.setDefaultPickupDelay();
}
@Override
public void onUpdate() {
super.onUpdate();
double velY = 0;
if (this.ticksExisted > 40)
{
velY = 0.0625D;
if (this.posY >= 256) {
this.setDead();
}
this.addVelocity(0, velY, 0);
if (this.ticksExisted % 10 == 0 && this.isCollided)
{ | UCPacketHandler.sendToNearbyPlayers(worldObj, getPosition(), new PacketUCEffect(EnumParticleTypes.EXPLOSION_NORMAL, this.posX, this.posY, this.posZ, 3)); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/blocks/BlockBaseUC.java | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
| import com.bafomdad.uniquecrops.UniqueCrops;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.ItemBlock;
import net.minecraftforge.fml.common.registry.GameRegistry; | package com.bafomdad.uniquecrops.blocks;
public class BlockBaseUC extends Block {
public BlockBaseUC(String name, Material mat) {
super(mat);
setRegistryName(name); | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
// Path: com/bafomdad/uniquecrops/blocks/BlockBaseUC.java
import com.bafomdad.uniquecrops.UniqueCrops;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.ItemBlock;
import net.minecraftforge.fml.common.registry.GameRegistry;
package com.bafomdad.uniquecrops.blocks;
public class BlockBaseUC extends Block {
public BlockBaseUC(String name, Material mat) {
super(mat);
setRegistryName(name); | setUnlocalizedName(UniqueCrops.MOD_ID + "." + name); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/items/baubles/EmblemScarab.java | // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
| import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.item.ItemStack;
import baubles.api.BaubleType;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap; | package com.bafomdad.uniquecrops.items.baubles;
public class EmblemScarab extends ItemBauble {
public EmblemScarab() {
| // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
// Path: com/bafomdad/uniquecrops/items/baubles/EmblemScarab.java
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.item.ItemStack;
import baubles.api.BaubleType;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap;
package com.bafomdad.uniquecrops.items.baubles;
public class EmblemScarab extends ItemBauble {
public EmblemScarab() {
| super(EnumEmblems.SCARAB); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/entities/FakePlayerUC.java | // Path: com/bafomdad/uniquecrops/network/FakeNetHandlerPlayServer.java
// public class FakeNetHandlerPlayServer extends NetHandlerPlayServer {
//
// public FakeNetHandlerPlayServer(EntityPlayerMP player) {
//
// super(FMLCommonHandler.instance().getMinecraftServerInstance(), new NetworkManager(EnumPacketDirection.CLIENTBOUND), player);
// }
//
// @Override
// public NetworkManager getNetworkManager()
// {
// return null;
// }
//
// @Override
// public void kickPlayerFromServer(String p_147360_1_)
// {
// }
//
// @Override
// public void processInput(CPacketInput p_147358_1_)
// {
// }
//
// @Override
// public void processPlayer(CPacketPlayer p_147347_1_)
// {
// }
//
// @Override
// public void setPlayerLocation(double p_147364_1_, double p_147364_3_, double p_147364_5_, float p_147364_7_, float p_147364_8_)
// {
// }
//
// @Override
// public void processPlayerDigging(CPacketPlayerDigging p_147345_1_)
// {
// }
//
// @Override
// public void processPlayerBlockPlacement(CPacketPlayerTryUseItem packetIn)
// {
// }
//
// @Override
// public void onDisconnect(ITextComponent p_147231_1_)
// {
// }
//
// @Override
// public void sendPacket(Packet<?> p_147359_1_)
// {
// }
//
// @Override
// public void processHeldItemChange(CPacketHeldItemChange p_147355_1_)
// {
// }
//
// @Override
// public void processChatMessage(CPacketChatMessage p_147354_1_)
// {
// }
//
// @Override
// public void handleAnimation(CPacketAnimation packetIn)
// {
//
// }
//
// @Override
// public void processEntityAction(CPacketEntityAction p_147357_1_)
// {
// }
//
// @Override
// public void processUseEntity(CPacketUseEntity p_147340_1_)
// {
// }
//
// @Override
// public void processClientStatus(CPacketClientStatus p_147342_1_)
// {
// }
//
// @Override
// public void processCloseWindow(CPacketCloseWindow p_147356_1_)
// {
// }
//
// @Override
// public void processClickWindow(CPacketClickWindow p_147351_1_)
// {
// }
//
// @Override
// public void processEnchantItem(CPacketEnchantItem p_147338_1_)
// {
// }
//
// @Override
// public void processCreativeInventoryAction(CPacketCreativeInventoryAction p_147344_1_)
// {
// }
//
// @Override
// public void processConfirmTransaction(CPacketConfirmTransaction p_147339_1_)
// {
// }
//
// @Override
// public void processUpdateSign(CPacketUpdateSign p_147343_1_)
// {
// }
//
// @Override
// public void processKeepAlive(CPacketKeepAlive p_147353_1_)
// {
// }
//
// @Override
// public void processPlayerAbilities(CPacketPlayerAbilities p_147348_1_)
// {
// }
//
// @Override
// public void processTabComplete(CPacketTabComplete p_147341_1_)
// {
// }
//
// @Override
// public void processClientSettings(CPacketClientSettings p_147352_1_)
// {
// }
//
// @Override
// public void handleSpectate(CPacketSpectate packetIn)
// {
// }
//
// @Override
// public void handleResourcePackStatus(CPacketResourcePackStatus packetIn)
// {
// }
// }
| import com.bafomdad.uniquecrops.network.FakeNetHandlerPlayServer;
import com.mojang.authlib.GameProfile;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.fml.common.FMLCommonHandler; | package com.bafomdad.uniquecrops.entities;
public class FakePlayerUC extends FakePlayer {
public FakePlayerUC(World world, BlockPos pos, GameProfile profile) {
super(FMLCommonHandler.instance().getMinecraftServerInstance().worldServerForDimension(world.provider.getDimension()), profile);
posX = pos.getX() + 0.5;
posY = pos.getY() + 0.5;
posZ = pos.getZ() + 0.5; | // Path: com/bafomdad/uniquecrops/network/FakeNetHandlerPlayServer.java
// public class FakeNetHandlerPlayServer extends NetHandlerPlayServer {
//
// public FakeNetHandlerPlayServer(EntityPlayerMP player) {
//
// super(FMLCommonHandler.instance().getMinecraftServerInstance(), new NetworkManager(EnumPacketDirection.CLIENTBOUND), player);
// }
//
// @Override
// public NetworkManager getNetworkManager()
// {
// return null;
// }
//
// @Override
// public void kickPlayerFromServer(String p_147360_1_)
// {
// }
//
// @Override
// public void processInput(CPacketInput p_147358_1_)
// {
// }
//
// @Override
// public void processPlayer(CPacketPlayer p_147347_1_)
// {
// }
//
// @Override
// public void setPlayerLocation(double p_147364_1_, double p_147364_3_, double p_147364_5_, float p_147364_7_, float p_147364_8_)
// {
// }
//
// @Override
// public void processPlayerDigging(CPacketPlayerDigging p_147345_1_)
// {
// }
//
// @Override
// public void processPlayerBlockPlacement(CPacketPlayerTryUseItem packetIn)
// {
// }
//
// @Override
// public void onDisconnect(ITextComponent p_147231_1_)
// {
// }
//
// @Override
// public void sendPacket(Packet<?> p_147359_1_)
// {
// }
//
// @Override
// public void processHeldItemChange(CPacketHeldItemChange p_147355_1_)
// {
// }
//
// @Override
// public void processChatMessage(CPacketChatMessage p_147354_1_)
// {
// }
//
// @Override
// public void handleAnimation(CPacketAnimation packetIn)
// {
//
// }
//
// @Override
// public void processEntityAction(CPacketEntityAction p_147357_1_)
// {
// }
//
// @Override
// public void processUseEntity(CPacketUseEntity p_147340_1_)
// {
// }
//
// @Override
// public void processClientStatus(CPacketClientStatus p_147342_1_)
// {
// }
//
// @Override
// public void processCloseWindow(CPacketCloseWindow p_147356_1_)
// {
// }
//
// @Override
// public void processClickWindow(CPacketClickWindow p_147351_1_)
// {
// }
//
// @Override
// public void processEnchantItem(CPacketEnchantItem p_147338_1_)
// {
// }
//
// @Override
// public void processCreativeInventoryAction(CPacketCreativeInventoryAction p_147344_1_)
// {
// }
//
// @Override
// public void processConfirmTransaction(CPacketConfirmTransaction p_147339_1_)
// {
// }
//
// @Override
// public void processUpdateSign(CPacketUpdateSign p_147343_1_)
// {
// }
//
// @Override
// public void processKeepAlive(CPacketKeepAlive p_147353_1_)
// {
// }
//
// @Override
// public void processPlayerAbilities(CPacketPlayerAbilities p_147348_1_)
// {
// }
//
// @Override
// public void processTabComplete(CPacketTabComplete p_147341_1_)
// {
// }
//
// @Override
// public void processClientSettings(CPacketClientSettings p_147352_1_)
// {
// }
//
// @Override
// public void handleSpectate(CPacketSpectate packetIn)
// {
// }
//
// @Override
// public void handleResourcePackStatus(CPacketResourcePackStatus packetIn)
// {
// }
// }
// Path: com/bafomdad/uniquecrops/entities/FakePlayerUC.java
import com.bafomdad.uniquecrops.network.FakeNetHandlerPlayServer;
import com.mojang.authlib.GameProfile;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.fml.common.FMLCommonHandler;
package com.bafomdad.uniquecrops.entities;
public class FakePlayerUC extends FakePlayer {
public FakePlayerUC(World world, BlockPos pos, GameProfile profile) {
super(FMLCommonHandler.instance().getMinecraftServerInstance().worldServerForDimension(world.provider.getDimension()), profile);
posX = pos.getX() + 0.5;
posY = pos.getY() + 0.5;
posZ = pos.getZ() + 0.5; | this.connection = new FakeNetHandlerPlayServer(this); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/init/UCEntities.java | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
| import com.bafomdad.uniquecrops.UniqueCrops;
import com.bafomdad.uniquecrops.entities.*;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; | package com.bafomdad.uniquecrops.init;
public class UCEntities {
public static void init() {
| // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
// Path: com/bafomdad/uniquecrops/init/UCEntities.java
import com.bafomdad.uniquecrops.UniqueCrops;
import com.bafomdad.uniquecrops.entities.*;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
package com.bafomdad.uniquecrops.init;
public class UCEntities {
public static void init() {
| EntityRegistry.registerModEntity(EntityCustomPotion.class, UniqueCrops.MOD_ID + "reversepotion", 0, UniqueCrops.instance, 64, 1, true); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/items/baubles/EmblemLeaf.java | // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
| import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemArmor.ArmorMaterial;
import net.minecraft.item.ItemStack;
import baubles.api.BaubleType;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap; | package com.bafomdad.uniquecrops.items.baubles;
public class EmblemLeaf extends ItemBauble {
private int armorCount;
public EmblemLeaf() {
| // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
// Path: com/bafomdad/uniquecrops/items/baubles/EmblemLeaf.java
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemArmor.ArmorMaterial;
import net.minecraft.item.ItemStack;
import baubles.api.BaubleType;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap;
package com.bafomdad.uniquecrops.items.baubles;
public class EmblemLeaf extends ItemBauble {
private int armorCount;
public EmblemLeaf() {
| super(EnumEmblems.LEAF); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/items/baubles/EmblemFood.java | // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
| import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import baubles.api.BaubleType;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap; | package com.bafomdad.uniquecrops.items.baubles;
public class EmblemFood extends ItemBauble {
public EmblemFood() {
| // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
// Path: com/bafomdad/uniquecrops/items/baubles/EmblemFood.java
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import baubles.api.BaubleType;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap;
package com.bafomdad.uniquecrops.items.baubles;
public class EmblemFood extends ItemBauble {
public EmblemFood() {
| super(EnumEmblems.FOOD); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/items/baubles/EmblemDefense.java | // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
| import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.init.Enchantments;
import net.minecraft.item.ItemShield;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import baubles.api.BaubleType;
import baubles.api.BaublesApi;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap; | package com.bafomdad.uniquecrops.items.baubles;
public class EmblemDefense extends ItemBauble {
public EmblemDefense() {
| // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
// Path: com/bafomdad/uniquecrops/items/baubles/EmblemDefense.java
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.init.Enchantments;
import net.minecraft.item.ItemShield;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import baubles.api.BaubleType;
import baubles.api.BaublesApi;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap;
package com.bafomdad.uniquecrops.items.baubles;
public class EmblemDefense extends ItemBauble {
public EmblemDefense() {
| super(EnumEmblems.DEFENSE); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/items/baubles/EmblemPowerfist.java | // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
| import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.PlayerEvent.BreakSpeed;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import baubles.api.BaubleType;
import baubles.api.BaublesApi;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap; | package com.bafomdad.uniquecrops.items.baubles;
public class EmblemPowerfist extends ItemBauble {
public EmblemPowerfist() {
| // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
// Path: com/bafomdad/uniquecrops/items/baubles/EmblemPowerfist.java
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.PlayerEvent.BreakSpeed;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import baubles.api.BaubleType;
import baubles.api.BaublesApi;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap;
package com.bafomdad.uniquecrops.items.baubles;
public class EmblemPowerfist extends ItemBauble {
public EmblemPowerfist() {
| super(EnumEmblems.POWERFIST); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/items/baubles/EmblemMelee.java | // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
| import java.util.Collection;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.item.ItemStack;
import baubles.api.BaubleType; | package com.bafomdad.uniquecrops.items.baubles;
public class EmblemMelee extends ItemBauble {
public EmblemMelee() {
| // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
// Path: com/bafomdad/uniquecrops/items/baubles/EmblemMelee.java
import java.util.Collection;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.item.ItemStack;
import baubles.api.BaubleType;
package com.bafomdad.uniquecrops.items.baubles;
public class EmblemMelee extends ItemBauble {
public EmblemMelee() {
| super(EnumEmblems.MELEE); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/items/baubles/EmblemPacifism.java | // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
| import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import baubles.api.BaubleType;
import baubles.api.BaublesApi;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap; | package com.bafomdad.uniquecrops.items.baubles;
public class EmblemPacifism extends ItemBauble {
public EmblemPacifism() {
| // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
// Path: com/bafomdad/uniquecrops/items/baubles/EmblemPacifism.java
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import baubles.api.BaubleType;
import baubles.api.BaublesApi;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap;
package com.bafomdad.uniquecrops.items.baubles;
public class EmblemPacifism extends ItemBauble {
public EmblemPacifism() {
| super(EnumEmblems.PACIFISM); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/blocks/BlockOldGravel.java | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
| import com.bafomdad.uniquecrops.UniqueCrops;
import net.minecraft.block.BlockGravel;
import net.minecraft.block.SoundType;
import net.minecraft.item.ItemBlock;
import net.minecraftforge.fml.common.registry.GameRegistry; | package com.bafomdad.uniquecrops.blocks;
public class BlockOldGravel extends BlockGravel {
public BlockOldGravel() {
setRegistryName("oldgravel"); | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
// Path: com/bafomdad/uniquecrops/blocks/BlockOldGravel.java
import com.bafomdad.uniquecrops.UniqueCrops;
import net.minecraft.block.BlockGravel;
import net.minecraft.block.SoundType;
import net.minecraft.item.ItemBlock;
import net.minecraftforge.fml.common.registry.GameRegistry;
package com.bafomdad.uniquecrops.blocks;
public class BlockOldGravel extends BlockGravel {
public BlockOldGravel() {
setRegistryName("oldgravel"); | setUnlocalizedName(UniqueCrops.MOD_ID + ".oldgravel"); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/gui/PageEula.java | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
| import org.lwjgl.opengl.GL11;
import com.bafomdad.uniquecrops.UniqueCrops;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n; | package com.bafomdad.uniquecrops.gui;
public abstract class PageEula {
public static GuiBookEula gui;
protected Minecraft mc = Minecraft.getMinecraft();
protected int drawX, drawY, wordWrap;
public PageEula(GuiBookEula screen) {
this.gui = screen;
this.drawX = (screen.width - screen.WIDTH) / 2 + 25;
this.drawY = (screen.height - screen.HEIGHT) / 2 + 15;
this.wordWrap = this.gui.WIDTH - 40;
}
public void draw() {
GL11.glColor4f(1f, 1f, 1f, 1f);
}
public static void loadPages(GuiBookEula screen) {
GuiBookEula.pageList.clear();
for (int i = 0; i < 8; i++) | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
// Path: com/bafomdad/uniquecrops/gui/PageEula.java
import org.lwjgl.opengl.GL11;
import com.bafomdad.uniquecrops.UniqueCrops;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
package com.bafomdad.uniquecrops.gui;
public abstract class PageEula {
public static GuiBookEula gui;
protected Minecraft mc = Minecraft.getMinecraft();
protected int drawX, drawY, wordWrap;
public PageEula(GuiBookEula screen) {
this.gui = screen;
this.drawX = (screen.width - screen.WIDTH) / 2 + 25;
this.drawY = (screen.height - screen.HEIGHT) / 2 + 15;
this.wordWrap = this.gui.WIDTH - 40;
}
public void draw() {
GL11.glColor4f(1f, 1f, 1f, 1f);
}
public static void loadPages(GuiBookEula screen) {
GuiBookEula.pageList.clear();
for (int i = 0; i < 8; i++) | GuiBookEula.pageList.add(new EulaText(screen, I18n.format(UniqueCrops.MOD_ID + ".eula.text" + i))); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/blocks/BlockOldStone.java | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
| import com.bafomdad.uniquecrops.UniqueCrops;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.item.ItemBlock;
import net.minecraftforge.fml.common.registry.GameRegistry; | package com.bafomdad.uniquecrops.blocks;
public class BlockOldStone extends Block {
public BlockOldStone(String name) {
super(Material.ROCK);
setRegistryName("old" + name); | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
// Path: com/bafomdad/uniquecrops/blocks/BlockOldStone.java
import com.bafomdad.uniquecrops.UniqueCrops;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.item.ItemBlock;
import net.minecraftforge.fml.common.registry.GameRegistry;
package com.bafomdad.uniquecrops.blocks;
public class BlockOldStone extends Block {
public BlockOldStone(String name) {
super(Material.ROCK);
setRegistryName("old" + name); | setUnlocalizedName(UniqueCrops.MOD_ID + ".old" + name); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/items/baubles/EmblemTransformation.java | // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import baubles.api.BaubleType;
import baubles.api.BaublesApi;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap; | package com.bafomdad.uniquecrops.items.baubles;
public class EmblemTransformation extends ItemBauble {
public EmblemTransformation() {
| // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
// Path: com/bafomdad/uniquecrops/items/baubles/EmblemTransformation.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import baubles.api.BaubleType;
import baubles.api.BaublesApi;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap;
package com.bafomdad.uniquecrops.items.baubles;
public class EmblemTransformation extends ItemBauble {
public EmblemTransformation() {
| super(EnumEmblems.TRANSFORMATION); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/blocks/BlockOldGrass.java | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: com/bafomdad/uniquecrops/init/UCBlocks.java
// public class UCBlocks {
//
// // CROPS
// public static BlockCropsBase
// cropNormal,
// cropPrecision,
// cropKnowledge,
// cropDirigible,
// cropMillennium,
// cropEnderlily,
// cropCollis,
// cropWeepingbells,
// cropInvisibilia,
// cropMaryjane,
// cropMusica,
// cropCinderbella,
// cropMerlinia,
// cropFeroxia,
// cropEula,
// cropCobblonia,
// cropDyeius,
// cropAbstract,
// cropWafflonia,
// cropDevilsnare,
// cropPixelsius,
// cropArtisia,
// cropPetramia,
// cropMalleatoris;
//
// public static Block oldCobble, oldCobbleMoss, oldGravel, oldGrass, oldBrick;
// public static Block hourglass, totemhead, lavalily, darkBlock;
//
// public static void init() {
//
// cropNormal = new Normal();
// cropPrecision = new Precision();
// cropKnowledge = new Knowledge();
// cropDirigible = new Dirigible();
// cropMillennium = new Millennium();
// cropEnderlily = new Enderlily();
// cropCollis = new Collis();
// cropInvisibilia = new Invisibilia();
// cropMaryjane = new MaryJane();
// cropWeepingbells = new WeepingBells();
// cropMusica = new Musica();
// cropCinderbella = new Cinderbella();
// cropMerlinia = new Merlinia();
// cropFeroxia = new Feroxia();
// cropEula = new Eula();
// cropCobblonia = new Cobblonia();
// cropDyeius = new Dyeius();
// cropAbstract = new Abstract();
// cropWafflonia = new Wafflonia();
// cropDevilsnare = new DevilSnare();
// cropPixelsius = new Pixelsius();
// cropArtisia = new Artisia();
// cropPetramia = new Petramia();
// cropMalleatoris = new Malleatoris();
//
// oldCobble = new BlockOldStone("cobble");
// oldCobbleMoss = new BlockOldStone("cobblemoss");
// oldBrick = new BlockOldStone("brick");
// oldGravel = new BlockOldGravel();
// oldGrass = new BlockOldGrass();
// hourglass = new BlockHourglass();
// totemhead = new BlockTotemhead();
// lavalily = new BlockLavaLily();
// darkBlock = new BlockDarkBlock();
// }
//
// @SideOnly(Side.CLIENT)
// public static void initModels() {
//
// registerBlockModel(oldCobble);
// registerBlockModel(oldCobbleMoss);
// registerBlockModel(oldBrick);
// registerBlockModel(oldGravel);
// registerBlockModel(oldGrass);
// registerBlockModel(hourglass);
// registerBlockModel(totemhead);
// registerBlockModel(lavalily);
// registerBlockModel(darkBlock);
//
// ClientRegistry.bindTileEntitySpecialRenderer(TileArtisia.class, new RenderCraftItem());
// }
//
// private static void registerBlockModel(Block block) {
//
// ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(block), 0, new ModelResourceLocation(block.getRegistryName(), "inventory"));
// }
// }
| import java.util.Random;
import com.bafomdad.uniquecrops.UniqueCrops;
import com.bafomdad.uniquecrops.init.UCBlocks;
import net.minecraft.block.BlockDirt;
import net.minecraft.block.BlockGrass;
import net.minecraft.block.SoundType;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.GameRegistry; | package com.bafomdad.uniquecrops.blocks;
public class BlockOldGrass extends BlockGrass {
public BlockOldGrass() {
setRegistryName("oldgrass"); | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: com/bafomdad/uniquecrops/init/UCBlocks.java
// public class UCBlocks {
//
// // CROPS
// public static BlockCropsBase
// cropNormal,
// cropPrecision,
// cropKnowledge,
// cropDirigible,
// cropMillennium,
// cropEnderlily,
// cropCollis,
// cropWeepingbells,
// cropInvisibilia,
// cropMaryjane,
// cropMusica,
// cropCinderbella,
// cropMerlinia,
// cropFeroxia,
// cropEula,
// cropCobblonia,
// cropDyeius,
// cropAbstract,
// cropWafflonia,
// cropDevilsnare,
// cropPixelsius,
// cropArtisia,
// cropPetramia,
// cropMalleatoris;
//
// public static Block oldCobble, oldCobbleMoss, oldGravel, oldGrass, oldBrick;
// public static Block hourglass, totemhead, lavalily, darkBlock;
//
// public static void init() {
//
// cropNormal = new Normal();
// cropPrecision = new Precision();
// cropKnowledge = new Knowledge();
// cropDirigible = new Dirigible();
// cropMillennium = new Millennium();
// cropEnderlily = new Enderlily();
// cropCollis = new Collis();
// cropInvisibilia = new Invisibilia();
// cropMaryjane = new MaryJane();
// cropWeepingbells = new WeepingBells();
// cropMusica = new Musica();
// cropCinderbella = new Cinderbella();
// cropMerlinia = new Merlinia();
// cropFeroxia = new Feroxia();
// cropEula = new Eula();
// cropCobblonia = new Cobblonia();
// cropDyeius = new Dyeius();
// cropAbstract = new Abstract();
// cropWafflonia = new Wafflonia();
// cropDevilsnare = new DevilSnare();
// cropPixelsius = new Pixelsius();
// cropArtisia = new Artisia();
// cropPetramia = new Petramia();
// cropMalleatoris = new Malleatoris();
//
// oldCobble = new BlockOldStone("cobble");
// oldCobbleMoss = new BlockOldStone("cobblemoss");
// oldBrick = new BlockOldStone("brick");
// oldGravel = new BlockOldGravel();
// oldGrass = new BlockOldGrass();
// hourglass = new BlockHourglass();
// totemhead = new BlockTotemhead();
// lavalily = new BlockLavaLily();
// darkBlock = new BlockDarkBlock();
// }
//
// @SideOnly(Side.CLIENT)
// public static void initModels() {
//
// registerBlockModel(oldCobble);
// registerBlockModel(oldCobbleMoss);
// registerBlockModel(oldBrick);
// registerBlockModel(oldGravel);
// registerBlockModel(oldGrass);
// registerBlockModel(hourglass);
// registerBlockModel(totemhead);
// registerBlockModel(lavalily);
// registerBlockModel(darkBlock);
//
// ClientRegistry.bindTileEntitySpecialRenderer(TileArtisia.class, new RenderCraftItem());
// }
//
// private static void registerBlockModel(Block block) {
//
// ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(block), 0, new ModelResourceLocation(block.getRegistryName(), "inventory"));
// }
// }
// Path: com/bafomdad/uniquecrops/blocks/BlockOldGrass.java
import java.util.Random;
import com.bafomdad.uniquecrops.UniqueCrops;
import com.bafomdad.uniquecrops.init.UCBlocks;
import net.minecraft.block.BlockDirt;
import net.minecraft.block.BlockGrass;
import net.minecraft.block.SoundType;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.GameRegistry;
package com.bafomdad.uniquecrops.blocks;
public class BlockOldGrass extends BlockGrass {
public BlockOldGrass() {
setRegistryName("oldgrass"); | setUnlocalizedName(UniqueCrops.MOD_ID + ".oldgrass"); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/init/UCBaubles.java | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: com/bafomdad/uniquecrops/core/EnumItems.java
// public enum EnumItems implements IStringSerializable {
//
// GUIDE("guidebook"),
// DISCOUNT("discountbook"),
// PLUM("dirigibleplum"),
// CINDERLEAF("cinderleaf"),
// TIMEDUST("timedust"),
// LILYTWINE("lilytwine"),
// GOLDENRODS("goldenrods"),
// PRENUGGET("prenugget"),
// PREGEM("pregem"),
// ESSENCE("essence"),
// TIMEMEAL("timemeal"),
// INVISITWINE("invisitwine"),
// INVISIFEATHER("invisifeather"),
// POTIONSPLASH("potionreversesplash"),
// SLIPPER("slipperglass"),
// WEEPINGTEAR("weepingtear"),
// WEEPINGEYE("weepingeye"),
// MILLENNIUMEYE("millenniumeye"),
// UPGRADE("upgradebook"),
// EGGUPGRADE("eggupgrade"),
// EASYBADGE("easybadge"),
// DOGRESIDUE("dogresidue"),
// ABSTRACT("abstract"),
// LEGALSTUFF("legalstuff"),
// EULA("eulabook"),
// DUMMYITEM("dummy"),
// PIXELS("pixels");
//
// final String name;
//
// EnumItems(String name) {
//
// this.name = name;
// }
//
// @Override
// public String getName() {
//
// return name;
// }
// }
| import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import com.bafomdad.uniquecrops.UniqueCrops;
import com.bafomdad.uniquecrops.core.EnumItems;
import com.bafomdad.uniquecrops.items.baubles.*; | package com.bafomdad.uniquecrops.init;
public class UCBaubles {
public static ItemBauble
emblemMelee,
emblemScarab,
emblemTransformation,
emblemPowerfist,
emblemRainbow,
emblemFood,
emblemIronstomach,
emblemDefense,
emblemLeaf,
emblemPacifism;
public static void init() {
| // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: com/bafomdad/uniquecrops/core/EnumItems.java
// public enum EnumItems implements IStringSerializable {
//
// GUIDE("guidebook"),
// DISCOUNT("discountbook"),
// PLUM("dirigibleplum"),
// CINDERLEAF("cinderleaf"),
// TIMEDUST("timedust"),
// LILYTWINE("lilytwine"),
// GOLDENRODS("goldenrods"),
// PRENUGGET("prenugget"),
// PREGEM("pregem"),
// ESSENCE("essence"),
// TIMEMEAL("timemeal"),
// INVISITWINE("invisitwine"),
// INVISIFEATHER("invisifeather"),
// POTIONSPLASH("potionreversesplash"),
// SLIPPER("slipperglass"),
// WEEPINGTEAR("weepingtear"),
// WEEPINGEYE("weepingeye"),
// MILLENNIUMEYE("millenniumeye"),
// UPGRADE("upgradebook"),
// EGGUPGRADE("eggupgrade"),
// EASYBADGE("easybadge"),
// DOGRESIDUE("dogresidue"),
// ABSTRACT("abstract"),
// LEGALSTUFF("legalstuff"),
// EULA("eulabook"),
// DUMMYITEM("dummy"),
// PIXELS("pixels");
//
// final String name;
//
// EnumItems(String name) {
//
// this.name = name;
// }
//
// @Override
// public String getName() {
//
// return name;
// }
// }
// Path: com/bafomdad/uniquecrops/init/UCBaubles.java
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import com.bafomdad.uniquecrops.UniqueCrops;
import com.bafomdad.uniquecrops.core.EnumItems;
import com.bafomdad.uniquecrops.items.baubles.*;
package com.bafomdad.uniquecrops.init;
public class UCBaubles {
public static ItemBauble
emblemMelee,
emblemScarab,
emblemTransformation,
emblemPowerfist,
emblemRainbow,
emblemFood,
emblemIronstomach,
emblemDefense,
emblemLeaf,
emblemPacifism;
public static void init() {
| if (!UniqueCrops.baublesLoaded) return; |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/init/UCBaubles.java | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: com/bafomdad/uniquecrops/core/EnumItems.java
// public enum EnumItems implements IStringSerializable {
//
// GUIDE("guidebook"),
// DISCOUNT("discountbook"),
// PLUM("dirigibleplum"),
// CINDERLEAF("cinderleaf"),
// TIMEDUST("timedust"),
// LILYTWINE("lilytwine"),
// GOLDENRODS("goldenrods"),
// PRENUGGET("prenugget"),
// PREGEM("pregem"),
// ESSENCE("essence"),
// TIMEMEAL("timemeal"),
// INVISITWINE("invisitwine"),
// INVISIFEATHER("invisifeather"),
// POTIONSPLASH("potionreversesplash"),
// SLIPPER("slipperglass"),
// WEEPINGTEAR("weepingtear"),
// WEEPINGEYE("weepingeye"),
// MILLENNIUMEYE("millenniumeye"),
// UPGRADE("upgradebook"),
// EGGUPGRADE("eggupgrade"),
// EASYBADGE("easybadge"),
// DOGRESIDUE("dogresidue"),
// ABSTRACT("abstract"),
// LEGALSTUFF("legalstuff"),
// EULA("eulabook"),
// DUMMYITEM("dummy"),
// PIXELS("pixels");
//
// final String name;
//
// EnumItems(String name) {
//
// this.name = name;
// }
//
// @Override
// public String getName() {
//
// return name;
// }
// }
| import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import com.bafomdad.uniquecrops.UniqueCrops;
import com.bafomdad.uniquecrops.core.EnumItems;
import com.bafomdad.uniquecrops.items.baubles.*; | emblemFood = new EmblemFood();
emblemIronstomach = new EmblemIronstomach();
emblemDefense = new EmblemDefense();
emblemLeaf = new EmblemLeaf();
emblemPacifism = new EmblemPacifism();
}
@SideOnly(Side.CLIENT)
public static void initModels() {
if (!UniqueCrops.baublesLoaded) return;
registerItemModel(emblemMelee);
registerItemModel(emblemScarab);
registerItemModel(emblemTransformation);
registerItemModel(emblemPowerfist);
registerItemModel(emblemRainbow);
registerItemModel(emblemFood);
registerItemModel(emblemIronstomach);
registerItemModel(emblemDefense);
registerItemModel(emblemLeaf);
registerItemModel(emblemPacifism);
}
public static void initRecipes() {
if (!UniqueCrops.baublesLoaded) return;
GameRegistry.addRecipe(new ItemStack(emblemMelee), " d ", "gDi", " w " , 'd', Items.DIAMOND_SWORD, 'g', Items.GOLDEN_SWORD, 'i', Items.IRON_SWORD, 'w', Items.WOODEN_SWORD, 'D', UCBlocks.darkBlock);
GameRegistry.addRecipe(new ItemStack(emblemScarab), "gGg", "GDG", "gGg", 'g', Items.GOLD_INGOT, 'G', Blocks.GOLD_BLOCK, 'D', UCBlocks.darkBlock); | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: com/bafomdad/uniquecrops/core/EnumItems.java
// public enum EnumItems implements IStringSerializable {
//
// GUIDE("guidebook"),
// DISCOUNT("discountbook"),
// PLUM("dirigibleplum"),
// CINDERLEAF("cinderleaf"),
// TIMEDUST("timedust"),
// LILYTWINE("lilytwine"),
// GOLDENRODS("goldenrods"),
// PRENUGGET("prenugget"),
// PREGEM("pregem"),
// ESSENCE("essence"),
// TIMEMEAL("timemeal"),
// INVISITWINE("invisitwine"),
// INVISIFEATHER("invisifeather"),
// POTIONSPLASH("potionreversesplash"),
// SLIPPER("slipperglass"),
// WEEPINGTEAR("weepingtear"),
// WEEPINGEYE("weepingeye"),
// MILLENNIUMEYE("millenniumeye"),
// UPGRADE("upgradebook"),
// EGGUPGRADE("eggupgrade"),
// EASYBADGE("easybadge"),
// DOGRESIDUE("dogresidue"),
// ABSTRACT("abstract"),
// LEGALSTUFF("legalstuff"),
// EULA("eulabook"),
// DUMMYITEM("dummy"),
// PIXELS("pixels");
//
// final String name;
//
// EnumItems(String name) {
//
// this.name = name;
// }
//
// @Override
// public String getName() {
//
// return name;
// }
// }
// Path: com/bafomdad/uniquecrops/init/UCBaubles.java
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import com.bafomdad.uniquecrops.UniqueCrops;
import com.bafomdad.uniquecrops.core.EnumItems;
import com.bafomdad.uniquecrops.items.baubles.*;
emblemFood = new EmblemFood();
emblemIronstomach = new EmblemIronstomach();
emblemDefense = new EmblemDefense();
emblemLeaf = new EmblemLeaf();
emblemPacifism = new EmblemPacifism();
}
@SideOnly(Side.CLIENT)
public static void initModels() {
if (!UniqueCrops.baublesLoaded) return;
registerItemModel(emblemMelee);
registerItemModel(emblemScarab);
registerItemModel(emblemTransformation);
registerItemModel(emblemPowerfist);
registerItemModel(emblemRainbow);
registerItemModel(emblemFood);
registerItemModel(emblemIronstomach);
registerItemModel(emblemDefense);
registerItemModel(emblemLeaf);
registerItemModel(emblemPacifism);
}
public static void initRecipes() {
if (!UniqueCrops.baublesLoaded) return;
GameRegistry.addRecipe(new ItemStack(emblemMelee), " d ", "gDi", " w " , 'd', Items.DIAMOND_SWORD, 'g', Items.GOLDEN_SWORD, 'i', Items.IRON_SWORD, 'w', Items.WOODEN_SWORD, 'D', UCBlocks.darkBlock);
GameRegistry.addRecipe(new ItemStack(emblemScarab), "gGg", "GDG", "gGg", 'g', Items.GOLD_INGOT, 'G', Blocks.GOLD_BLOCK, 'D', UCBlocks.darkBlock); | GameRegistry.addRecipe(new ItemStack(emblemTransformation), " P ", "fDf", " f ", 'P', UCItems.generic.createStack(EnumItems.POTIONSPLASH), 'f', Items.FEATHER, 'D', UCBlocks.darkBlock); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/items/baubles/EmblemRainbow.java | // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
| import java.util.List;
import java.util.Random;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.passive.EntitySheep;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Enchantments;
import net.minecraft.item.ItemShears;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.IShearable;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteractSpecific;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import baubles.api.BaubleType;
import baubles.api.BaublesApi;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap; | package com.bafomdad.uniquecrops.items.baubles;
public class EmblemRainbow extends ItemBauble {
public EmblemRainbow() {
| // Path: com/bafomdad/uniquecrops/core/EnumEmblems.java
// public enum EnumEmblems {
//
// MELEE,
// SCARAB,
// DEFENSE,
// IRONSTOMACH,
// POWERFIST,
// TRANSFORMATION,
// LEAF,
// FOOD,
// RAINBOW,
// PACIFISM;
// }
// Path: com/bafomdad/uniquecrops/items/baubles/EmblemRainbow.java
import java.util.List;
import java.util.Random;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.passive.EntitySheep;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Enchantments;
import net.minecraft.item.ItemShears;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.IShearable;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteractSpecific;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import baubles.api.BaubleType;
import baubles.api.BaublesApi;
import com.bafomdad.uniquecrops.core.EnumEmblems;
import com.google.common.collect.Multimap;
package com.bafomdad.uniquecrops.items.baubles;
public class EmblemRainbow extends ItemBauble {
public EmblemRainbow() {
| super(EnumEmblems.RAINBOW); |
bafomdad/uniquecrops | com/bafomdad/uniquecrops/blocks/BlockCropsBase.java | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: com/bafomdad/uniquecrops/core/EnumCrops.java
// public enum EnumCrops implements IStringSerializable {
//
// NORMAL("normal"),
// PRECISION("precision"),
// FLYINGPLANT("dirigible"),
// SHYPLANT("weepingbells"),
// BOOKPLANT("knowledge"),
// TELEPLANT("enderlily"),
// FOREVERPLANT("millennium"),
// BACKWARDSPLANT("merlinia"),
// INVISIBLEPLANT("invisibilia"),
// MUSICAPLANT("musica"),
// SAVAGEPLANT("feroxia"),
// CINDERBELLA("cinderbella"),
// HIGHPLANT("collis"),
// BLAZINGPLANT("maryjane"),
// EULA("eula"),
// DYE("dyeius"),
// COBBLEPLANT("cobblonia"),
// ABSTRACT("abstract"),
// DEVILSNARE("devilsnare"),
// WAFFLE("wafflonia"),
// PIXELS("pixelsius"),
// CRAFTER("artisia"),
// BEDROCKIUM("petramia"),
// ANVILICIOUS("malleatoris");
//
// final String name;
//
// EnumCrops(String name) {
//
// this.name = name;
// }
//
// @Override
// public String getName() {
//
// return name;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.annotation.Nullable;
import net.minecraft.block.BlockCrops;
import net.minecraft.block.state.IBlockState;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Enchantments;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import com.bafomdad.uniquecrops.UniqueCrops;
import com.bafomdad.uniquecrops.core.EnumCrops; | package com.bafomdad.uniquecrops.blocks;
public abstract class BlockCropsBase extends BlockCrops {
private EnumCrops type;
protected boolean extra;
protected boolean canPlant;
protected boolean clickHarvest;
public BlockCropsBase(EnumCrops type, boolean extra, boolean canPlant) {
this.type = type;
this.extra = extra;
this.canPlant = canPlant;
this.clickHarvest = true;
setRegistryName("crop" + type.getName()); | // Path: com/bafomdad/uniquecrops/UniqueCrops.java
// @Mod(modid=UniqueCrops.MOD_ID, name=UniqueCrops.MOD_NAME, version=UniqueCrops.VERSION)
// public class UniqueCrops {
//
// public static final String MOD_ID = "uniquecrops";
// public static final String MOD_NAME = "Unique Crops";
// public static final String VERSION = "0.2.02";
//
// @SidedProxy(clientSide="com.bafomdad.uniquecrops.proxies.ClientProxy", serverSide="com.bafomdad.uniquecrops.proxies.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.Instance(MOD_ID)
// public static UniqueCrops instance;
//
// public static UCTab TAB = new UCTab();
// public static UCConfig config;
//
// public static boolean baublesLoaded = Loader.isModLoaded("Baubles");
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// config = new UCConfig();
// config.loadConfig(event);
//
// proxy.preInit(event);
// proxy.initAllModels();
// proxy.checkResource();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// proxy.init(event);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: com/bafomdad/uniquecrops/core/EnumCrops.java
// public enum EnumCrops implements IStringSerializable {
//
// NORMAL("normal"),
// PRECISION("precision"),
// FLYINGPLANT("dirigible"),
// SHYPLANT("weepingbells"),
// BOOKPLANT("knowledge"),
// TELEPLANT("enderlily"),
// FOREVERPLANT("millennium"),
// BACKWARDSPLANT("merlinia"),
// INVISIBLEPLANT("invisibilia"),
// MUSICAPLANT("musica"),
// SAVAGEPLANT("feroxia"),
// CINDERBELLA("cinderbella"),
// HIGHPLANT("collis"),
// BLAZINGPLANT("maryjane"),
// EULA("eula"),
// DYE("dyeius"),
// COBBLEPLANT("cobblonia"),
// ABSTRACT("abstract"),
// DEVILSNARE("devilsnare"),
// WAFFLE("wafflonia"),
// PIXELS("pixelsius"),
// CRAFTER("artisia"),
// BEDROCKIUM("petramia"),
// ANVILICIOUS("malleatoris");
//
// final String name;
//
// EnumCrops(String name) {
//
// this.name = name;
// }
//
// @Override
// public String getName() {
//
// return name;
// }
// }
// Path: com/bafomdad/uniquecrops/blocks/BlockCropsBase.java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.annotation.Nullable;
import net.minecraft.block.BlockCrops;
import net.minecraft.block.state.IBlockState;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Enchantments;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import com.bafomdad.uniquecrops.UniqueCrops;
import com.bafomdad.uniquecrops.core.EnumCrops;
package com.bafomdad.uniquecrops.blocks;
public abstract class BlockCropsBase extends BlockCrops {
private EnumCrops type;
protected boolean extra;
protected boolean canPlant;
protected boolean clickHarvest;
public BlockCropsBase(EnumCrops type, boolean extra, boolean canPlant) {
this.type = type;
this.extra = extra;
this.canPlant = canPlant;
this.clickHarvest = true;
setRegistryName("crop" + type.getName()); | setUnlocalizedName(UniqueCrops.MOD_ID + ".crop" + type.getName()); |
TheCBProject/EnderStorage | src/main/java/codechicken/enderstorage/config/EnderStorageConfig.java | // Path: src/main/java/codechicken/enderstorage/EnderStorage.java
// @Mod (MOD_ID)
// public class EnderStorage {
//
// public static final Logger logger = LogManager.getLogger("EnderStorage");
//
// public static final String MOD_ID = "enderstorage";
//
// public static Proxy proxy;
//
// public EnderStorage() {
// proxy = DistExecutor.unsafeRunForDist(() -> ProxyClient::new, () -> Proxy::new);
// FMLJavaModLoadingContext.get().getModEventBus().register(this);
// EnderStorageConfig.load();
// EnderStorageManager.init();
// }
//
// @SubscribeEvent
// public void onCommonSetup(FMLCommonSetupEvent event) {
// proxy.commonSetup(event);
// }
//
// @SubscribeEvent
// public void onClientSetup(FMLClientSetupEvent event) {
// proxy.clientSetup(event);
// }
//
// @SubscribeEvent
// public void onServerSetup(FMLDedicatedServerSetupEvent event) {
//
// }
//
// // @Mod.EventHandler
// // public void serverStarting(FMLServerStartingEvent event) {
// // event.registerServerCommand(new EnderStorageCommand());
// // }
//
// }
| import codechicken.enderstorage.EnderStorage;
import codechicken.lib.config.ConfigTag;
import codechicken.lib.config.StandardConfigFile;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;
import java.nio.file.Paths; | if (config != null) {
throw new IllegalStateException("Tried to load config more than once.");
}
config = new StandardConfigFile(Paths.get("./config/EnderStorage.cfg")).load();
// ConfigSyncManager.registerSync(new ResourceLocation("enderstorage:config"), config);
ConfigTag personalItemTag = config.getTag("personalItem")//
.setComment("The RegistryName for the Item to lock EnderChests and Tanks.")//
.setDefaultString("minecraft:diamond");
anarchyMode = config.getTag("anarchyMode")//
.setComment("Causes chests to lose personal settings and drop the diamond on break.")//
.setDefaultBoolean(false)//
.getBoolean();
storageSize = config.getTag("item_storage_size")//
.setComment("The size of each inventory of EnderStorage, 0 = 3x3, 1 = 3x9, 2 = 6x9, default = 1")//
.setDefaultInt(1)//
.getInt();
disableCreatorVisuals = config.getTag("disableCreatorVisuals")//
.setComment("Disables the tank on top of creators heads.")//
.setDefaultBoolean(false)//
.getBoolean();
useVanillaEnderChestSounds = config.getTag("useVanillaEnderChestsSounds")//
.setComment("Enable this to make EnderStorage use vanilla's EnderChest sounds instead of the standard chest.")//
.setDefaultBoolean(false)//
.getBoolean();
ResourceLocation personalItemName = new ResourceLocation(personalItemTag.getString());
if (ForgeRegistries.ITEMS.containsKey(personalItemName)) {
personalItem = new ItemStack(ForgeRegistries.ITEMS.getValue(personalItemName));
} else { | // Path: src/main/java/codechicken/enderstorage/EnderStorage.java
// @Mod (MOD_ID)
// public class EnderStorage {
//
// public static final Logger logger = LogManager.getLogger("EnderStorage");
//
// public static final String MOD_ID = "enderstorage";
//
// public static Proxy proxy;
//
// public EnderStorage() {
// proxy = DistExecutor.unsafeRunForDist(() -> ProxyClient::new, () -> Proxy::new);
// FMLJavaModLoadingContext.get().getModEventBus().register(this);
// EnderStorageConfig.load();
// EnderStorageManager.init();
// }
//
// @SubscribeEvent
// public void onCommonSetup(FMLCommonSetupEvent event) {
// proxy.commonSetup(event);
// }
//
// @SubscribeEvent
// public void onClientSetup(FMLClientSetupEvent event) {
// proxy.clientSetup(event);
// }
//
// @SubscribeEvent
// public void onServerSetup(FMLDedicatedServerSetupEvent event) {
//
// }
//
// // @Mod.EventHandler
// // public void serverStarting(FMLServerStartingEvent event) {
// // event.registerServerCommand(new EnderStorageCommand());
// // }
//
// }
// Path: src/main/java/codechicken/enderstorage/config/EnderStorageConfig.java
import codechicken.enderstorage.EnderStorage;
import codechicken.lib.config.ConfigTag;
import codechicken.lib.config.StandardConfigFile;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;
import java.nio.file.Paths;
if (config != null) {
throw new IllegalStateException("Tried to load config more than once.");
}
config = new StandardConfigFile(Paths.get("./config/EnderStorage.cfg")).load();
// ConfigSyncManager.registerSync(new ResourceLocation("enderstorage:config"), config);
ConfigTag personalItemTag = config.getTag("personalItem")//
.setComment("The RegistryName for the Item to lock EnderChests and Tanks.")//
.setDefaultString("minecraft:diamond");
anarchyMode = config.getTag("anarchyMode")//
.setComment("Causes chests to lose personal settings and drop the diamond on break.")//
.setDefaultBoolean(false)//
.getBoolean();
storageSize = config.getTag("item_storage_size")//
.setComment("The size of each inventory of EnderStorage, 0 = 3x3, 1 = 3x9, 2 = 6x9, default = 1")//
.setDefaultInt(1)//
.getInt();
disableCreatorVisuals = config.getTag("disableCreatorVisuals")//
.setComment("Disables the tank on top of creators heads.")//
.setDefaultBoolean(false)//
.getBoolean();
useVanillaEnderChestSounds = config.getTag("useVanillaEnderChestsSounds")//
.setComment("Enable this to make EnderStorage use vanilla's EnderChest sounds instead of the standard chest.")//
.setDefaultBoolean(false)//
.getBoolean();
ResourceLocation personalItemName = new ResourceLocation(personalItemTag.getString());
if (ForgeRegistries.ITEMS.containsKey(personalItemName)) {
personalItem = new ItemStack(ForgeRegistries.ITEMS.getValue(personalItemName));
} else { | EnderStorage.logger.warn("Failed to load PersonaItem '{}', does not exist. Using default.", personalItemName); |
TheCBProject/EnderStorage | src/main/java/codechicken/enderstorage/client/model/ButtonModelLibrary.java | // Path: src/main/java/codechicken/enderstorage/tile/TileFrequencyOwner.java
// public abstract class TileFrequencyOwner extends TileEntity implements ITickableTileEntity {
//
// public static Cuboid6 selection_button = new Cuboid6(-1 / 16D, 0, -2 / 16D, 1 / 16D, 1 / 16D, 2 / 16D);
//
// protected Frequency frequency = new Frequency();
// private int changeCount;
//
// public TileFrequencyOwner(TileEntityType<?> tileEntityTypeIn) {
// super(tileEntityTypeIn);
// }
//
// public Frequency getFrequency() {
// return frequency;
// }
//
// public void setFreq(Frequency frequency) {
// this.frequency = frequency;
// onFrequencySet();
// setChanged();
// BlockState state = level.getBlockState(worldPosition);
// level.sendBlockUpdated(worldPosition, state, state, 3);
// if (!level.isClientSide) {
// sendUpdatePacket();
// }
// }
//
// @Override
// public void tick() {
// if (getStorage().getChangeCount() > changeCount) {
// level.updateNeighbourForOutputSignal(worldPosition, getBlockState().getBlock());
// changeCount = getStorage().getChangeCount();
// }
// }
//
// public abstract AbstractEnderStorage getStorage();
//
// public void onFrequencySet() {
//
// }
//
// @Override
// public void load(BlockState state, CompoundNBT tag) {
// super.load(state, tag);
// frequency.set(new Frequency(tag.getCompound("Frequency")));
// }
//
// @Override
// public CompoundNBT save(CompoundNBT tag) {
// super.save(tag);
// tag.put("Frequency", frequency.writeToNBT(new CompoundNBT()));
// return tag;
// }
//
// @Override
// public void setLevelAndPosition(World p_226984_1_, BlockPos p_226984_2_) {
// super.setLevelAndPosition(p_226984_1_, p_226984_2_);
// onFrequencySet();
// }
//
// public boolean activate(PlayerEntity player, int subHit, Hand hand) {
// return false;
// }
//
// public void onNeighborChange(BlockPos from) {
// }
//
// public void onPlaced(LivingEntity entity) {
// }
//
// protected void sendUpdatePacket() {
// createPacket().sendToChunk(level, getBlockPos().getX() >> 4, getBlockPos().getZ() >> 4);
// }
//
// public PacketCustom createPacket() {
// PacketCustom packet = new PacketCustom(EnderStorageNetwork.NET_CHANNEL, 1);
// writeToPacket(packet);
// return packet;
// }
//
// @Override
// public final SUpdateTileEntityPacket getUpdatePacket() {
// return createPacket().toTilePacket(getBlockPos());
// }
//
// @Override
// public CompoundNBT getUpdateTag() {
// return createPacket().writeToNBT(super.getUpdateTag());
// }
//
// public void writeToPacket(MCDataOutput packet) {
// frequency.writeToPacket(packet);
// }
//
// public void readFromPacket(MCDataInput packet) {
// frequency.set(Frequency.readFromPacket(packet));
// onFrequencySet();
// }
//
// @Override
// public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket pkt) {
// readFromPacket(PacketCustom.fromTilePacket(pkt));
// }
//
// @Override
// public void handleUpdateTag(BlockState state, CompoundNBT tag) {
// readFromPacket(PacketCustom.fromNBTTag(tag));
// }
//
// public int getLightValue() {
// return 0;
// }
//
// public boolean redstoneInteraction() {
// return false;
// }
//
// public int comparatorInput() {
// return 0;
// }
//
// public boolean rotate() {
// return false;
// }
// }
| import codechicken.enderstorage.tile.TileFrequencyOwner;
import codechicken.lib.render.CCModel;
import codechicken.lib.vec.Vector3;
import codechicken.lib.vec.Vertex5; | package codechicken.enderstorage.client.model;
public class ButtonModelLibrary {
public static CCModel button;
static {
generateButton();
}
private static void generateButton() {
button = CCModel.quadModel(20); | // Path: src/main/java/codechicken/enderstorage/tile/TileFrequencyOwner.java
// public abstract class TileFrequencyOwner extends TileEntity implements ITickableTileEntity {
//
// public static Cuboid6 selection_button = new Cuboid6(-1 / 16D, 0, -2 / 16D, 1 / 16D, 1 / 16D, 2 / 16D);
//
// protected Frequency frequency = new Frequency();
// private int changeCount;
//
// public TileFrequencyOwner(TileEntityType<?> tileEntityTypeIn) {
// super(tileEntityTypeIn);
// }
//
// public Frequency getFrequency() {
// return frequency;
// }
//
// public void setFreq(Frequency frequency) {
// this.frequency = frequency;
// onFrequencySet();
// setChanged();
// BlockState state = level.getBlockState(worldPosition);
// level.sendBlockUpdated(worldPosition, state, state, 3);
// if (!level.isClientSide) {
// sendUpdatePacket();
// }
// }
//
// @Override
// public void tick() {
// if (getStorage().getChangeCount() > changeCount) {
// level.updateNeighbourForOutputSignal(worldPosition, getBlockState().getBlock());
// changeCount = getStorage().getChangeCount();
// }
// }
//
// public abstract AbstractEnderStorage getStorage();
//
// public void onFrequencySet() {
//
// }
//
// @Override
// public void load(BlockState state, CompoundNBT tag) {
// super.load(state, tag);
// frequency.set(new Frequency(tag.getCompound("Frequency")));
// }
//
// @Override
// public CompoundNBT save(CompoundNBT tag) {
// super.save(tag);
// tag.put("Frequency", frequency.writeToNBT(new CompoundNBT()));
// return tag;
// }
//
// @Override
// public void setLevelAndPosition(World p_226984_1_, BlockPos p_226984_2_) {
// super.setLevelAndPosition(p_226984_1_, p_226984_2_);
// onFrequencySet();
// }
//
// public boolean activate(PlayerEntity player, int subHit, Hand hand) {
// return false;
// }
//
// public void onNeighborChange(BlockPos from) {
// }
//
// public void onPlaced(LivingEntity entity) {
// }
//
// protected void sendUpdatePacket() {
// createPacket().sendToChunk(level, getBlockPos().getX() >> 4, getBlockPos().getZ() >> 4);
// }
//
// public PacketCustom createPacket() {
// PacketCustom packet = new PacketCustom(EnderStorageNetwork.NET_CHANNEL, 1);
// writeToPacket(packet);
// return packet;
// }
//
// @Override
// public final SUpdateTileEntityPacket getUpdatePacket() {
// return createPacket().toTilePacket(getBlockPos());
// }
//
// @Override
// public CompoundNBT getUpdateTag() {
// return createPacket().writeToNBT(super.getUpdateTag());
// }
//
// public void writeToPacket(MCDataOutput packet) {
// frequency.writeToPacket(packet);
// }
//
// public void readFromPacket(MCDataInput packet) {
// frequency.set(Frequency.readFromPacket(packet));
// onFrequencySet();
// }
//
// @Override
// public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket pkt) {
// readFromPacket(PacketCustom.fromTilePacket(pkt));
// }
//
// @Override
// public void handleUpdateTag(BlockState state, CompoundNBT tag) {
// readFromPacket(PacketCustom.fromNBTTag(tag));
// }
//
// public int getLightValue() {
// return 0;
// }
//
// public boolean redstoneInteraction() {
// return false;
// }
//
// public int comparatorInput() {
// return 0;
// }
//
// public boolean rotate() {
// return false;
// }
// }
// Path: src/main/java/codechicken/enderstorage/client/model/ButtonModelLibrary.java
import codechicken.enderstorage.tile.TileFrequencyOwner;
import codechicken.lib.render.CCModel;
import codechicken.lib.vec.Vector3;
import codechicken.lib.vec.Vertex5;
package codechicken.enderstorage.client.model;
public class ButtonModelLibrary {
public static CCModel button;
static {
generateButton();
}
private static void generateButton() {
button = CCModel.quadModel(20); | Vector3 min = TileFrequencyOwner.selection_button.min; |
hecoding/Pac-Man | src/jeco/core/operator/mutation/UniformMutation.java | // Path: src/jeco/core/problem/Problem.java
// public abstract class Problem<V extends Variable<?>> {
// //private static final Logger logger = Logger.getLogger(Problem.class.getName());
//
// public static final double INFINITY = Double.POSITIVE_INFINITY;
// protected int numberOfVariables;
// protected int numberOfObjectives;
// protected double[] lowerBound;
// protected double[] upperBound;
//
// protected int maxEvaluations;
// protected int numEvaluations;
//
// public Problem(int numberOfVariables, int numberOfObjectives) {
// this.numberOfVariables = numberOfVariables;
// this.numberOfObjectives = numberOfObjectives;
// this.lowerBound = new double[numberOfVariables];
// this.upperBound = new double[numberOfVariables];
// this.maxEvaluations = Integer.MAX_VALUE;
// resetNumEvaluations();
// }
//
// public int getNumberOfVariables() {
// return numberOfVariables;
// }
//
// public int getNumberOfObjectives() {
// return numberOfObjectives;
// }
//
// public double getLowerBound(int i) {
// return lowerBound[i];
// }
//
// public double getUpperBound(int i) {
// return upperBound[i];
// }
//
// public int getMaxEvaluations() {
// return maxEvaluations;
// }
//
// public void setMaxEvaluations(int maxEvaluations) {
// this.maxEvaluations = maxEvaluations;
// }
//
// public int getNumEvaluations() {
// return numEvaluations;
// }
//
// public final void resetNumEvaluations() {
// numEvaluations = 0;
// }
//
// public void setNumEvaluations(int numEvaluations) {
// this.numEvaluations = numEvaluations;
// }
//
// public abstract Solutions<V> newRandomSetOfSolutions(int size);
//
// public void evaluate(Solutions<V> solutions) {
// for (Solution<V> solution : solutions) {
// evaluate(solution);
// }
// }
//
// public abstract void evaluate(Solution<V> solution);
//
// @Override
// public abstract Problem<V> clone();
//
// public boolean reachedMaxEvaluations() {
// return (numEvaluations >= maxEvaluations);
// }
// }
//
// Path: src/jeco/core/problem/Variable.java
// public class Variable<T> {
// protected T value;
//
// public Variable(T value) {
// this.value = value;
// }
//
// public T getValue() { return value; }
//
// public void setValue(T value) { this.value = value; }
//
// @Override
// public Variable<T> clone() {
// return new Variable<T>(value);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object right) {
// Variable<T> var = (Variable<T>)right;
// return this.value.equals(var.value);
// }
//
// @Override
// public String toString()
// {
// return value.toString();
// }
// }
| import java.util.ArrayList;
import jeco.core.problem.Problem;
import jeco.core.problem.Solution;
import jeco.core.problem.Variable;
import jeco.core.util.random.RandomGenerator; | package jeco.core.operator.mutation;
//Solutions must be real
public class UniformMutation<T extends Variable<Double>> extends MutationOperator<T> {
public static final double DEFAULT_PERTURBATION_INDEX = 0.5;
/**
* Stores the value used in a uniform mutation operator
*/
protected double perturbationIndex;
protected double probability; | // Path: src/jeco/core/problem/Problem.java
// public abstract class Problem<V extends Variable<?>> {
// //private static final Logger logger = Logger.getLogger(Problem.class.getName());
//
// public static final double INFINITY = Double.POSITIVE_INFINITY;
// protected int numberOfVariables;
// protected int numberOfObjectives;
// protected double[] lowerBound;
// protected double[] upperBound;
//
// protected int maxEvaluations;
// protected int numEvaluations;
//
// public Problem(int numberOfVariables, int numberOfObjectives) {
// this.numberOfVariables = numberOfVariables;
// this.numberOfObjectives = numberOfObjectives;
// this.lowerBound = new double[numberOfVariables];
// this.upperBound = new double[numberOfVariables];
// this.maxEvaluations = Integer.MAX_VALUE;
// resetNumEvaluations();
// }
//
// public int getNumberOfVariables() {
// return numberOfVariables;
// }
//
// public int getNumberOfObjectives() {
// return numberOfObjectives;
// }
//
// public double getLowerBound(int i) {
// return lowerBound[i];
// }
//
// public double getUpperBound(int i) {
// return upperBound[i];
// }
//
// public int getMaxEvaluations() {
// return maxEvaluations;
// }
//
// public void setMaxEvaluations(int maxEvaluations) {
// this.maxEvaluations = maxEvaluations;
// }
//
// public int getNumEvaluations() {
// return numEvaluations;
// }
//
// public final void resetNumEvaluations() {
// numEvaluations = 0;
// }
//
// public void setNumEvaluations(int numEvaluations) {
// this.numEvaluations = numEvaluations;
// }
//
// public abstract Solutions<V> newRandomSetOfSolutions(int size);
//
// public void evaluate(Solutions<V> solutions) {
// for (Solution<V> solution : solutions) {
// evaluate(solution);
// }
// }
//
// public abstract void evaluate(Solution<V> solution);
//
// @Override
// public abstract Problem<V> clone();
//
// public boolean reachedMaxEvaluations() {
// return (numEvaluations >= maxEvaluations);
// }
// }
//
// Path: src/jeco/core/problem/Variable.java
// public class Variable<T> {
// protected T value;
//
// public Variable(T value) {
// this.value = value;
// }
//
// public T getValue() { return value; }
//
// public void setValue(T value) { this.value = value; }
//
// @Override
// public Variable<T> clone() {
// return new Variable<T>(value);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object right) {
// Variable<T> var = (Variable<T>)right;
// return this.value.equals(var.value);
// }
//
// @Override
// public String toString()
// {
// return value.toString();
// }
// }
// Path: src/jeco/core/operator/mutation/UniformMutation.java
import java.util.ArrayList;
import jeco.core.problem.Problem;
import jeco.core.problem.Solution;
import jeco.core.problem.Variable;
import jeco.core.util.random.RandomGenerator;
package jeco.core.operator.mutation;
//Solutions must be real
public class UniformMutation<T extends Variable<Double>> extends MutationOperator<T> {
public static final double DEFAULT_PERTURBATION_INDEX = 0.5;
/**
* Stores the value used in a uniform mutation operator
*/
protected double perturbationIndex;
protected double probability; | protected Problem<T> problem; |
hecoding/Pac-Man | src/jeco/core/operator/evaluator/fitness/MOFitnessWrapper.java | // Path: src/pacman/game/util/GameInfo.java
// public class GameInfo {
//
// private int pillsEaten;
// private int powerPillsEaten;
// private int ghostsEaten;
// private int timeLasted;
// private int lastLevelReached;
// private int score;
//
// private double avgPillsEaten;
// private double avgPowerPillsEaten;
// private double avgGhostsEaten;
// private double avgTimeLasted;
// private double avgLastLevelReached;
// private double avgScore;
//
// public GameInfo(){
// pillsEaten = 0;
// powerPillsEaten = 0;
// ghostsEaten = 0;
// timeLasted = 0;
// lastLevelReached = 0;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
//
// public void increasePillsEaten(){
// this.pillsEaten++;
// }
//
// public void increasePowerPillsEaten(){
// this.powerPillsEaten++;
// }
//
// public void increaseGhostsEaten(){
// this.ghostsEaten++;
// }
//
// public int getLastLevelReached() {
// return lastLevelReached;
// }
// public void setLastLevelReached(int lastLevelReached) {
// this.lastLevelReached = lastLevelReached;
// }
// public int getPillsEaten() {
// return pillsEaten;
// }
// public void setPillsEaten(int pillsEaten) {
// this.pillsEaten = pillsEaten;
// }
// public int getPowerPillsEaten() {
// return powerPillsEaten;
// }
// public void setPowerPillsEaten(int powerPillsEaten) {
// this.powerPillsEaten = powerPillsEaten;
// }
// public int getGhostsEaten() {
// return ghostsEaten;
// }
// public void setGhostsEaten(int ghostsEaten) {
// this.ghostsEaten = ghostsEaten;
// }
// public int getTimeLasted() {
// return timeLasted;
// }
// public void setTimeLasted(int timeLasted) {
// this.timeLasted = timeLasted;
// }
// public double getAvgPillsEaten() {
// return avgPillsEaten;
// }
// public double getAvgPowerPillsEaten() {
// return avgPowerPillsEaten;
// }
// public double getAvgGhostsEaten() {
// return avgGhostsEaten;
// }
// public double getAvgTimeLasted() {
// return avgTimeLasted;
// }
// public double getAvgLastLevelReached() {
// return avgLastLevelReached;
// }
// public double getAvgScore() {
// return avgScore;
// }
// public void setAvgPillsEaten(double avgPillsEaten) {
// this.avgPillsEaten = avgPillsEaten;
// }
//
// public void setAvgPowerPillsEaten(double avgPowerPillsEaten) {
// this.avgPowerPillsEaten = avgPowerPillsEaten;
// }
//
// public void setAvgGhostsEaten(double avgGhostsEaten) {
// this.avgGhostsEaten = avgGhostsEaten;
// }
//
// public void setAvgTimeLasted(double avgTimeLasted) {
// this.avgTimeLasted = avgTimeLasted;
// }
//
// public void setAvgLastLevelReached(double avgLastLevelReached) {
// this.avgLastLevelReached = avgLastLevelReached;
// }
//
// public void setAvgScore(double avgScore) {
// this.avgScore = avgScore;
// }
//
// public static GameInfo averageGamesInfo(ArrayList<GameInfo> gamesInfo){
// GameInfo giFinal = new GameInfo();
//
// double pillsTotales = 0;
// double powerPillsTotales = 0;
// double ghostsTotales = 0;
// double timeTotal = 0;
// double levelsTotal = 0;
// double scoreTotal = 0;
//
// int numGames = gamesInfo.size();
//
// for(int i = 0; i < numGames; i++){
// pillsTotales += gamesInfo.get(i).getPillsEaten();
// powerPillsTotales += gamesInfo.get(i).getPowerPillsEaten();
// ghostsTotales += gamesInfo.get(i).getGhostsEaten();
// timeTotal += gamesInfo.get(i).getTimeLasted();
// levelsTotal += gamesInfo.get(i).getLastLevelReached();
// scoreTotal += gamesInfo.get(i).getScore();
// }
//
// pillsTotales /= numGames;
// powerPillsTotales /= numGames;
// ghostsTotales /= numGames;
// timeTotal /= numGames;
// levelsTotal /= numGames;
// scoreTotal /= numGames;
//
// giFinal.setAvgPillsEaten(pillsTotales);
// giFinal.setAvgPowerPillsEaten(powerPillsTotales);
// giFinal.setAvgGhostsEaten(ghostsTotales);
// giFinal.setAvgTimeLasted(timeTotal);
// giFinal.setAvgLastLevelReached(levelsTotal);
// giFinal.setAvgScore(scoreTotal);
//
// return giFinal;
// }
//
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import pacman.game.util.GameInfo; | package jeco.core.operator.evaluator.fitness;
public class MOFitnessWrapper {
public ArrayList<FitnessEvaluatorInterface> funcs;
public MOFitnessWrapper(FitnessEvaluatorInterface... funcs) {
this.funcs = new ArrayList<>(funcs.length);
Collections.addAll(this.funcs, funcs);
}
public void addObjectiveFunction(FitnessEvaluatorInterface f) {
if (f != null)
this.funcs.add(f);
}
| // Path: src/pacman/game/util/GameInfo.java
// public class GameInfo {
//
// private int pillsEaten;
// private int powerPillsEaten;
// private int ghostsEaten;
// private int timeLasted;
// private int lastLevelReached;
// private int score;
//
// private double avgPillsEaten;
// private double avgPowerPillsEaten;
// private double avgGhostsEaten;
// private double avgTimeLasted;
// private double avgLastLevelReached;
// private double avgScore;
//
// public GameInfo(){
// pillsEaten = 0;
// powerPillsEaten = 0;
// ghostsEaten = 0;
// timeLasted = 0;
// lastLevelReached = 0;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
//
// public void increasePillsEaten(){
// this.pillsEaten++;
// }
//
// public void increasePowerPillsEaten(){
// this.powerPillsEaten++;
// }
//
// public void increaseGhostsEaten(){
// this.ghostsEaten++;
// }
//
// public int getLastLevelReached() {
// return lastLevelReached;
// }
// public void setLastLevelReached(int lastLevelReached) {
// this.lastLevelReached = lastLevelReached;
// }
// public int getPillsEaten() {
// return pillsEaten;
// }
// public void setPillsEaten(int pillsEaten) {
// this.pillsEaten = pillsEaten;
// }
// public int getPowerPillsEaten() {
// return powerPillsEaten;
// }
// public void setPowerPillsEaten(int powerPillsEaten) {
// this.powerPillsEaten = powerPillsEaten;
// }
// public int getGhostsEaten() {
// return ghostsEaten;
// }
// public void setGhostsEaten(int ghostsEaten) {
// this.ghostsEaten = ghostsEaten;
// }
// public int getTimeLasted() {
// return timeLasted;
// }
// public void setTimeLasted(int timeLasted) {
// this.timeLasted = timeLasted;
// }
// public double getAvgPillsEaten() {
// return avgPillsEaten;
// }
// public double getAvgPowerPillsEaten() {
// return avgPowerPillsEaten;
// }
// public double getAvgGhostsEaten() {
// return avgGhostsEaten;
// }
// public double getAvgTimeLasted() {
// return avgTimeLasted;
// }
// public double getAvgLastLevelReached() {
// return avgLastLevelReached;
// }
// public double getAvgScore() {
// return avgScore;
// }
// public void setAvgPillsEaten(double avgPillsEaten) {
// this.avgPillsEaten = avgPillsEaten;
// }
//
// public void setAvgPowerPillsEaten(double avgPowerPillsEaten) {
// this.avgPowerPillsEaten = avgPowerPillsEaten;
// }
//
// public void setAvgGhostsEaten(double avgGhostsEaten) {
// this.avgGhostsEaten = avgGhostsEaten;
// }
//
// public void setAvgTimeLasted(double avgTimeLasted) {
// this.avgTimeLasted = avgTimeLasted;
// }
//
// public void setAvgLastLevelReached(double avgLastLevelReached) {
// this.avgLastLevelReached = avgLastLevelReached;
// }
//
// public void setAvgScore(double avgScore) {
// this.avgScore = avgScore;
// }
//
// public static GameInfo averageGamesInfo(ArrayList<GameInfo> gamesInfo){
// GameInfo giFinal = new GameInfo();
//
// double pillsTotales = 0;
// double powerPillsTotales = 0;
// double ghostsTotales = 0;
// double timeTotal = 0;
// double levelsTotal = 0;
// double scoreTotal = 0;
//
// int numGames = gamesInfo.size();
//
// for(int i = 0; i < numGames; i++){
// pillsTotales += gamesInfo.get(i).getPillsEaten();
// powerPillsTotales += gamesInfo.get(i).getPowerPillsEaten();
// ghostsTotales += gamesInfo.get(i).getGhostsEaten();
// timeTotal += gamesInfo.get(i).getTimeLasted();
// levelsTotal += gamesInfo.get(i).getLastLevelReached();
// scoreTotal += gamesInfo.get(i).getScore();
// }
//
// pillsTotales /= numGames;
// powerPillsTotales /= numGames;
// ghostsTotales /= numGames;
// timeTotal /= numGames;
// levelsTotal /= numGames;
// scoreTotal /= numGames;
//
// giFinal.setAvgPillsEaten(pillsTotales);
// giFinal.setAvgPowerPillsEaten(powerPillsTotales);
// giFinal.setAvgGhostsEaten(ghostsTotales);
// giFinal.setAvgTimeLasted(timeTotal);
// giFinal.setAvgLastLevelReached(levelsTotal);
// giFinal.setAvgScore(scoreTotal);
//
// return giFinal;
// }
//
// }
// Path: src/jeco/core/operator/evaluator/fitness/MOFitnessWrapper.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import pacman.game.util.GameInfo;
package jeco.core.operator.evaluator.fitness;
public class MOFitnessWrapper {
public ArrayList<FitnessEvaluatorInterface> funcs;
public MOFitnessWrapper(FitnessEvaluatorInterface... funcs) {
this.funcs = new ArrayList<>(funcs.length);
Collections.addAll(this.funcs, funcs);
}
public void addObjectiveFunction(FitnessEvaluatorInterface f) {
if (f != null)
this.funcs.add(f);
}
| public ArrayList<Double> evaluate(GameInfo gi) { |
hecoding/Pac-Man | src/view/gui/swing/factory/ObjectiveFactory.java | // Path: src/jeco/core/operator/evaluator/fitness/FitnessEvaluatorInterface.java
// public interface FitnessEvaluatorInterface {
//
// public double evaluate(GameInfo gi);
// public double worstFitness();
// public String getName();
//
// }
| import java.util.HashMap;
import jeco.core.operator.evaluator.fitness.FitnessEvaluatorInterface; | package view.gui.swing.factory;
public class ObjectiveFactory {
private static ObjectiveFactory instance; | // Path: src/jeco/core/operator/evaluator/fitness/FitnessEvaluatorInterface.java
// public interface FitnessEvaluatorInterface {
//
// public double evaluate(GameInfo gi);
// public double worstFitness();
// public String getName();
//
// }
// Path: src/view/gui/swing/factory/ObjectiveFactory.java
import java.util.HashMap;
import jeco.core.operator.evaluator.fitness.FitnessEvaluatorInterface;
package view.gui.swing.factory;
public class ObjectiveFactory {
private static ObjectiveFactory instance; | private HashMap<String, Class<? extends FitnessEvaluatorInterface>> registered = new HashMap<>(); |
hecoding/Pac-Man | src/jeco/core/operator/evaluator/fitness/NaiveFitness.java | // Path: src/pacman/game/util/GameInfo.java
// public class GameInfo {
//
// private int pillsEaten;
// private int powerPillsEaten;
// private int ghostsEaten;
// private int timeLasted;
// private int lastLevelReached;
// private int score;
//
// private double avgPillsEaten;
// private double avgPowerPillsEaten;
// private double avgGhostsEaten;
// private double avgTimeLasted;
// private double avgLastLevelReached;
// private double avgScore;
//
// public GameInfo(){
// pillsEaten = 0;
// powerPillsEaten = 0;
// ghostsEaten = 0;
// timeLasted = 0;
// lastLevelReached = 0;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
//
// public void increasePillsEaten(){
// this.pillsEaten++;
// }
//
// public void increasePowerPillsEaten(){
// this.powerPillsEaten++;
// }
//
// public void increaseGhostsEaten(){
// this.ghostsEaten++;
// }
//
// public int getLastLevelReached() {
// return lastLevelReached;
// }
// public void setLastLevelReached(int lastLevelReached) {
// this.lastLevelReached = lastLevelReached;
// }
// public int getPillsEaten() {
// return pillsEaten;
// }
// public void setPillsEaten(int pillsEaten) {
// this.pillsEaten = pillsEaten;
// }
// public int getPowerPillsEaten() {
// return powerPillsEaten;
// }
// public void setPowerPillsEaten(int powerPillsEaten) {
// this.powerPillsEaten = powerPillsEaten;
// }
// public int getGhostsEaten() {
// return ghostsEaten;
// }
// public void setGhostsEaten(int ghostsEaten) {
// this.ghostsEaten = ghostsEaten;
// }
// public int getTimeLasted() {
// return timeLasted;
// }
// public void setTimeLasted(int timeLasted) {
// this.timeLasted = timeLasted;
// }
// public double getAvgPillsEaten() {
// return avgPillsEaten;
// }
// public double getAvgPowerPillsEaten() {
// return avgPowerPillsEaten;
// }
// public double getAvgGhostsEaten() {
// return avgGhostsEaten;
// }
// public double getAvgTimeLasted() {
// return avgTimeLasted;
// }
// public double getAvgLastLevelReached() {
// return avgLastLevelReached;
// }
// public double getAvgScore() {
// return avgScore;
// }
// public void setAvgPillsEaten(double avgPillsEaten) {
// this.avgPillsEaten = avgPillsEaten;
// }
//
// public void setAvgPowerPillsEaten(double avgPowerPillsEaten) {
// this.avgPowerPillsEaten = avgPowerPillsEaten;
// }
//
// public void setAvgGhostsEaten(double avgGhostsEaten) {
// this.avgGhostsEaten = avgGhostsEaten;
// }
//
// public void setAvgTimeLasted(double avgTimeLasted) {
// this.avgTimeLasted = avgTimeLasted;
// }
//
// public void setAvgLastLevelReached(double avgLastLevelReached) {
// this.avgLastLevelReached = avgLastLevelReached;
// }
//
// public void setAvgScore(double avgScore) {
// this.avgScore = avgScore;
// }
//
// public static GameInfo averageGamesInfo(ArrayList<GameInfo> gamesInfo){
// GameInfo giFinal = new GameInfo();
//
// double pillsTotales = 0;
// double powerPillsTotales = 0;
// double ghostsTotales = 0;
// double timeTotal = 0;
// double levelsTotal = 0;
// double scoreTotal = 0;
//
// int numGames = gamesInfo.size();
//
// for(int i = 0; i < numGames; i++){
// pillsTotales += gamesInfo.get(i).getPillsEaten();
// powerPillsTotales += gamesInfo.get(i).getPowerPillsEaten();
// ghostsTotales += gamesInfo.get(i).getGhostsEaten();
// timeTotal += gamesInfo.get(i).getTimeLasted();
// levelsTotal += gamesInfo.get(i).getLastLevelReached();
// scoreTotal += gamesInfo.get(i).getScore();
// }
//
// pillsTotales /= numGames;
// powerPillsTotales /= numGames;
// ghostsTotales /= numGames;
// timeTotal /= numGames;
// levelsTotal /= numGames;
// scoreTotal /= numGames;
//
// giFinal.setAvgPillsEaten(pillsTotales);
// giFinal.setAvgPowerPillsEaten(powerPillsTotales);
// giFinal.setAvgGhostsEaten(ghostsTotales);
// giFinal.setAvgTimeLasted(timeTotal);
// giFinal.setAvgLastLevelReached(levelsTotal);
// giFinal.setAvgScore(scoreTotal);
//
// return giFinal;
// }
//
// }
| import pacman.game.util.GameInfo; | package jeco.core.operator.evaluator.fitness;
public class NaiveFitness implements FitnessEvaluatorInterface {
@Override | // Path: src/pacman/game/util/GameInfo.java
// public class GameInfo {
//
// private int pillsEaten;
// private int powerPillsEaten;
// private int ghostsEaten;
// private int timeLasted;
// private int lastLevelReached;
// private int score;
//
// private double avgPillsEaten;
// private double avgPowerPillsEaten;
// private double avgGhostsEaten;
// private double avgTimeLasted;
// private double avgLastLevelReached;
// private double avgScore;
//
// public GameInfo(){
// pillsEaten = 0;
// powerPillsEaten = 0;
// ghostsEaten = 0;
// timeLasted = 0;
// lastLevelReached = 0;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
//
// public void increasePillsEaten(){
// this.pillsEaten++;
// }
//
// public void increasePowerPillsEaten(){
// this.powerPillsEaten++;
// }
//
// public void increaseGhostsEaten(){
// this.ghostsEaten++;
// }
//
// public int getLastLevelReached() {
// return lastLevelReached;
// }
// public void setLastLevelReached(int lastLevelReached) {
// this.lastLevelReached = lastLevelReached;
// }
// public int getPillsEaten() {
// return pillsEaten;
// }
// public void setPillsEaten(int pillsEaten) {
// this.pillsEaten = pillsEaten;
// }
// public int getPowerPillsEaten() {
// return powerPillsEaten;
// }
// public void setPowerPillsEaten(int powerPillsEaten) {
// this.powerPillsEaten = powerPillsEaten;
// }
// public int getGhostsEaten() {
// return ghostsEaten;
// }
// public void setGhostsEaten(int ghostsEaten) {
// this.ghostsEaten = ghostsEaten;
// }
// public int getTimeLasted() {
// return timeLasted;
// }
// public void setTimeLasted(int timeLasted) {
// this.timeLasted = timeLasted;
// }
// public double getAvgPillsEaten() {
// return avgPillsEaten;
// }
// public double getAvgPowerPillsEaten() {
// return avgPowerPillsEaten;
// }
// public double getAvgGhostsEaten() {
// return avgGhostsEaten;
// }
// public double getAvgTimeLasted() {
// return avgTimeLasted;
// }
// public double getAvgLastLevelReached() {
// return avgLastLevelReached;
// }
// public double getAvgScore() {
// return avgScore;
// }
// public void setAvgPillsEaten(double avgPillsEaten) {
// this.avgPillsEaten = avgPillsEaten;
// }
//
// public void setAvgPowerPillsEaten(double avgPowerPillsEaten) {
// this.avgPowerPillsEaten = avgPowerPillsEaten;
// }
//
// public void setAvgGhostsEaten(double avgGhostsEaten) {
// this.avgGhostsEaten = avgGhostsEaten;
// }
//
// public void setAvgTimeLasted(double avgTimeLasted) {
// this.avgTimeLasted = avgTimeLasted;
// }
//
// public void setAvgLastLevelReached(double avgLastLevelReached) {
// this.avgLastLevelReached = avgLastLevelReached;
// }
//
// public void setAvgScore(double avgScore) {
// this.avgScore = avgScore;
// }
//
// public static GameInfo averageGamesInfo(ArrayList<GameInfo> gamesInfo){
// GameInfo giFinal = new GameInfo();
//
// double pillsTotales = 0;
// double powerPillsTotales = 0;
// double ghostsTotales = 0;
// double timeTotal = 0;
// double levelsTotal = 0;
// double scoreTotal = 0;
//
// int numGames = gamesInfo.size();
//
// for(int i = 0; i < numGames; i++){
// pillsTotales += gamesInfo.get(i).getPillsEaten();
// powerPillsTotales += gamesInfo.get(i).getPowerPillsEaten();
// ghostsTotales += gamesInfo.get(i).getGhostsEaten();
// timeTotal += gamesInfo.get(i).getTimeLasted();
// levelsTotal += gamesInfo.get(i).getLastLevelReached();
// scoreTotal += gamesInfo.get(i).getScore();
// }
//
// pillsTotales /= numGames;
// powerPillsTotales /= numGames;
// ghostsTotales /= numGames;
// timeTotal /= numGames;
// levelsTotal /= numGames;
// scoreTotal /= numGames;
//
// giFinal.setAvgPillsEaten(pillsTotales);
// giFinal.setAvgPowerPillsEaten(powerPillsTotales);
// giFinal.setAvgGhostsEaten(ghostsTotales);
// giFinal.setAvgTimeLasted(timeTotal);
// giFinal.setAvgLastLevelReached(levelsTotal);
// giFinal.setAvgScore(scoreTotal);
//
// return giFinal;
// }
//
// }
// Path: src/jeco/core/operator/evaluator/fitness/NaiveFitness.java
import pacman.game.util.GameInfo;
package jeco.core.operator.evaluator.fitness;
public class NaiveFitness implements FitnessEvaluatorInterface {
@Override | public double evaluate(GameInfo gi) { |
hecoding/Pac-Man | src/pacman/game/internal/Ghost.java | // Path: src/pacman/game/Constants.java
// public enum GHOST
// {
// BLINKY(40),
// PINKY(60),
// INKY(80),
// SUE(100);
//
// public final int initialLairTime;
//
// GHOST(int lairTime)
// {
// this.initialLairTime=lairTime;
// }
// };
//
// Path: src/pacman/game/Constants.java
// public enum MOVE
// {
// UP {
// public MOVE opposite() {
// return MOVE.DOWN;
// }
//
// public MOVE R90() {
// return MOVE.RIGHT;
// }
//
// public MOVE L90() {
// return MOVE.LEFT;
// };
// },
// RIGHT {
// public MOVE opposite() {
// return MOVE.LEFT;
// }
//
// public MOVE R90() {
// return MOVE.DOWN;
// }
//
// public MOVE L90() {
// return MOVE.UP;
// };
// },
// DOWN {
// public MOVE opposite() {
// return MOVE.UP;
// }
//
// public MOVE R90() {
// return MOVE.LEFT;
// }
//
// public MOVE L90() {
// return MOVE.RIGHT;
// };
// },
// LEFT {
// public MOVE opposite() {
// return MOVE.RIGHT;
// }
//
// public MOVE R90() {
// return MOVE.UP;
// }
//
// public MOVE L90() {
// return MOVE.DOWN;
// };
// },
// NEUTRAL {
// public MOVE opposite() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE R90() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE L90() {
// return MOVE.NEUTRAL;
// };
// };
//
// public abstract MOVE opposite();
// public abstract MOVE R90();
// public abstract MOVE L90();
// };
| import pacman.game.Constants.GHOST;
import pacman.game.Constants.MOVE; | package pacman.game.internal;
/*
* Data structure to hold all information pertaining to the ghosts.
*/
public final class Ghost
{
public int currentNodeIndex, edibleTime, lairTime; | // Path: src/pacman/game/Constants.java
// public enum GHOST
// {
// BLINKY(40),
// PINKY(60),
// INKY(80),
// SUE(100);
//
// public final int initialLairTime;
//
// GHOST(int lairTime)
// {
// this.initialLairTime=lairTime;
// }
// };
//
// Path: src/pacman/game/Constants.java
// public enum MOVE
// {
// UP {
// public MOVE opposite() {
// return MOVE.DOWN;
// }
//
// public MOVE R90() {
// return MOVE.RIGHT;
// }
//
// public MOVE L90() {
// return MOVE.LEFT;
// };
// },
// RIGHT {
// public MOVE opposite() {
// return MOVE.LEFT;
// }
//
// public MOVE R90() {
// return MOVE.DOWN;
// }
//
// public MOVE L90() {
// return MOVE.UP;
// };
// },
// DOWN {
// public MOVE opposite() {
// return MOVE.UP;
// }
//
// public MOVE R90() {
// return MOVE.LEFT;
// }
//
// public MOVE L90() {
// return MOVE.RIGHT;
// };
// },
// LEFT {
// public MOVE opposite() {
// return MOVE.RIGHT;
// }
//
// public MOVE R90() {
// return MOVE.UP;
// }
//
// public MOVE L90() {
// return MOVE.DOWN;
// };
// },
// NEUTRAL {
// public MOVE opposite() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE R90() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE L90() {
// return MOVE.NEUTRAL;
// };
// };
//
// public abstract MOVE opposite();
// public abstract MOVE R90();
// public abstract MOVE L90();
// };
// Path: src/pacman/game/internal/Ghost.java
import pacman.game.Constants.GHOST;
import pacman.game.Constants.MOVE;
package pacman.game.internal;
/*
* Data structure to hold all information pertaining to the ghosts.
*/
public final class Ghost
{
public int currentNodeIndex, edibleTime, lairTime; | public GHOST type; |
hecoding/Pac-Man | src/pacman/game/internal/Ghost.java | // Path: src/pacman/game/Constants.java
// public enum GHOST
// {
// BLINKY(40),
// PINKY(60),
// INKY(80),
// SUE(100);
//
// public final int initialLairTime;
//
// GHOST(int lairTime)
// {
// this.initialLairTime=lairTime;
// }
// };
//
// Path: src/pacman/game/Constants.java
// public enum MOVE
// {
// UP {
// public MOVE opposite() {
// return MOVE.DOWN;
// }
//
// public MOVE R90() {
// return MOVE.RIGHT;
// }
//
// public MOVE L90() {
// return MOVE.LEFT;
// };
// },
// RIGHT {
// public MOVE opposite() {
// return MOVE.LEFT;
// }
//
// public MOVE R90() {
// return MOVE.DOWN;
// }
//
// public MOVE L90() {
// return MOVE.UP;
// };
// },
// DOWN {
// public MOVE opposite() {
// return MOVE.UP;
// }
//
// public MOVE R90() {
// return MOVE.LEFT;
// }
//
// public MOVE L90() {
// return MOVE.RIGHT;
// };
// },
// LEFT {
// public MOVE opposite() {
// return MOVE.RIGHT;
// }
//
// public MOVE R90() {
// return MOVE.UP;
// }
//
// public MOVE L90() {
// return MOVE.DOWN;
// };
// },
// NEUTRAL {
// public MOVE opposite() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE R90() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE L90() {
// return MOVE.NEUTRAL;
// };
// };
//
// public abstract MOVE opposite();
// public abstract MOVE R90();
// public abstract MOVE L90();
// };
| import pacman.game.Constants.GHOST;
import pacman.game.Constants.MOVE; | package pacman.game.internal;
/*
* Data structure to hold all information pertaining to the ghosts.
*/
public final class Ghost
{
public int currentNodeIndex, edibleTime, lairTime;
public GHOST type; | // Path: src/pacman/game/Constants.java
// public enum GHOST
// {
// BLINKY(40),
// PINKY(60),
// INKY(80),
// SUE(100);
//
// public final int initialLairTime;
//
// GHOST(int lairTime)
// {
// this.initialLairTime=lairTime;
// }
// };
//
// Path: src/pacman/game/Constants.java
// public enum MOVE
// {
// UP {
// public MOVE opposite() {
// return MOVE.DOWN;
// }
//
// public MOVE R90() {
// return MOVE.RIGHT;
// }
//
// public MOVE L90() {
// return MOVE.LEFT;
// };
// },
// RIGHT {
// public MOVE opposite() {
// return MOVE.LEFT;
// }
//
// public MOVE R90() {
// return MOVE.DOWN;
// }
//
// public MOVE L90() {
// return MOVE.UP;
// };
// },
// DOWN {
// public MOVE opposite() {
// return MOVE.UP;
// }
//
// public MOVE R90() {
// return MOVE.LEFT;
// }
//
// public MOVE L90() {
// return MOVE.RIGHT;
// };
// },
// LEFT {
// public MOVE opposite() {
// return MOVE.RIGHT;
// }
//
// public MOVE R90() {
// return MOVE.UP;
// }
//
// public MOVE L90() {
// return MOVE.DOWN;
// };
// },
// NEUTRAL {
// public MOVE opposite() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE R90() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE L90() {
// return MOVE.NEUTRAL;
// };
// };
//
// public abstract MOVE opposite();
// public abstract MOVE R90();
// public abstract MOVE L90();
// };
// Path: src/pacman/game/internal/Ghost.java
import pacman.game.Constants.GHOST;
import pacman.game.Constants.MOVE;
package pacman.game.internal;
/*
* Data structure to hold all information pertaining to the ghosts.
*/
public final class Ghost
{
public int currentNodeIndex, edibleTime, lairTime;
public GHOST type; | public MOVE lastMoveMade; |
hecoding/Pac-Man | src/jeco/core/operator/evaluator/fitness/GhostsEatenFitness.java | // Path: src/pacman/game/util/GameInfo.java
// public class GameInfo {
//
// private int pillsEaten;
// private int powerPillsEaten;
// private int ghostsEaten;
// private int timeLasted;
// private int lastLevelReached;
// private int score;
//
// private double avgPillsEaten;
// private double avgPowerPillsEaten;
// private double avgGhostsEaten;
// private double avgTimeLasted;
// private double avgLastLevelReached;
// private double avgScore;
//
// public GameInfo(){
// pillsEaten = 0;
// powerPillsEaten = 0;
// ghostsEaten = 0;
// timeLasted = 0;
// lastLevelReached = 0;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
//
// public void increasePillsEaten(){
// this.pillsEaten++;
// }
//
// public void increasePowerPillsEaten(){
// this.powerPillsEaten++;
// }
//
// public void increaseGhostsEaten(){
// this.ghostsEaten++;
// }
//
// public int getLastLevelReached() {
// return lastLevelReached;
// }
// public void setLastLevelReached(int lastLevelReached) {
// this.lastLevelReached = lastLevelReached;
// }
// public int getPillsEaten() {
// return pillsEaten;
// }
// public void setPillsEaten(int pillsEaten) {
// this.pillsEaten = pillsEaten;
// }
// public int getPowerPillsEaten() {
// return powerPillsEaten;
// }
// public void setPowerPillsEaten(int powerPillsEaten) {
// this.powerPillsEaten = powerPillsEaten;
// }
// public int getGhostsEaten() {
// return ghostsEaten;
// }
// public void setGhostsEaten(int ghostsEaten) {
// this.ghostsEaten = ghostsEaten;
// }
// public int getTimeLasted() {
// return timeLasted;
// }
// public void setTimeLasted(int timeLasted) {
// this.timeLasted = timeLasted;
// }
// public double getAvgPillsEaten() {
// return avgPillsEaten;
// }
// public double getAvgPowerPillsEaten() {
// return avgPowerPillsEaten;
// }
// public double getAvgGhostsEaten() {
// return avgGhostsEaten;
// }
// public double getAvgTimeLasted() {
// return avgTimeLasted;
// }
// public double getAvgLastLevelReached() {
// return avgLastLevelReached;
// }
// public double getAvgScore() {
// return avgScore;
// }
// public void setAvgPillsEaten(double avgPillsEaten) {
// this.avgPillsEaten = avgPillsEaten;
// }
//
// public void setAvgPowerPillsEaten(double avgPowerPillsEaten) {
// this.avgPowerPillsEaten = avgPowerPillsEaten;
// }
//
// public void setAvgGhostsEaten(double avgGhostsEaten) {
// this.avgGhostsEaten = avgGhostsEaten;
// }
//
// public void setAvgTimeLasted(double avgTimeLasted) {
// this.avgTimeLasted = avgTimeLasted;
// }
//
// public void setAvgLastLevelReached(double avgLastLevelReached) {
// this.avgLastLevelReached = avgLastLevelReached;
// }
//
// public void setAvgScore(double avgScore) {
// this.avgScore = avgScore;
// }
//
// public static GameInfo averageGamesInfo(ArrayList<GameInfo> gamesInfo){
// GameInfo giFinal = new GameInfo();
//
// double pillsTotales = 0;
// double powerPillsTotales = 0;
// double ghostsTotales = 0;
// double timeTotal = 0;
// double levelsTotal = 0;
// double scoreTotal = 0;
//
// int numGames = gamesInfo.size();
//
// for(int i = 0; i < numGames; i++){
// pillsTotales += gamesInfo.get(i).getPillsEaten();
// powerPillsTotales += gamesInfo.get(i).getPowerPillsEaten();
// ghostsTotales += gamesInfo.get(i).getGhostsEaten();
// timeTotal += gamesInfo.get(i).getTimeLasted();
// levelsTotal += gamesInfo.get(i).getLastLevelReached();
// scoreTotal += gamesInfo.get(i).getScore();
// }
//
// pillsTotales /= numGames;
// powerPillsTotales /= numGames;
// ghostsTotales /= numGames;
// timeTotal /= numGames;
// levelsTotal /= numGames;
// scoreTotal /= numGames;
//
// giFinal.setAvgPillsEaten(pillsTotales);
// giFinal.setAvgPowerPillsEaten(powerPillsTotales);
// giFinal.setAvgGhostsEaten(ghostsTotales);
// giFinal.setAvgTimeLasted(timeTotal);
// giFinal.setAvgLastLevelReached(levelsTotal);
// giFinal.setAvgScore(scoreTotal);
//
// return giFinal;
// }
//
// }
| import pacman.game.util.GameInfo; | package jeco.core.operator.evaluator.fitness;
public class GhostsEatenFitness implements FitnessEvaluatorInterface {
@Override | // Path: src/pacman/game/util/GameInfo.java
// public class GameInfo {
//
// private int pillsEaten;
// private int powerPillsEaten;
// private int ghostsEaten;
// private int timeLasted;
// private int lastLevelReached;
// private int score;
//
// private double avgPillsEaten;
// private double avgPowerPillsEaten;
// private double avgGhostsEaten;
// private double avgTimeLasted;
// private double avgLastLevelReached;
// private double avgScore;
//
// public GameInfo(){
// pillsEaten = 0;
// powerPillsEaten = 0;
// ghostsEaten = 0;
// timeLasted = 0;
// lastLevelReached = 0;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
//
// public void increasePillsEaten(){
// this.pillsEaten++;
// }
//
// public void increasePowerPillsEaten(){
// this.powerPillsEaten++;
// }
//
// public void increaseGhostsEaten(){
// this.ghostsEaten++;
// }
//
// public int getLastLevelReached() {
// return lastLevelReached;
// }
// public void setLastLevelReached(int lastLevelReached) {
// this.lastLevelReached = lastLevelReached;
// }
// public int getPillsEaten() {
// return pillsEaten;
// }
// public void setPillsEaten(int pillsEaten) {
// this.pillsEaten = pillsEaten;
// }
// public int getPowerPillsEaten() {
// return powerPillsEaten;
// }
// public void setPowerPillsEaten(int powerPillsEaten) {
// this.powerPillsEaten = powerPillsEaten;
// }
// public int getGhostsEaten() {
// return ghostsEaten;
// }
// public void setGhostsEaten(int ghostsEaten) {
// this.ghostsEaten = ghostsEaten;
// }
// public int getTimeLasted() {
// return timeLasted;
// }
// public void setTimeLasted(int timeLasted) {
// this.timeLasted = timeLasted;
// }
// public double getAvgPillsEaten() {
// return avgPillsEaten;
// }
// public double getAvgPowerPillsEaten() {
// return avgPowerPillsEaten;
// }
// public double getAvgGhostsEaten() {
// return avgGhostsEaten;
// }
// public double getAvgTimeLasted() {
// return avgTimeLasted;
// }
// public double getAvgLastLevelReached() {
// return avgLastLevelReached;
// }
// public double getAvgScore() {
// return avgScore;
// }
// public void setAvgPillsEaten(double avgPillsEaten) {
// this.avgPillsEaten = avgPillsEaten;
// }
//
// public void setAvgPowerPillsEaten(double avgPowerPillsEaten) {
// this.avgPowerPillsEaten = avgPowerPillsEaten;
// }
//
// public void setAvgGhostsEaten(double avgGhostsEaten) {
// this.avgGhostsEaten = avgGhostsEaten;
// }
//
// public void setAvgTimeLasted(double avgTimeLasted) {
// this.avgTimeLasted = avgTimeLasted;
// }
//
// public void setAvgLastLevelReached(double avgLastLevelReached) {
// this.avgLastLevelReached = avgLastLevelReached;
// }
//
// public void setAvgScore(double avgScore) {
// this.avgScore = avgScore;
// }
//
// public static GameInfo averageGamesInfo(ArrayList<GameInfo> gamesInfo){
// GameInfo giFinal = new GameInfo();
//
// double pillsTotales = 0;
// double powerPillsTotales = 0;
// double ghostsTotales = 0;
// double timeTotal = 0;
// double levelsTotal = 0;
// double scoreTotal = 0;
//
// int numGames = gamesInfo.size();
//
// for(int i = 0; i < numGames; i++){
// pillsTotales += gamesInfo.get(i).getPillsEaten();
// powerPillsTotales += gamesInfo.get(i).getPowerPillsEaten();
// ghostsTotales += gamesInfo.get(i).getGhostsEaten();
// timeTotal += gamesInfo.get(i).getTimeLasted();
// levelsTotal += gamesInfo.get(i).getLastLevelReached();
// scoreTotal += gamesInfo.get(i).getScore();
// }
//
// pillsTotales /= numGames;
// powerPillsTotales /= numGames;
// ghostsTotales /= numGames;
// timeTotal /= numGames;
// levelsTotal /= numGames;
// scoreTotal /= numGames;
//
// giFinal.setAvgPillsEaten(pillsTotales);
// giFinal.setAvgPowerPillsEaten(powerPillsTotales);
// giFinal.setAvgGhostsEaten(ghostsTotales);
// giFinal.setAvgTimeLasted(timeTotal);
// giFinal.setAvgLastLevelReached(levelsTotal);
// giFinal.setAvgScore(scoreTotal);
//
// return giFinal;
// }
//
// }
// Path: src/jeco/core/operator/evaluator/fitness/GhostsEatenFitness.java
import pacman.game.util.GameInfo;
package jeco.core.operator.evaluator.fitness;
public class GhostsEatenFitness implements FitnessEvaluatorInterface {
@Override | public double evaluate(GameInfo gi) { |
hecoding/Pac-Man | src/jeco/core/operator/mutation/NonUniformMutation.java | // Path: src/jeco/core/problem/Problem.java
// public abstract class Problem<V extends Variable<?>> {
// //private static final Logger logger = Logger.getLogger(Problem.class.getName());
//
// public static final double INFINITY = Double.POSITIVE_INFINITY;
// protected int numberOfVariables;
// protected int numberOfObjectives;
// protected double[] lowerBound;
// protected double[] upperBound;
//
// protected int maxEvaluations;
// protected int numEvaluations;
//
// public Problem(int numberOfVariables, int numberOfObjectives) {
// this.numberOfVariables = numberOfVariables;
// this.numberOfObjectives = numberOfObjectives;
// this.lowerBound = new double[numberOfVariables];
// this.upperBound = new double[numberOfVariables];
// this.maxEvaluations = Integer.MAX_VALUE;
// resetNumEvaluations();
// }
//
// public int getNumberOfVariables() {
// return numberOfVariables;
// }
//
// public int getNumberOfObjectives() {
// return numberOfObjectives;
// }
//
// public double getLowerBound(int i) {
// return lowerBound[i];
// }
//
// public double getUpperBound(int i) {
// return upperBound[i];
// }
//
// public int getMaxEvaluations() {
// return maxEvaluations;
// }
//
// public void setMaxEvaluations(int maxEvaluations) {
// this.maxEvaluations = maxEvaluations;
// }
//
// public int getNumEvaluations() {
// return numEvaluations;
// }
//
// public final void resetNumEvaluations() {
// numEvaluations = 0;
// }
//
// public void setNumEvaluations(int numEvaluations) {
// this.numEvaluations = numEvaluations;
// }
//
// public abstract Solutions<V> newRandomSetOfSolutions(int size);
//
// public void evaluate(Solutions<V> solutions) {
// for (Solution<V> solution : solutions) {
// evaluate(solution);
// }
// }
//
// public abstract void evaluate(Solution<V> solution);
//
// @Override
// public abstract Problem<V> clone();
//
// public boolean reachedMaxEvaluations() {
// return (numEvaluations >= maxEvaluations);
// }
// }
//
// Path: src/jeco/core/problem/Variable.java
// public class Variable<T> {
// protected T value;
//
// public Variable(T value) {
// this.value = value;
// }
//
// public T getValue() { return value; }
//
// public void setValue(T value) { this.value = value; }
//
// @Override
// public Variable<T> clone() {
// return new Variable<T>(value);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object right) {
// Variable<T> var = (Variable<T>)right;
// return this.value.equals(var.value);
// }
//
// @Override
// public String toString()
// {
// return value.toString();
// }
// }
| import java.util.ArrayList;
import jeco.core.problem.Problem;
import jeco.core.problem.Solution;
import jeco.core.problem.Variable;
import jeco.core.util.random.RandomGenerator; | package jeco.core.operator.mutation;
//Note: Solutions must be real
public class NonUniformMutation<T extends Variable<Double>> extends MutationOperator<T> {
public static final double DEFAULT_PERTURBATION_INDEX = 0.5; | // Path: src/jeco/core/problem/Problem.java
// public abstract class Problem<V extends Variable<?>> {
// //private static final Logger logger = Logger.getLogger(Problem.class.getName());
//
// public static final double INFINITY = Double.POSITIVE_INFINITY;
// protected int numberOfVariables;
// protected int numberOfObjectives;
// protected double[] lowerBound;
// protected double[] upperBound;
//
// protected int maxEvaluations;
// protected int numEvaluations;
//
// public Problem(int numberOfVariables, int numberOfObjectives) {
// this.numberOfVariables = numberOfVariables;
// this.numberOfObjectives = numberOfObjectives;
// this.lowerBound = new double[numberOfVariables];
// this.upperBound = new double[numberOfVariables];
// this.maxEvaluations = Integer.MAX_VALUE;
// resetNumEvaluations();
// }
//
// public int getNumberOfVariables() {
// return numberOfVariables;
// }
//
// public int getNumberOfObjectives() {
// return numberOfObjectives;
// }
//
// public double getLowerBound(int i) {
// return lowerBound[i];
// }
//
// public double getUpperBound(int i) {
// return upperBound[i];
// }
//
// public int getMaxEvaluations() {
// return maxEvaluations;
// }
//
// public void setMaxEvaluations(int maxEvaluations) {
// this.maxEvaluations = maxEvaluations;
// }
//
// public int getNumEvaluations() {
// return numEvaluations;
// }
//
// public final void resetNumEvaluations() {
// numEvaluations = 0;
// }
//
// public void setNumEvaluations(int numEvaluations) {
// this.numEvaluations = numEvaluations;
// }
//
// public abstract Solutions<V> newRandomSetOfSolutions(int size);
//
// public void evaluate(Solutions<V> solutions) {
// for (Solution<V> solution : solutions) {
// evaluate(solution);
// }
// }
//
// public abstract void evaluate(Solution<V> solution);
//
// @Override
// public abstract Problem<V> clone();
//
// public boolean reachedMaxEvaluations() {
// return (numEvaluations >= maxEvaluations);
// }
// }
//
// Path: src/jeco/core/problem/Variable.java
// public class Variable<T> {
// protected T value;
//
// public Variable(T value) {
// this.value = value;
// }
//
// public T getValue() { return value; }
//
// public void setValue(T value) { this.value = value; }
//
// @Override
// public Variable<T> clone() {
// return new Variable<T>(value);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object right) {
// Variable<T> var = (Variable<T>)right;
// return this.value.equals(var.value);
// }
//
// @Override
// public String toString()
// {
// return value.toString();
// }
// }
// Path: src/jeco/core/operator/mutation/NonUniformMutation.java
import java.util.ArrayList;
import jeco.core.problem.Problem;
import jeco.core.problem.Solution;
import jeco.core.problem.Variable;
import jeco.core.util.random.RandomGenerator;
package jeco.core.operator.mutation;
//Note: Solutions must be real
public class NonUniformMutation<T extends Variable<Double>> extends MutationOperator<T> {
public static final double DEFAULT_PERTURBATION_INDEX = 0.5; | protected Problem<T> problem; |
hecoding/Pac-Man | src/view/gui/swing/factory/GhostControllerFactory.java | // Path: src/pacman/game/Constants.java
// public enum GHOST
// {
// BLINKY(40),
// PINKY(60),
// INKY(80),
// SUE(100);
//
// public final int initialLairTime;
//
// GHOST(int lairTime)
// {
// this.initialLairTime=lairTime;
// }
// };
//
// Path: src/pacman/game/Constants.java
// public enum MOVE
// {
// UP {
// public MOVE opposite() {
// return MOVE.DOWN;
// }
//
// public MOVE R90() {
// return MOVE.RIGHT;
// }
//
// public MOVE L90() {
// return MOVE.LEFT;
// };
// },
// RIGHT {
// public MOVE opposite() {
// return MOVE.LEFT;
// }
//
// public MOVE R90() {
// return MOVE.DOWN;
// }
//
// public MOVE L90() {
// return MOVE.UP;
// };
// },
// DOWN {
// public MOVE opposite() {
// return MOVE.UP;
// }
//
// public MOVE R90() {
// return MOVE.LEFT;
// }
//
// public MOVE L90() {
// return MOVE.RIGHT;
// };
// },
// LEFT {
// public MOVE opposite() {
// return MOVE.RIGHT;
// }
//
// public MOVE R90() {
// return MOVE.UP;
// }
//
// public MOVE L90() {
// return MOVE.DOWN;
// };
// },
// NEUTRAL {
// public MOVE opposite() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE R90() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE L90() {
// return MOVE.NEUTRAL;
// };
// };
//
// public abstract MOVE opposite();
// public abstract MOVE R90();
// public abstract MOVE L90();
// };
| import java.util.EnumMap;
import java.util.HashMap;
import pacman.controllers.Controller;
import pacman.game.Constants.GHOST;
import pacman.game.Constants.MOVE; | package view.gui.swing.factory;
public class GhostControllerFactory {
private static GhostControllerFactory instance; | // Path: src/pacman/game/Constants.java
// public enum GHOST
// {
// BLINKY(40),
// PINKY(60),
// INKY(80),
// SUE(100);
//
// public final int initialLairTime;
//
// GHOST(int lairTime)
// {
// this.initialLairTime=lairTime;
// }
// };
//
// Path: src/pacman/game/Constants.java
// public enum MOVE
// {
// UP {
// public MOVE opposite() {
// return MOVE.DOWN;
// }
//
// public MOVE R90() {
// return MOVE.RIGHT;
// }
//
// public MOVE L90() {
// return MOVE.LEFT;
// };
// },
// RIGHT {
// public MOVE opposite() {
// return MOVE.LEFT;
// }
//
// public MOVE R90() {
// return MOVE.DOWN;
// }
//
// public MOVE L90() {
// return MOVE.UP;
// };
// },
// DOWN {
// public MOVE opposite() {
// return MOVE.UP;
// }
//
// public MOVE R90() {
// return MOVE.LEFT;
// }
//
// public MOVE L90() {
// return MOVE.RIGHT;
// };
// },
// LEFT {
// public MOVE opposite() {
// return MOVE.RIGHT;
// }
//
// public MOVE R90() {
// return MOVE.UP;
// }
//
// public MOVE L90() {
// return MOVE.DOWN;
// };
// },
// NEUTRAL {
// public MOVE opposite() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE R90() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE L90() {
// return MOVE.NEUTRAL;
// };
// };
//
// public abstract MOVE opposite();
// public abstract MOVE R90();
// public abstract MOVE L90();
// };
// Path: src/view/gui/swing/factory/GhostControllerFactory.java
import java.util.EnumMap;
import java.util.HashMap;
import pacman.controllers.Controller;
import pacman.game.Constants.GHOST;
import pacman.game.Constants.MOVE;
package view.gui.swing.factory;
public class GhostControllerFactory {
private static GhostControllerFactory instance; | private HashMap<String, Class<? extends Controller<EnumMap<GHOST,MOVE>>>> registered = new HashMap<>(); |
hecoding/Pac-Man | src/view/gui/swing/factory/GhostControllerFactory.java | // Path: src/pacman/game/Constants.java
// public enum GHOST
// {
// BLINKY(40),
// PINKY(60),
// INKY(80),
// SUE(100);
//
// public final int initialLairTime;
//
// GHOST(int lairTime)
// {
// this.initialLairTime=lairTime;
// }
// };
//
// Path: src/pacman/game/Constants.java
// public enum MOVE
// {
// UP {
// public MOVE opposite() {
// return MOVE.DOWN;
// }
//
// public MOVE R90() {
// return MOVE.RIGHT;
// }
//
// public MOVE L90() {
// return MOVE.LEFT;
// };
// },
// RIGHT {
// public MOVE opposite() {
// return MOVE.LEFT;
// }
//
// public MOVE R90() {
// return MOVE.DOWN;
// }
//
// public MOVE L90() {
// return MOVE.UP;
// };
// },
// DOWN {
// public MOVE opposite() {
// return MOVE.UP;
// }
//
// public MOVE R90() {
// return MOVE.LEFT;
// }
//
// public MOVE L90() {
// return MOVE.RIGHT;
// };
// },
// LEFT {
// public MOVE opposite() {
// return MOVE.RIGHT;
// }
//
// public MOVE R90() {
// return MOVE.UP;
// }
//
// public MOVE L90() {
// return MOVE.DOWN;
// };
// },
// NEUTRAL {
// public MOVE opposite() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE R90() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE L90() {
// return MOVE.NEUTRAL;
// };
// };
//
// public abstract MOVE opposite();
// public abstract MOVE R90();
// public abstract MOVE L90();
// };
| import java.util.EnumMap;
import java.util.HashMap;
import pacman.controllers.Controller;
import pacman.game.Constants.GHOST;
import pacman.game.Constants.MOVE; | package view.gui.swing.factory;
public class GhostControllerFactory {
private static GhostControllerFactory instance; | // Path: src/pacman/game/Constants.java
// public enum GHOST
// {
// BLINKY(40),
// PINKY(60),
// INKY(80),
// SUE(100);
//
// public final int initialLairTime;
//
// GHOST(int lairTime)
// {
// this.initialLairTime=lairTime;
// }
// };
//
// Path: src/pacman/game/Constants.java
// public enum MOVE
// {
// UP {
// public MOVE opposite() {
// return MOVE.DOWN;
// }
//
// public MOVE R90() {
// return MOVE.RIGHT;
// }
//
// public MOVE L90() {
// return MOVE.LEFT;
// };
// },
// RIGHT {
// public MOVE opposite() {
// return MOVE.LEFT;
// }
//
// public MOVE R90() {
// return MOVE.DOWN;
// }
//
// public MOVE L90() {
// return MOVE.UP;
// };
// },
// DOWN {
// public MOVE opposite() {
// return MOVE.UP;
// }
//
// public MOVE R90() {
// return MOVE.LEFT;
// }
//
// public MOVE L90() {
// return MOVE.RIGHT;
// };
// },
// LEFT {
// public MOVE opposite() {
// return MOVE.RIGHT;
// }
//
// public MOVE R90() {
// return MOVE.UP;
// }
//
// public MOVE L90() {
// return MOVE.DOWN;
// };
// },
// NEUTRAL {
// public MOVE opposite() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE R90() {
// return MOVE.NEUTRAL;
// }
//
// public MOVE L90() {
// return MOVE.NEUTRAL;
// };
// };
//
// public abstract MOVE opposite();
// public abstract MOVE R90();
// public abstract MOVE L90();
// };
// Path: src/view/gui/swing/factory/GhostControllerFactory.java
import java.util.EnumMap;
import java.util.HashMap;
import pacman.controllers.Controller;
import pacman.game.Constants.GHOST;
import pacman.game.Constants.MOVE;
package view.gui.swing.factory;
public class GhostControllerFactory {
private static GhostControllerFactory instance; | private HashMap<String, Class<? extends Controller<EnumMap<GHOST,MOVE>>>> registered = new HashMap<>(); |
hecoding/Pac-Man | src/jeco/core/operator/evaluator/fitness/LevelsCompletedFitness.java | // Path: src/pacman/game/util/GameInfo.java
// public class GameInfo {
//
// private int pillsEaten;
// private int powerPillsEaten;
// private int ghostsEaten;
// private int timeLasted;
// private int lastLevelReached;
// private int score;
//
// private double avgPillsEaten;
// private double avgPowerPillsEaten;
// private double avgGhostsEaten;
// private double avgTimeLasted;
// private double avgLastLevelReached;
// private double avgScore;
//
// public GameInfo(){
// pillsEaten = 0;
// powerPillsEaten = 0;
// ghostsEaten = 0;
// timeLasted = 0;
// lastLevelReached = 0;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
//
// public void increasePillsEaten(){
// this.pillsEaten++;
// }
//
// public void increasePowerPillsEaten(){
// this.powerPillsEaten++;
// }
//
// public void increaseGhostsEaten(){
// this.ghostsEaten++;
// }
//
// public int getLastLevelReached() {
// return lastLevelReached;
// }
// public void setLastLevelReached(int lastLevelReached) {
// this.lastLevelReached = lastLevelReached;
// }
// public int getPillsEaten() {
// return pillsEaten;
// }
// public void setPillsEaten(int pillsEaten) {
// this.pillsEaten = pillsEaten;
// }
// public int getPowerPillsEaten() {
// return powerPillsEaten;
// }
// public void setPowerPillsEaten(int powerPillsEaten) {
// this.powerPillsEaten = powerPillsEaten;
// }
// public int getGhostsEaten() {
// return ghostsEaten;
// }
// public void setGhostsEaten(int ghostsEaten) {
// this.ghostsEaten = ghostsEaten;
// }
// public int getTimeLasted() {
// return timeLasted;
// }
// public void setTimeLasted(int timeLasted) {
// this.timeLasted = timeLasted;
// }
// public double getAvgPillsEaten() {
// return avgPillsEaten;
// }
// public double getAvgPowerPillsEaten() {
// return avgPowerPillsEaten;
// }
// public double getAvgGhostsEaten() {
// return avgGhostsEaten;
// }
// public double getAvgTimeLasted() {
// return avgTimeLasted;
// }
// public double getAvgLastLevelReached() {
// return avgLastLevelReached;
// }
// public double getAvgScore() {
// return avgScore;
// }
// public void setAvgPillsEaten(double avgPillsEaten) {
// this.avgPillsEaten = avgPillsEaten;
// }
//
// public void setAvgPowerPillsEaten(double avgPowerPillsEaten) {
// this.avgPowerPillsEaten = avgPowerPillsEaten;
// }
//
// public void setAvgGhostsEaten(double avgGhostsEaten) {
// this.avgGhostsEaten = avgGhostsEaten;
// }
//
// public void setAvgTimeLasted(double avgTimeLasted) {
// this.avgTimeLasted = avgTimeLasted;
// }
//
// public void setAvgLastLevelReached(double avgLastLevelReached) {
// this.avgLastLevelReached = avgLastLevelReached;
// }
//
// public void setAvgScore(double avgScore) {
// this.avgScore = avgScore;
// }
//
// public static GameInfo averageGamesInfo(ArrayList<GameInfo> gamesInfo){
// GameInfo giFinal = new GameInfo();
//
// double pillsTotales = 0;
// double powerPillsTotales = 0;
// double ghostsTotales = 0;
// double timeTotal = 0;
// double levelsTotal = 0;
// double scoreTotal = 0;
//
// int numGames = gamesInfo.size();
//
// for(int i = 0; i < numGames; i++){
// pillsTotales += gamesInfo.get(i).getPillsEaten();
// powerPillsTotales += gamesInfo.get(i).getPowerPillsEaten();
// ghostsTotales += gamesInfo.get(i).getGhostsEaten();
// timeTotal += gamesInfo.get(i).getTimeLasted();
// levelsTotal += gamesInfo.get(i).getLastLevelReached();
// scoreTotal += gamesInfo.get(i).getScore();
// }
//
// pillsTotales /= numGames;
// powerPillsTotales /= numGames;
// ghostsTotales /= numGames;
// timeTotal /= numGames;
// levelsTotal /= numGames;
// scoreTotal /= numGames;
//
// giFinal.setAvgPillsEaten(pillsTotales);
// giFinal.setAvgPowerPillsEaten(powerPillsTotales);
// giFinal.setAvgGhostsEaten(ghostsTotales);
// giFinal.setAvgTimeLasted(timeTotal);
// giFinal.setAvgLastLevelReached(levelsTotal);
// giFinal.setAvgScore(scoreTotal);
//
// return giFinal;
// }
//
// }
| import pacman.game.util.GameInfo; | package jeco.core.operator.evaluator.fitness;
public class LevelsCompletedFitness implements FitnessEvaluatorInterface {
@Override | // Path: src/pacman/game/util/GameInfo.java
// public class GameInfo {
//
// private int pillsEaten;
// private int powerPillsEaten;
// private int ghostsEaten;
// private int timeLasted;
// private int lastLevelReached;
// private int score;
//
// private double avgPillsEaten;
// private double avgPowerPillsEaten;
// private double avgGhostsEaten;
// private double avgTimeLasted;
// private double avgLastLevelReached;
// private double avgScore;
//
// public GameInfo(){
// pillsEaten = 0;
// powerPillsEaten = 0;
// ghostsEaten = 0;
// timeLasted = 0;
// lastLevelReached = 0;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
//
// public void increasePillsEaten(){
// this.pillsEaten++;
// }
//
// public void increasePowerPillsEaten(){
// this.powerPillsEaten++;
// }
//
// public void increaseGhostsEaten(){
// this.ghostsEaten++;
// }
//
// public int getLastLevelReached() {
// return lastLevelReached;
// }
// public void setLastLevelReached(int lastLevelReached) {
// this.lastLevelReached = lastLevelReached;
// }
// public int getPillsEaten() {
// return pillsEaten;
// }
// public void setPillsEaten(int pillsEaten) {
// this.pillsEaten = pillsEaten;
// }
// public int getPowerPillsEaten() {
// return powerPillsEaten;
// }
// public void setPowerPillsEaten(int powerPillsEaten) {
// this.powerPillsEaten = powerPillsEaten;
// }
// public int getGhostsEaten() {
// return ghostsEaten;
// }
// public void setGhostsEaten(int ghostsEaten) {
// this.ghostsEaten = ghostsEaten;
// }
// public int getTimeLasted() {
// return timeLasted;
// }
// public void setTimeLasted(int timeLasted) {
// this.timeLasted = timeLasted;
// }
// public double getAvgPillsEaten() {
// return avgPillsEaten;
// }
// public double getAvgPowerPillsEaten() {
// return avgPowerPillsEaten;
// }
// public double getAvgGhostsEaten() {
// return avgGhostsEaten;
// }
// public double getAvgTimeLasted() {
// return avgTimeLasted;
// }
// public double getAvgLastLevelReached() {
// return avgLastLevelReached;
// }
// public double getAvgScore() {
// return avgScore;
// }
// public void setAvgPillsEaten(double avgPillsEaten) {
// this.avgPillsEaten = avgPillsEaten;
// }
//
// public void setAvgPowerPillsEaten(double avgPowerPillsEaten) {
// this.avgPowerPillsEaten = avgPowerPillsEaten;
// }
//
// public void setAvgGhostsEaten(double avgGhostsEaten) {
// this.avgGhostsEaten = avgGhostsEaten;
// }
//
// public void setAvgTimeLasted(double avgTimeLasted) {
// this.avgTimeLasted = avgTimeLasted;
// }
//
// public void setAvgLastLevelReached(double avgLastLevelReached) {
// this.avgLastLevelReached = avgLastLevelReached;
// }
//
// public void setAvgScore(double avgScore) {
// this.avgScore = avgScore;
// }
//
// public static GameInfo averageGamesInfo(ArrayList<GameInfo> gamesInfo){
// GameInfo giFinal = new GameInfo();
//
// double pillsTotales = 0;
// double powerPillsTotales = 0;
// double ghostsTotales = 0;
// double timeTotal = 0;
// double levelsTotal = 0;
// double scoreTotal = 0;
//
// int numGames = gamesInfo.size();
//
// for(int i = 0; i < numGames; i++){
// pillsTotales += gamesInfo.get(i).getPillsEaten();
// powerPillsTotales += gamesInfo.get(i).getPowerPillsEaten();
// ghostsTotales += gamesInfo.get(i).getGhostsEaten();
// timeTotal += gamesInfo.get(i).getTimeLasted();
// levelsTotal += gamesInfo.get(i).getLastLevelReached();
// scoreTotal += gamesInfo.get(i).getScore();
// }
//
// pillsTotales /= numGames;
// powerPillsTotales /= numGames;
// ghostsTotales /= numGames;
// timeTotal /= numGames;
// levelsTotal /= numGames;
// scoreTotal /= numGames;
//
// giFinal.setAvgPillsEaten(pillsTotales);
// giFinal.setAvgPowerPillsEaten(powerPillsTotales);
// giFinal.setAvgGhostsEaten(ghostsTotales);
// giFinal.setAvgTimeLasted(timeTotal);
// giFinal.setAvgLastLevelReached(levelsTotal);
// giFinal.setAvgScore(scoreTotal);
//
// return giFinal;
// }
//
// }
// Path: src/jeco/core/operator/evaluator/fitness/LevelsCompletedFitness.java
import pacman.game.util.GameInfo;
package jeco.core.operator.evaluator.fitness;
public class LevelsCompletedFitness implements FitnessEvaluatorInterface {
@Override | public double evaluate(GameInfo gi) { |
hecoding/Pac-Man | src/jeco/core/operator/mutation/PolynomialMutation.java | // Path: src/jeco/core/problem/Problem.java
// public abstract class Problem<V extends Variable<?>> {
// //private static final Logger logger = Logger.getLogger(Problem.class.getName());
//
// public static final double INFINITY = Double.POSITIVE_INFINITY;
// protected int numberOfVariables;
// protected int numberOfObjectives;
// protected double[] lowerBound;
// protected double[] upperBound;
//
// protected int maxEvaluations;
// protected int numEvaluations;
//
// public Problem(int numberOfVariables, int numberOfObjectives) {
// this.numberOfVariables = numberOfVariables;
// this.numberOfObjectives = numberOfObjectives;
// this.lowerBound = new double[numberOfVariables];
// this.upperBound = new double[numberOfVariables];
// this.maxEvaluations = Integer.MAX_VALUE;
// resetNumEvaluations();
// }
//
// public int getNumberOfVariables() {
// return numberOfVariables;
// }
//
// public int getNumberOfObjectives() {
// return numberOfObjectives;
// }
//
// public double getLowerBound(int i) {
// return lowerBound[i];
// }
//
// public double getUpperBound(int i) {
// return upperBound[i];
// }
//
// public int getMaxEvaluations() {
// return maxEvaluations;
// }
//
// public void setMaxEvaluations(int maxEvaluations) {
// this.maxEvaluations = maxEvaluations;
// }
//
// public int getNumEvaluations() {
// return numEvaluations;
// }
//
// public final void resetNumEvaluations() {
// numEvaluations = 0;
// }
//
// public void setNumEvaluations(int numEvaluations) {
// this.numEvaluations = numEvaluations;
// }
//
// public abstract Solutions<V> newRandomSetOfSolutions(int size);
//
// public void evaluate(Solutions<V> solutions) {
// for (Solution<V> solution : solutions) {
// evaluate(solution);
// }
// }
//
// public abstract void evaluate(Solution<V> solution);
//
// @Override
// public abstract Problem<V> clone();
//
// public boolean reachedMaxEvaluations() {
// return (numEvaluations >= maxEvaluations);
// }
// }
//
// Path: src/jeco/core/problem/Variable.java
// public class Variable<T> {
// protected T value;
//
// public Variable(T value) {
// this.value = value;
// }
//
// public T getValue() { return value; }
//
// public void setValue(T value) { this.value = value; }
//
// @Override
// public Variable<T> clone() {
// return new Variable<T>(value);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object right) {
// Variable<T> var = (Variable<T>)right;
// return this.value.equals(var.value);
// }
//
// @Override
// public String toString()
// {
// return value.toString();
// }
// }
| import java.util.ArrayList;
import jeco.core.problem.Problem;
import jeco.core.problem.Solution;
import jeco.core.problem.Variable;
import jeco.core.util.random.RandomGenerator; | package jeco.core.operator.mutation;
public class PolynomialMutation<T extends Variable<Double>> extends MutationOperator<T> {
/**
* DEFAULT_INDEX_MUTATION defines a default index for mutation
*/
public static final double DEFAULT_ETA_M = 20.0; | // Path: src/jeco/core/problem/Problem.java
// public abstract class Problem<V extends Variable<?>> {
// //private static final Logger logger = Logger.getLogger(Problem.class.getName());
//
// public static final double INFINITY = Double.POSITIVE_INFINITY;
// protected int numberOfVariables;
// protected int numberOfObjectives;
// protected double[] lowerBound;
// protected double[] upperBound;
//
// protected int maxEvaluations;
// protected int numEvaluations;
//
// public Problem(int numberOfVariables, int numberOfObjectives) {
// this.numberOfVariables = numberOfVariables;
// this.numberOfObjectives = numberOfObjectives;
// this.lowerBound = new double[numberOfVariables];
// this.upperBound = new double[numberOfVariables];
// this.maxEvaluations = Integer.MAX_VALUE;
// resetNumEvaluations();
// }
//
// public int getNumberOfVariables() {
// return numberOfVariables;
// }
//
// public int getNumberOfObjectives() {
// return numberOfObjectives;
// }
//
// public double getLowerBound(int i) {
// return lowerBound[i];
// }
//
// public double getUpperBound(int i) {
// return upperBound[i];
// }
//
// public int getMaxEvaluations() {
// return maxEvaluations;
// }
//
// public void setMaxEvaluations(int maxEvaluations) {
// this.maxEvaluations = maxEvaluations;
// }
//
// public int getNumEvaluations() {
// return numEvaluations;
// }
//
// public final void resetNumEvaluations() {
// numEvaluations = 0;
// }
//
// public void setNumEvaluations(int numEvaluations) {
// this.numEvaluations = numEvaluations;
// }
//
// public abstract Solutions<V> newRandomSetOfSolutions(int size);
//
// public void evaluate(Solutions<V> solutions) {
// for (Solution<V> solution : solutions) {
// evaluate(solution);
// }
// }
//
// public abstract void evaluate(Solution<V> solution);
//
// @Override
// public abstract Problem<V> clone();
//
// public boolean reachedMaxEvaluations() {
// return (numEvaluations >= maxEvaluations);
// }
// }
//
// Path: src/jeco/core/problem/Variable.java
// public class Variable<T> {
// protected T value;
//
// public Variable(T value) {
// this.value = value;
// }
//
// public T getValue() { return value; }
//
// public void setValue(T value) { this.value = value; }
//
// @Override
// public Variable<T> clone() {
// return new Variable<T>(value);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object right) {
// Variable<T> var = (Variable<T>)right;
// return this.value.equals(var.value);
// }
//
// @Override
// public String toString()
// {
// return value.toString();
// }
// }
// Path: src/jeco/core/operator/mutation/PolynomialMutation.java
import java.util.ArrayList;
import jeco.core.problem.Problem;
import jeco.core.problem.Solution;
import jeco.core.problem.Variable;
import jeco.core.util.random.RandomGenerator;
package jeco.core.operator.mutation;
public class PolynomialMutation<T extends Variable<Double>> extends MutationOperator<T> {
/**
* DEFAULT_INDEX_MUTATION defines a default index for mutation
*/
public static final double DEFAULT_ETA_M = 20.0; | protected Problem<T> problem; |
hecoding/Pac-Man | src/util/externallogger/ExtLogger.java | // Path: src/util/GitConn.java
// public class GitConn {
//
// private Repository repository;
// private Git git;
// private boolean established;
//
// public GitConn(){
//
// repository = null;
// git = null;
// established = true;
//
// try {
// git = Git.open( new File( "./.git" ) );
// } catch (IOException e2) {
// established = false;
// System.err.println("EXTLOGGER: No se ha podido establecer conexión con git. Logging sin commit hash.");
// }
//
// if(established)
// repository = git.getRepository();
// }
//
// public boolean isConnected(){
// return established;
// }
//
//
// public String getLastCommitHash(){
// String hashy = null;
// try {
// ObjectId id = repository.resolve(Constants.HEAD);
// hashy = id.getName();
// } catch (IOException e) {
// established = false;
// System.err.println("EXTLOGGER: No se ha podido obtener el hash del último commit.");
// }
//
// return hashy;
// }
//
// }
| import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.io.OutputStreamWriter;
import util.GitConn; | package util.externallogger;
/*
* Process Log objects and extracts some metrics as CSV format
*/
public class ExtLogger {
private static BufferedWriter writer; | // Path: src/util/GitConn.java
// public class GitConn {
//
// private Repository repository;
// private Git git;
// private boolean established;
//
// public GitConn(){
//
// repository = null;
// git = null;
// established = true;
//
// try {
// git = Git.open( new File( "./.git" ) );
// } catch (IOException e2) {
// established = false;
// System.err.println("EXTLOGGER: No se ha podido establecer conexión con git. Logging sin commit hash.");
// }
//
// if(established)
// repository = git.getRepository();
// }
//
// public boolean isConnected(){
// return established;
// }
//
//
// public String getLastCommitHash(){
// String hashy = null;
// try {
// ObjectId id = repository.resolve(Constants.HEAD);
// hashy = id.getName();
// } catch (IOException e) {
// established = false;
// System.err.println("EXTLOGGER: No se ha podido obtener el hash del último commit.");
// }
//
// return hashy;
// }
//
// }
// Path: src/util/externallogger/ExtLogger.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.io.OutputStreamWriter;
import util.GitConn;
package util.externallogger;
/*
* Process Log objects and extracts some metrics as CSV format
*/
public class ExtLogger {
private static BufferedWriter writer; | private GitConn gitc; |
hecoding/Pac-Man | src/main/Main.java | // Path: src/view/gui/swing/GUIView.java
// public class GUIView extends JFrame {
// private static final long serialVersionUID = 1L;
// final static int ticks = 19;
// private static GeneralController gCtrl;
// private static GUIController guiCtrl;
// private CenterPanel centerPanel;
// private SettingsPanel settingsPanel;
// private StatusBarPanel status;
//
// public GUIView() {
//
// this.setTitle("Pac-Man");
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
// initGUI();
// }
// });
// }
//
// private void initGUI() {
// gCtrl = new GeneralController();
// guiCtrl = new GUIController();
// this.status = new StatusBarPanel(gCtrl);
// this.centerPanel = new CenterPanel(gCtrl);
// this.settingsPanel = new SettingsPanel(guiCtrl, gCtrl);
//
// guiCtrl.setStatusBarPanel(this.status);
// guiCtrl.setCenterPanel(this.centerPanel);
// guiCtrl.setSettingsPanel(this.settingsPanel);
//
// try {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (UnsupportedLookAndFeelException e) {
// e.printStackTrace();
// }
//
// JPanel mainPanel = new JPanel(new BorderLayout());
//
// mainPanel.add(centerPanel, BorderLayout.CENTER);
// mainPanel.add(settingsPanel, BorderLayout.LINE_START);
// this.add(mainPanel);
//
// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// this.setSize(new Dimension(1268,845));
// this.setMinimumSize(new Dimension(750, 550));
// this.setLocationRelativeTo(null); // center on the screen (doesn't show nice with multiple monitors)
// this.setVisible(true);
// }
//
// }
| import view.gui.swing.GUIView; | package main;
public class Main {
public static void main(String[] args) {
// la GUI
@SuppressWarnings("unused")
//CLIView view = new CLIView(); | // Path: src/view/gui/swing/GUIView.java
// public class GUIView extends JFrame {
// private static final long serialVersionUID = 1L;
// final static int ticks = 19;
// private static GeneralController gCtrl;
// private static GUIController guiCtrl;
// private CenterPanel centerPanel;
// private SettingsPanel settingsPanel;
// private StatusBarPanel status;
//
// public GUIView() {
//
// this.setTitle("Pac-Man");
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
// initGUI();
// }
// });
// }
//
// private void initGUI() {
// gCtrl = new GeneralController();
// guiCtrl = new GUIController();
// this.status = new StatusBarPanel(gCtrl);
// this.centerPanel = new CenterPanel(gCtrl);
// this.settingsPanel = new SettingsPanel(guiCtrl, gCtrl);
//
// guiCtrl.setStatusBarPanel(this.status);
// guiCtrl.setCenterPanel(this.centerPanel);
// guiCtrl.setSettingsPanel(this.settingsPanel);
//
// try {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (UnsupportedLookAndFeelException e) {
// e.printStackTrace();
// }
//
// JPanel mainPanel = new JPanel(new BorderLayout());
//
// mainPanel.add(centerPanel, BorderLayout.CENTER);
// mainPanel.add(settingsPanel, BorderLayout.LINE_START);
// this.add(mainPanel);
//
// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// this.setSize(new Dimension(1268,845));
// this.setMinimumSize(new Dimension(750, 550));
// this.setLocationRelativeTo(null); // center on the screen (doesn't show nice with multiple monitors)
// this.setVisible(true);
// }
//
// }
// Path: src/main/Main.java
import view.gui.swing.GUIView;
package main;
public class Main {
public static void main(String[] args) {
// la GUI
@SuppressWarnings("unused")
//CLIView view = new CLIView(); | GUIView view = new GUIView(); |
hecoding/Pac-Man | src/jeco/core/operator/mutation/NeutralMutation.java | // Path: src/jeco/core/problem/Problem.java
// public abstract class Problem<V extends Variable<?>> {
// //private static final Logger logger = Logger.getLogger(Problem.class.getName());
//
// public static final double INFINITY = Double.POSITIVE_INFINITY;
// protected int numberOfVariables;
// protected int numberOfObjectives;
// protected double[] lowerBound;
// protected double[] upperBound;
//
// protected int maxEvaluations;
// protected int numEvaluations;
//
// public Problem(int numberOfVariables, int numberOfObjectives) {
// this.numberOfVariables = numberOfVariables;
// this.numberOfObjectives = numberOfObjectives;
// this.lowerBound = new double[numberOfVariables];
// this.upperBound = new double[numberOfVariables];
// this.maxEvaluations = Integer.MAX_VALUE;
// resetNumEvaluations();
// }
//
// public int getNumberOfVariables() {
// return numberOfVariables;
// }
//
// public int getNumberOfObjectives() {
// return numberOfObjectives;
// }
//
// public double getLowerBound(int i) {
// return lowerBound[i];
// }
//
// public double getUpperBound(int i) {
// return upperBound[i];
// }
//
// public int getMaxEvaluations() {
// return maxEvaluations;
// }
//
// public void setMaxEvaluations(int maxEvaluations) {
// this.maxEvaluations = maxEvaluations;
// }
//
// public int getNumEvaluations() {
// return numEvaluations;
// }
//
// public final void resetNumEvaluations() {
// numEvaluations = 0;
// }
//
// public void setNumEvaluations(int numEvaluations) {
// this.numEvaluations = numEvaluations;
// }
//
// public abstract Solutions<V> newRandomSetOfSolutions(int size);
//
// public void evaluate(Solutions<V> solutions) {
// for (Solution<V> solution : solutions) {
// evaluate(solution);
// }
// }
//
// public abstract void evaluate(Solution<V> solution);
//
// @Override
// public abstract Problem<V> clone();
//
// public boolean reachedMaxEvaluations() {
// return (numEvaluations >= maxEvaluations);
// }
// }
//
// Path: src/jeco/core/problem/Variable.java
// public class Variable<T> {
// protected T value;
//
// public Variable(T value) {
// this.value = value;
// }
//
// public T getValue() { return value; }
//
// public void setValue(T value) { this.value = value; }
//
// @Override
// public Variable<T> clone() {
// return new Variable<T>(value);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object right) {
// Variable<T> var = (Variable<T>)right;
// return this.value.equals(var.value);
// }
//
// @Override
// public String toString()
// {
// return value.toString();
// }
// }
//
// Path: src/jeco/core/problem/solution/NeutralMutationSolution.java
// public class NeutralMutationSolution extends Solution<Variable<Integer>> {
// protected ArrayList<Integer> noOptionsPhenotype = new ArrayList<Integer>();
//
// public NeutralMutationSolution(int numberOfObjectives) {
// super(numberOfObjectives);
// }
//
// public ArrayList<Integer> getNoOptionsPhenotype() {
// return noOptionsPhenotype;
// }
//
// public void setNoOptionsPhenotype(ArrayList<Integer> noOptionsPhenotype) {
// this.noOptionsPhenotype = noOptionsPhenotype;
// }
//
// @Override
// public NeutralMutationSolution clone() {
// NeutralMutationSolution clone = new NeutralMutationSolution(objectives.size());
// for (int i = 0; i < objectives.size(); ++i) {
// clone.objectives.set(i, objectives.get(i));
// }
// for (int i = 0; i < variables.size(); ++i) {
// clone.variables.add(variables.get(i).clone());
// }
//
// for (Map.Entry<String, Number> entry : properties.entrySet()) {
// clone.properties.put(entry.getKey(), entry.getValue());
// }
//
// for (int i = 0; i < noOptionsPhenotype.size(); ++i) {
// clone.noOptionsPhenotype.add(noOptionsPhenotype.get(i).intValue()); // clone doesn't work
// }
//
// return clone;
// }
//
// // noOptionsPhenotype is dependent of variables array, thus no equals method modification is needed
// }
| import jeco.core.problem.Problem;
import jeco.core.problem.Solution;
import jeco.core.problem.Variable;
import jeco.core.problem.solution.NeutralMutationSolution;
import jeco.core.util.random.RandomGenerator; | package jeco.core.operator.mutation;
public class NeutralMutation<T extends Variable<Integer>> extends MutationOperator<T> {
protected Problem<T> problem;
public NeutralMutation(Problem<T> problem, double probability) {
super(probability);
this.problem = problem;
}
public Solution<T> execute(Solution<T> solution) { | // Path: src/jeco/core/problem/Problem.java
// public abstract class Problem<V extends Variable<?>> {
// //private static final Logger logger = Logger.getLogger(Problem.class.getName());
//
// public static final double INFINITY = Double.POSITIVE_INFINITY;
// protected int numberOfVariables;
// protected int numberOfObjectives;
// protected double[] lowerBound;
// protected double[] upperBound;
//
// protected int maxEvaluations;
// protected int numEvaluations;
//
// public Problem(int numberOfVariables, int numberOfObjectives) {
// this.numberOfVariables = numberOfVariables;
// this.numberOfObjectives = numberOfObjectives;
// this.lowerBound = new double[numberOfVariables];
// this.upperBound = new double[numberOfVariables];
// this.maxEvaluations = Integer.MAX_VALUE;
// resetNumEvaluations();
// }
//
// public int getNumberOfVariables() {
// return numberOfVariables;
// }
//
// public int getNumberOfObjectives() {
// return numberOfObjectives;
// }
//
// public double getLowerBound(int i) {
// return lowerBound[i];
// }
//
// public double getUpperBound(int i) {
// return upperBound[i];
// }
//
// public int getMaxEvaluations() {
// return maxEvaluations;
// }
//
// public void setMaxEvaluations(int maxEvaluations) {
// this.maxEvaluations = maxEvaluations;
// }
//
// public int getNumEvaluations() {
// return numEvaluations;
// }
//
// public final void resetNumEvaluations() {
// numEvaluations = 0;
// }
//
// public void setNumEvaluations(int numEvaluations) {
// this.numEvaluations = numEvaluations;
// }
//
// public abstract Solutions<V> newRandomSetOfSolutions(int size);
//
// public void evaluate(Solutions<V> solutions) {
// for (Solution<V> solution : solutions) {
// evaluate(solution);
// }
// }
//
// public abstract void evaluate(Solution<V> solution);
//
// @Override
// public abstract Problem<V> clone();
//
// public boolean reachedMaxEvaluations() {
// return (numEvaluations >= maxEvaluations);
// }
// }
//
// Path: src/jeco/core/problem/Variable.java
// public class Variable<T> {
// protected T value;
//
// public Variable(T value) {
// this.value = value;
// }
//
// public T getValue() { return value; }
//
// public void setValue(T value) { this.value = value; }
//
// @Override
// public Variable<T> clone() {
// return new Variable<T>(value);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object right) {
// Variable<T> var = (Variable<T>)right;
// return this.value.equals(var.value);
// }
//
// @Override
// public String toString()
// {
// return value.toString();
// }
// }
//
// Path: src/jeco/core/problem/solution/NeutralMutationSolution.java
// public class NeutralMutationSolution extends Solution<Variable<Integer>> {
// protected ArrayList<Integer> noOptionsPhenotype = new ArrayList<Integer>();
//
// public NeutralMutationSolution(int numberOfObjectives) {
// super(numberOfObjectives);
// }
//
// public ArrayList<Integer> getNoOptionsPhenotype() {
// return noOptionsPhenotype;
// }
//
// public void setNoOptionsPhenotype(ArrayList<Integer> noOptionsPhenotype) {
// this.noOptionsPhenotype = noOptionsPhenotype;
// }
//
// @Override
// public NeutralMutationSolution clone() {
// NeutralMutationSolution clone = new NeutralMutationSolution(objectives.size());
// for (int i = 0; i < objectives.size(); ++i) {
// clone.objectives.set(i, objectives.get(i));
// }
// for (int i = 0; i < variables.size(); ++i) {
// clone.variables.add(variables.get(i).clone());
// }
//
// for (Map.Entry<String, Number> entry : properties.entrySet()) {
// clone.properties.put(entry.getKey(), entry.getValue());
// }
//
// for (int i = 0; i < noOptionsPhenotype.size(); ++i) {
// clone.noOptionsPhenotype.add(noOptionsPhenotype.get(i).intValue()); // clone doesn't work
// }
//
// return clone;
// }
//
// // noOptionsPhenotype is dependent of variables array, thus no equals method modification is needed
// }
// Path: src/jeco/core/operator/mutation/NeutralMutation.java
import jeco.core.problem.Problem;
import jeco.core.problem.Solution;
import jeco.core.problem.Variable;
import jeco.core.problem.solution.NeutralMutationSolution;
import jeco.core.util.random.RandomGenerator;
package jeco.core.operator.mutation;
public class NeutralMutation<T extends Variable<Integer>> extends MutationOperator<T> {
protected Problem<T> problem;
public NeutralMutation(Problem<T> problem, double probability) {
super(probability);
this.problem = problem;
}
public Solution<T> execute(Solution<T> solution) { | NeutralMutationSolution nmSolution = (NeutralMutationSolution) solution; |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/index/ConfigEntityTypeAnnotationIndex.java | // Path: src/de/espend/idea/php/drupal/utils/IndexUtil.java
// public class IndexUtil {
//
// @NotNull
// public static Collection<PhpClass> getFormClassForId(@NotNull Project project, @NotNull String id) {
// Collection<PhpClass> phpClasses = new ArrayList<>();
//
// for (String key : SymfonyProcessors.createResult(project, ConfigEntityTypeAnnotationIndex.KEY)) {
// if(!id.equals(key)) {
// continue;
// }
//
// for (String value : FileBasedIndex.getInstance().getValues(ConfigEntityTypeAnnotationIndex.KEY, key, GlobalSearchScope.allScope(project))) {
// phpClasses.addAll(PhpElementsUtil.getClassesInterface(project, value));
// }
// }
//
// return phpClasses;
// }
//
// @NotNull
// public static Collection<PsiElement> getMenuForId(@NotNull Project project, @NotNull String text) {
// Collection<VirtualFile> virtualFiles = new ArrayList<>();
//
// FileBasedIndex.getInstance().getFilesWithKey(MenuIndex.KEY, new HashSet<>(Collections.singletonList(text)), virtualFile -> {
// virtualFiles.add(virtualFile);
// return true;
// }, GlobalSearchScope.allScope(project));
//
// Collection<PsiElement> targets = new ArrayList<>();
//
// for (VirtualFile virtualFile : virtualFiles) {
// PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
// if(!(file instanceof YAMLFile)) {
// continue;
// }
//
// ContainerUtil.addIfNotNull(targets, YAMLUtil.getQualifiedKeyInFile((YAMLFile) file, text));
// }
//
// return targets;
// }
//
// @NotNull
// public static Collection<LookupElement> getIndexedKeyLookup(@NotNull Project project, @NotNull ID<String, ?> var1) {
// Collection<LookupElement> lookupElements = new ArrayList<>();
//
// lookupElements.addAll(SymfonyProcessors.createResult(project, var1).stream().map(
// s -> LookupElementBuilder.create(s).withIcon(DrupalIcons.DRUPAL)).collect(Collectors.toList())
// );
//
// return lookupElements;
// }
//
// public static boolean isValidForIndex(@NotNull FileContent inputData, @NotNull PsiFile psiFile) {
//
// String fileName = psiFile.getName();
// if(fileName.startsWith(".") || fileName.endsWith("Test")) {
// return false;
// }
//
// VirtualFile baseDir = inputData.getProject().getBaseDir();
// if(baseDir == null) {
// return false;
// }
//
// // is Test file in path name
// String relativePath = VfsUtil.getRelativePath(inputData.getFile(), baseDir, '/');
// if(relativePath != null && (relativePath.contains("/Test/") || relativePath.contains("/Fixtures/"))) {
// return false;
// }
//
// return true;
// }
// }
| import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiRecursiveElementVisitor;
import com.intellij.util.indexing.*;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.EnumeratorStringDescriptor;
import com.intellij.util.io.KeyDescriptor;
import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;
import com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag;
import com.jetbrains.php.lang.psi.PhpFile;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import com.jetbrains.php.lang.psi.elements.PhpPsiElement;
import com.jetbrains.php.lang.psi.stubs.indexes.PhpConstantNameIndex;
import de.espend.idea.php.drupal.utils.IndexUtil;
import gnu.trove.THashMap;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package de.espend.idea.php.drupal.index;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class ConfigEntityTypeAnnotationIndex extends FileBasedIndexExtension<String, String> {
public static final ID<String, String> KEY = ID.create("de.espend.idea.php.drupal.config_entity_type_annotation");
private final KeyDescriptor<String> myKeyDescriptor = new EnumeratorStringDescriptor();
@NotNull
@Override
public DataIndexer<String, String, FileContent> getIndexer() {
return inputData -> {
final Map<String, String> map = new THashMap<>();
PsiFile psiFile = inputData.getPsiFile();
if(!(psiFile instanceof PhpFile)) {
return map;
}
| // Path: src/de/espend/idea/php/drupal/utils/IndexUtil.java
// public class IndexUtil {
//
// @NotNull
// public static Collection<PhpClass> getFormClassForId(@NotNull Project project, @NotNull String id) {
// Collection<PhpClass> phpClasses = new ArrayList<>();
//
// for (String key : SymfonyProcessors.createResult(project, ConfigEntityTypeAnnotationIndex.KEY)) {
// if(!id.equals(key)) {
// continue;
// }
//
// for (String value : FileBasedIndex.getInstance().getValues(ConfigEntityTypeAnnotationIndex.KEY, key, GlobalSearchScope.allScope(project))) {
// phpClasses.addAll(PhpElementsUtil.getClassesInterface(project, value));
// }
// }
//
// return phpClasses;
// }
//
// @NotNull
// public static Collection<PsiElement> getMenuForId(@NotNull Project project, @NotNull String text) {
// Collection<VirtualFile> virtualFiles = new ArrayList<>();
//
// FileBasedIndex.getInstance().getFilesWithKey(MenuIndex.KEY, new HashSet<>(Collections.singletonList(text)), virtualFile -> {
// virtualFiles.add(virtualFile);
// return true;
// }, GlobalSearchScope.allScope(project));
//
// Collection<PsiElement> targets = new ArrayList<>();
//
// for (VirtualFile virtualFile : virtualFiles) {
// PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
// if(!(file instanceof YAMLFile)) {
// continue;
// }
//
// ContainerUtil.addIfNotNull(targets, YAMLUtil.getQualifiedKeyInFile((YAMLFile) file, text));
// }
//
// return targets;
// }
//
// @NotNull
// public static Collection<LookupElement> getIndexedKeyLookup(@NotNull Project project, @NotNull ID<String, ?> var1) {
// Collection<LookupElement> lookupElements = new ArrayList<>();
//
// lookupElements.addAll(SymfonyProcessors.createResult(project, var1).stream().map(
// s -> LookupElementBuilder.create(s).withIcon(DrupalIcons.DRUPAL)).collect(Collectors.toList())
// );
//
// return lookupElements;
// }
//
// public static boolean isValidForIndex(@NotNull FileContent inputData, @NotNull PsiFile psiFile) {
//
// String fileName = psiFile.getName();
// if(fileName.startsWith(".") || fileName.endsWith("Test")) {
// return false;
// }
//
// VirtualFile baseDir = inputData.getProject().getBaseDir();
// if(baseDir == null) {
// return false;
// }
//
// // is Test file in path name
// String relativePath = VfsUtil.getRelativePath(inputData.getFile(), baseDir, '/');
// if(relativePath != null && (relativePath.contains("/Test/") || relativePath.contains("/Fixtures/"))) {
// return false;
// }
//
// return true;
// }
// }
// Path: src/de/espend/idea/php/drupal/index/ConfigEntityTypeAnnotationIndex.java
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiRecursiveElementVisitor;
import com.intellij.util.indexing.*;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.EnumeratorStringDescriptor;
import com.intellij.util.io.KeyDescriptor;
import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;
import com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag;
import com.jetbrains.php.lang.psi.PhpFile;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import com.jetbrains.php.lang.psi.elements.PhpPsiElement;
import com.jetbrains.php.lang.psi.stubs.indexes.PhpConstantNameIndex;
import de.espend.idea.php.drupal.utils.IndexUtil;
import gnu.trove.THashMap;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package de.espend.idea.php.drupal.index;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class ConfigEntityTypeAnnotationIndex extends FileBasedIndexExtension<String, String> {
public static final ID<String, String> KEY = ID.create("de.espend.idea.php.drupal.config_entity_type_annotation");
private final KeyDescriptor<String> myKeyDescriptor = new EnumeratorStringDescriptor();
@NotNull
@Override
public DataIndexer<String, String, FileContent> getIndexer() {
return inputData -> {
final Map<String, String> map = new THashMap<>();
PsiFile psiFile = inputData.getPsiFile();
if(!(psiFile instanceof PhpFile)) {
return map;
}
| if(!IndexUtil.isValidForIndex(inputData, psiFile)) { |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/config/ConfigCompletionGoto.java | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/index/ConfigSchemaIndex.java
// public class ConfigSchemaIndex extends FileBasedIndexExtension<String, Set<String>> {
//
// public static final ID<String, Set<String>> KEY = ID.create("de.espend.idea.php.drupal.config_schema");
// private static final StringSetDataExternalizer EXTERNALIZER = new StringSetDataExternalizer();
// private final KeyDescriptor<String> myKeyDescriptor = new EnumeratorStringDescriptor();
//
// @NotNull
// @Override
// public ID<String, Set<String>> getName() {
// return KEY;
// }
//
// @NotNull
// @Override
// public DataIndexer<String, Set<String>, FileContent> getIndexer() {
// return inputData -> {
// Map<String, Set<String>> map = new THashMap<>();
//
// PsiFile psiFile = inputData.getPsiFile();
// if(!Symfony2ProjectComponent.isEnabledForIndex(psiFile.getProject())) {
// return map;
// }
//
// if(!(psiFile instanceof YAMLFile) || !isValidForIndex(psiFile)) {
// return map;
// }
//
// for(YAMLKeyValue yamlKeyValue: YamlHelper.getTopLevelKeyValues((YAMLFile) psiFile)) {
// String key = PsiElementUtils.trimQuote(yamlKeyValue.getKeyText());
//
// if(StringUtils.isBlank(key) || key.contains("*")) {
// continue;
// }
//
// Set<String> mappings = new HashSet<>();
// YAMLKeyValue mapping = YamlHelper.getYamlKeyValue(yamlKeyValue, "mapping");
// if(mapping == null) {
// continue;
// }
//
// Set<String> keySet = YamlHelper.getKeySet(mapping);
// if(keySet != null) {
// mappings.addAll(keySet);
// }
//
// map.put(key, mappings);
// }
//
// return map;
// };
//
// }
//
// @NotNull
// @Override
// public KeyDescriptor<String> getKeyDescriptor() {
// return this.myKeyDescriptor;
// }
//
// @NotNull
// @Override
// public DataExternalizer<Set<String>> getValueExternalizer() {
// return EXTERNALIZER;
// }
//
// @NotNull
// @Override
// public FileBasedIndex.InputFilter getInputFilter() {
// return file ->
// file.getFileType() == YAMLFileType.YML || file.getFileType() == XmlFileType.INSTANCE;
// }
//
// @Override
// public boolean dependsOnFileContent() {
// return true;
// }
//
// @Override
// public int getVersion() {
// return 2;
// }
//
// private static boolean isValidForIndex(@NotNull PsiFile psiFile) {
//
// String fileName = psiFile.getName();
//
// return !(fileName.startsWith(".") || !fileName.endsWith(".schema.yml"));
// }
// }
| import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.indexing.FileBasedIndex;
import com.jetbrains.php.lang.PhpLanguage;
import com.jetbrains.php.lang.psi.elements.StringLiteralExpression;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.index.ConfigSchemaIndex;
import fr.adrienbrault.idea.symfony2plugin.Symfony2Icons;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionProvider;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrar;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrarParameter;
import fr.adrienbrault.idea.symfony2plugin.stubs.SymfonyProcessors;
import fr.adrienbrault.idea.symfony2plugin.util.MethodMatcher;
import fr.adrienbrault.idea.symfony2plugin.util.PsiElementUtils;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.yaml.YAMLFileType;
import org.jetbrains.yaml.psi.YAMLDocument;
import org.jetbrains.yaml.psi.YAMLKeyValue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet; | package de.espend.idea.php.drupal.config;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class ConfigCompletionGoto implements GotoCompletionRegistrar {
final private static MethodMatcher.CallToSignature[] CONFIG = new MethodMatcher.CallToSignature[] {
new MethodMatcher.CallToSignature("\\Drupal\\Core\\Config\\ConfigFactory", "get"),
};
@Override
public void register(GotoCompletionRegistrarParameter registrar) {
registrar.register(PlatformPatterns.psiElement().withParent(StringLiteralExpression.class).withLanguage(PhpLanguage.INSTANCE), psiElement -> {
| // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/index/ConfigSchemaIndex.java
// public class ConfigSchemaIndex extends FileBasedIndexExtension<String, Set<String>> {
//
// public static final ID<String, Set<String>> KEY = ID.create("de.espend.idea.php.drupal.config_schema");
// private static final StringSetDataExternalizer EXTERNALIZER = new StringSetDataExternalizer();
// private final KeyDescriptor<String> myKeyDescriptor = new EnumeratorStringDescriptor();
//
// @NotNull
// @Override
// public ID<String, Set<String>> getName() {
// return KEY;
// }
//
// @NotNull
// @Override
// public DataIndexer<String, Set<String>, FileContent> getIndexer() {
// return inputData -> {
// Map<String, Set<String>> map = new THashMap<>();
//
// PsiFile psiFile = inputData.getPsiFile();
// if(!Symfony2ProjectComponent.isEnabledForIndex(psiFile.getProject())) {
// return map;
// }
//
// if(!(psiFile instanceof YAMLFile) || !isValidForIndex(psiFile)) {
// return map;
// }
//
// for(YAMLKeyValue yamlKeyValue: YamlHelper.getTopLevelKeyValues((YAMLFile) psiFile)) {
// String key = PsiElementUtils.trimQuote(yamlKeyValue.getKeyText());
//
// if(StringUtils.isBlank(key) || key.contains("*")) {
// continue;
// }
//
// Set<String> mappings = new HashSet<>();
// YAMLKeyValue mapping = YamlHelper.getYamlKeyValue(yamlKeyValue, "mapping");
// if(mapping == null) {
// continue;
// }
//
// Set<String> keySet = YamlHelper.getKeySet(mapping);
// if(keySet != null) {
// mappings.addAll(keySet);
// }
//
// map.put(key, mappings);
// }
//
// return map;
// };
//
// }
//
// @NotNull
// @Override
// public KeyDescriptor<String> getKeyDescriptor() {
// return this.myKeyDescriptor;
// }
//
// @NotNull
// @Override
// public DataExternalizer<Set<String>> getValueExternalizer() {
// return EXTERNALIZER;
// }
//
// @NotNull
// @Override
// public FileBasedIndex.InputFilter getInputFilter() {
// return file ->
// file.getFileType() == YAMLFileType.YML || file.getFileType() == XmlFileType.INSTANCE;
// }
//
// @Override
// public boolean dependsOnFileContent() {
// return true;
// }
//
// @Override
// public int getVersion() {
// return 2;
// }
//
// private static boolean isValidForIndex(@NotNull PsiFile psiFile) {
//
// String fileName = psiFile.getName();
//
// return !(fileName.startsWith(".") || !fileName.endsWith(".schema.yml"));
// }
// }
// Path: src/de/espend/idea/php/drupal/config/ConfigCompletionGoto.java
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.indexing.FileBasedIndex;
import com.jetbrains.php.lang.PhpLanguage;
import com.jetbrains.php.lang.psi.elements.StringLiteralExpression;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.index.ConfigSchemaIndex;
import fr.adrienbrault.idea.symfony2plugin.Symfony2Icons;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionProvider;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrar;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrarParameter;
import fr.adrienbrault.idea.symfony2plugin.stubs.SymfonyProcessors;
import fr.adrienbrault.idea.symfony2plugin.util.MethodMatcher;
import fr.adrienbrault.idea.symfony2plugin.util.PsiElementUtils;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.yaml.YAMLFileType;
import org.jetbrains.yaml.psi.YAMLDocument;
import org.jetbrains.yaml.psi.YAMLKeyValue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
package de.espend.idea.php.drupal.config;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class ConfigCompletionGoto implements GotoCompletionRegistrar {
final private static MethodMatcher.CallToSignature[] CONFIG = new MethodMatcher.CallToSignature[] {
new MethodMatcher.CallToSignature("\\Drupal\\Core\\Config\\ConfigFactory", "get"),
};
@Override
public void register(GotoCompletionRegistrarParameter registrar) {
registrar.register(PlatformPatterns.psiElement().withParent(StringLiteralExpression.class).withLanguage(PhpLanguage.INSTANCE), psiElement -> {
| if(!DrupalProjectComponent.isEnabled(psiElement)) { |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/completion/PhpCompletionContributor.java | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/TranslationUtil.java
// public class TranslationUtil {
// public static void attachGetTextLookupKeys(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) {
// for(String phpClassName: SymfonyProcessors.createResult(project, GetTextFileIndex.KEY)) {
// completionResultSet.addElement(LookupElementBuilder.create(phpClassName).withIcon(DrupalIcons.DRUPAL));
// }
// }
// }
| import com.intellij.codeInsight.completion.*;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import com.jetbrains.php.lang.parser.PhpElementTypes;
import com.jetbrains.php.lang.psi.elements.*;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.TranslationUtil;
import fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper;
import org.jetbrains.annotations.NotNull; | package de.espend.idea.php.drupal.completion;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class PhpCompletionContributor extends CompletionContributor {
public PhpCompletionContributor() {
// t('foo');
// @TODO: pattern
extend(CompletionType.BASIC, PlatformPatterns.psiElement(), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
PsiElement psiElement = completionParameters.getOriginalPosition(); | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/TranslationUtil.java
// public class TranslationUtil {
// public static void attachGetTextLookupKeys(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) {
// for(String phpClassName: SymfonyProcessors.createResult(project, GetTextFileIndex.KEY)) {
// completionResultSet.addElement(LookupElementBuilder.create(phpClassName).withIcon(DrupalIcons.DRUPAL));
// }
// }
// }
// Path: src/de/espend/idea/php/drupal/completion/PhpCompletionContributor.java
import com.intellij.codeInsight.completion.*;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import com.jetbrains.php.lang.parser.PhpElementTypes;
import com.jetbrains.php.lang.psi.elements.*;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.TranslationUtil;
import fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper;
import org.jetbrains.annotations.NotNull;
package de.espend.idea.php.drupal.completion;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class PhpCompletionContributor extends CompletionContributor {
public PhpCompletionContributor() {
// t('foo');
// @TODO: pattern
extend(CompletionType.BASIC, PlatformPatterns.psiElement(), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
PsiElement psiElement = completionParameters.getOriginalPosition(); | if(psiElement == null || !DrupalProjectComponent.isEnabled(psiElement)) { |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/completion/PhpCompletionContributor.java | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/TranslationUtil.java
// public class TranslationUtil {
// public static void attachGetTextLookupKeys(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) {
// for(String phpClassName: SymfonyProcessors.createResult(project, GetTextFileIndex.KEY)) {
// completionResultSet.addElement(LookupElementBuilder.create(phpClassName).withIcon(DrupalIcons.DRUPAL));
// }
// }
// }
| import com.intellij.codeInsight.completion.*;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import com.jetbrains.php.lang.parser.PhpElementTypes;
import com.jetbrains.php.lang.psi.elements.*;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.TranslationUtil;
import fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper;
import org.jetbrains.annotations.NotNull; | package de.espend.idea.php.drupal.completion;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class PhpCompletionContributor extends CompletionContributor {
public PhpCompletionContributor() {
// t('foo');
// @TODO: pattern
extend(CompletionType.BASIC, PlatformPatterns.psiElement(), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
PsiElement psiElement = completionParameters.getOriginalPosition();
if(psiElement == null || !DrupalProjectComponent.isEnabled(psiElement)) {
return;
}
PsiElement literal = psiElement.getContext();
if (!(literal instanceof StringLiteralExpression)) {
return;
}
PsiElement parameterList = literal.getParent();
if (!(parameterList instanceof ParameterList)) {
return;
}
PsiElement functionReference = parameterList.getParent();
if (!(functionReference instanceof FunctionReference) || !"t".equals(((FunctionReference) functionReference).getName())) {
return;
}
| // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/TranslationUtil.java
// public class TranslationUtil {
// public static void attachGetTextLookupKeys(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) {
// for(String phpClassName: SymfonyProcessors.createResult(project, GetTextFileIndex.KEY)) {
// completionResultSet.addElement(LookupElementBuilder.create(phpClassName).withIcon(DrupalIcons.DRUPAL));
// }
// }
// }
// Path: src/de/espend/idea/php/drupal/completion/PhpCompletionContributor.java
import com.intellij.codeInsight.completion.*;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import com.jetbrains.php.lang.parser.PhpElementTypes;
import com.jetbrains.php.lang.psi.elements.*;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.TranslationUtil;
import fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper;
import org.jetbrains.annotations.NotNull;
package de.espend.idea.php.drupal.completion;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class PhpCompletionContributor extends CompletionContributor {
public PhpCompletionContributor() {
// t('foo');
// @TODO: pattern
extend(CompletionType.BASIC, PlatformPatterns.psiElement(), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
PsiElement psiElement = completionParameters.getOriginalPosition();
if(psiElement == null || !DrupalProjectComponent.isEnabled(psiElement)) {
return;
}
PsiElement literal = psiElement.getContext();
if (!(literal instanceof StringLiteralExpression)) {
return;
}
PsiElement parameterList = literal.getParent();
if (!(parameterList instanceof ParameterList)) {
return;
}
PsiElement functionReference = parameterList.getParent();
if (!(functionReference instanceof FunctionReference) || !"t".equals(((FunctionReference) functionReference).getName())) {
return;
}
| TranslationUtil.attachGetTextLookupKeys(completionResultSet, psiElement.getProject()); |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/registrar/PhpRouteParameterCompletion.java | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
| import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.patterns.PsiElementPattern;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.parser.PhpElementTypes;
import com.jetbrains.php.lang.psi.elements.*;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionProvider;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrar;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrarParameter;
import fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper;
import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections; | package de.espend.idea.php.drupal.registrar;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class PhpRouteParameterCompletion implements GotoCompletionRegistrar {
@Override
public void register(GotoCompletionRegistrarParameter registrar) {
registrar.register(getElementPatternPattern(), psiElement -> { | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
// Path: src/de/espend/idea/php/drupal/registrar/PhpRouteParameterCompletion.java
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.patterns.PsiElementPattern;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.parser.PhpElementTypes;
import com.jetbrains.php.lang.psi.elements.*;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionProvider;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrar;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrarParameter;
import fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper;
import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
package de.espend.idea.php.drupal.registrar;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class PhpRouteParameterCompletion implements GotoCompletionRegistrar {
@Override
public void register(GotoCompletionRegistrarParameter registrar) {
registrar.register(getElementPatternPattern(), psiElement -> { | if(!DrupalProjectComponent.isEnabled(psiElement)) { |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/navigation/PhpGoToDeclarationHandler.java | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/DrupalPattern.java
// public class DrupalPattern {
// public static boolean isAfterArrayKey(PsiElement psiElement, String arrayKeyName) {
//
// PsiElement literal = psiElement.getContext();
// if(!(literal instanceof StringLiteralExpression)) {
// return false;
// }
//
// PsiElement arrayValue = literal.getParent();
// if(arrayValue.getNode().getElementType() != PhpElementTypes.ARRAY_VALUE) {
// return false;
// }
//
// PsiElement arrayHashElement = arrayValue.getParent();
// if(!(arrayHashElement instanceof ArrayHashElement)) {
// return false;
// }
//
// PsiElement arrayKey = ((ArrayHashElement) arrayHashElement).getKey();
// String keyString = PhpElementsUtil.getStringValue(arrayKey);
//
// return arrayKeyName.equals(keyString);
// }
// }
| import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.psi.elements.StringLiteralExpression;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.DrupalPattern;
import fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List; | package de.espend.idea.php.drupal.navigation;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class PhpGoToDeclarationHandler implements GotoDeclarationHandler {
@Nullable
@Override
public PsiElement[] getGotoDeclarationTargets(PsiElement psiElement, int i, Editor editor) {
| // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/DrupalPattern.java
// public class DrupalPattern {
// public static boolean isAfterArrayKey(PsiElement psiElement, String arrayKeyName) {
//
// PsiElement literal = psiElement.getContext();
// if(!(literal instanceof StringLiteralExpression)) {
// return false;
// }
//
// PsiElement arrayValue = literal.getParent();
// if(arrayValue.getNode().getElementType() != PhpElementTypes.ARRAY_VALUE) {
// return false;
// }
//
// PsiElement arrayHashElement = arrayValue.getParent();
// if(!(arrayHashElement instanceof ArrayHashElement)) {
// return false;
// }
//
// PsiElement arrayKey = ((ArrayHashElement) arrayHashElement).getKey();
// String keyString = PhpElementsUtil.getStringValue(arrayKey);
//
// return arrayKeyName.equals(keyString);
// }
// }
// Path: src/de/espend/idea/php/drupal/navigation/PhpGoToDeclarationHandler.java
import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.psi.elements.StringLiteralExpression;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.DrupalPattern;
import fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
package de.espend.idea.php.drupal.navigation;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class PhpGoToDeclarationHandler implements GotoDeclarationHandler {
@Nullable
@Override
public PsiElement[] getGotoDeclarationTargets(PsiElement psiElement, int i, Editor editor) {
| if(!DrupalProjectComponent.isEnabled(psiElement)) { |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/navigation/PhpGoToDeclarationHandler.java | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/DrupalPattern.java
// public class DrupalPattern {
// public static boolean isAfterArrayKey(PsiElement psiElement, String arrayKeyName) {
//
// PsiElement literal = psiElement.getContext();
// if(!(literal instanceof StringLiteralExpression)) {
// return false;
// }
//
// PsiElement arrayValue = literal.getParent();
// if(arrayValue.getNode().getElementType() != PhpElementTypes.ARRAY_VALUE) {
// return false;
// }
//
// PsiElement arrayHashElement = arrayValue.getParent();
// if(!(arrayHashElement instanceof ArrayHashElement)) {
// return false;
// }
//
// PsiElement arrayKey = ((ArrayHashElement) arrayHashElement).getKey();
// String keyString = PhpElementsUtil.getStringValue(arrayKey);
//
// return arrayKeyName.equals(keyString);
// }
// }
| import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.psi.elements.StringLiteralExpression;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.DrupalPattern;
import fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List; | package de.espend.idea.php.drupal.navigation;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class PhpGoToDeclarationHandler implements GotoDeclarationHandler {
@Nullable
@Override
public PsiElement[] getGotoDeclarationTargets(PsiElement psiElement, int i, Editor editor) {
if(!DrupalProjectComponent.isEnabled(psiElement)) {
return new PsiElement[0];
}
List<PsiElement> psiElementList = new ArrayList<>();
PsiElement context = psiElement.getContext(); | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/DrupalPattern.java
// public class DrupalPattern {
// public static boolean isAfterArrayKey(PsiElement psiElement, String arrayKeyName) {
//
// PsiElement literal = psiElement.getContext();
// if(!(literal instanceof StringLiteralExpression)) {
// return false;
// }
//
// PsiElement arrayValue = literal.getParent();
// if(arrayValue.getNode().getElementType() != PhpElementTypes.ARRAY_VALUE) {
// return false;
// }
//
// PsiElement arrayHashElement = arrayValue.getParent();
// if(!(arrayHashElement instanceof ArrayHashElement)) {
// return false;
// }
//
// PsiElement arrayKey = ((ArrayHashElement) arrayHashElement).getKey();
// String keyString = PhpElementsUtil.getStringValue(arrayKey);
//
// return arrayKeyName.equals(keyString);
// }
// }
// Path: src/de/espend/idea/php/drupal/navigation/PhpGoToDeclarationHandler.java
import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.psi.elements.StringLiteralExpression;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.DrupalPattern;
import fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
package de.espend.idea.php.drupal.navigation;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class PhpGoToDeclarationHandler implements GotoDeclarationHandler {
@Nullable
@Override
public PsiElement[] getGotoDeclarationTargets(PsiElement psiElement, int i, Editor editor) {
if(!DrupalProjectComponent.isEnabled(psiElement)) {
return new PsiElement[0];
}
List<PsiElement> psiElementList = new ArrayList<>();
PsiElement context = psiElement.getContext(); | if(context instanceof StringLiteralExpression && DrupalPattern.isAfterArrayKey(psiElement, "route_name")) { |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/registrar/ControllerCompletion.java | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/DrupalUtil.java
// public class DrupalUtil {
//
// @NotNull
// public static Set<String> getModuleNames(@NotNull Project project) {
// Set<String> allFilesByExt = new HashSet<>();
//
// for (VirtualFile virtualFile : FilenameIndex.getAllFilesByExt(project, "yml")) {
// if(!virtualFile.getName().endsWith(".info.yml")) {
// continue;
// }
//
// allFilesByExt.add(StringUtils.stripEnd(virtualFile.getName(), ".info.yml"));
// }
//
// allFilesByExt.addAll(FilenameIndex.getAllFilesByExt(project, "module").stream()
// .map(virtualFile -> StringUtils.stripEnd(virtualFile.getName(), ".module"))
// .collect(Collectors.toList()));
//
// return allFilesByExt;
// }
//
// }
| import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.PhpIndex;
import com.jetbrains.php.lang.psi.elements.Method;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.DrupalUtil;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionProvider;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrar;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrarParameter;
import fr.adrienbrault.idea.symfony2plugin.config.yaml.YamlElementPatternHelper;
import fr.adrienbrault.idea.symfony2plugin.util.PhpIndexUtil;
import org.jetbrains.annotations.NotNull;
import java.util.*; | package de.espend.idea.php.drupal.registrar;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class ControllerCompletion implements GotoCompletionRegistrar {
@Override
public void register(GotoCompletionRegistrarParameter registrar) {
registrar.register(YamlElementPatternHelper.getSingleLineScalarKey("_controller"), psiElement -> { | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/DrupalUtil.java
// public class DrupalUtil {
//
// @NotNull
// public static Set<String> getModuleNames(@NotNull Project project) {
// Set<String> allFilesByExt = new HashSet<>();
//
// for (VirtualFile virtualFile : FilenameIndex.getAllFilesByExt(project, "yml")) {
// if(!virtualFile.getName().endsWith(".info.yml")) {
// continue;
// }
//
// allFilesByExt.add(StringUtils.stripEnd(virtualFile.getName(), ".info.yml"));
// }
//
// allFilesByExt.addAll(FilenameIndex.getAllFilesByExt(project, "module").stream()
// .map(virtualFile -> StringUtils.stripEnd(virtualFile.getName(), ".module"))
// .collect(Collectors.toList()));
//
// return allFilesByExt;
// }
//
// }
// Path: src/de/espend/idea/php/drupal/registrar/ControllerCompletion.java
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.PhpIndex;
import com.jetbrains.php.lang.psi.elements.Method;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.DrupalUtil;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionProvider;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrar;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrarParameter;
import fr.adrienbrault.idea.symfony2plugin.config.yaml.YamlElementPatternHelper;
import fr.adrienbrault.idea.symfony2plugin.util.PhpIndexUtil;
import org.jetbrains.annotations.NotNull;
import java.util.*;
package de.espend.idea.php.drupal.registrar;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class ControllerCompletion implements GotoCompletionRegistrar {
@Override
public void register(GotoCompletionRegistrarParameter registrar) {
registrar.register(YamlElementPatternHelper.getSingleLineScalarKey("_controller"), psiElement -> { | if(!DrupalProjectComponent.isEnabled(psiElement)) { |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/registrar/ControllerCompletion.java | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/DrupalUtil.java
// public class DrupalUtil {
//
// @NotNull
// public static Set<String> getModuleNames(@NotNull Project project) {
// Set<String> allFilesByExt = new HashSet<>();
//
// for (VirtualFile virtualFile : FilenameIndex.getAllFilesByExt(project, "yml")) {
// if(!virtualFile.getName().endsWith(".info.yml")) {
// continue;
// }
//
// allFilesByExt.add(StringUtils.stripEnd(virtualFile.getName(), ".info.yml"));
// }
//
// allFilesByExt.addAll(FilenameIndex.getAllFilesByExt(project, "module").stream()
// .map(virtualFile -> StringUtils.stripEnd(virtualFile.getName(), ".module"))
// .collect(Collectors.toList()));
//
// return allFilesByExt;
// }
//
// }
| import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.PhpIndex;
import com.jetbrains.php.lang.psi.elements.Method;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.DrupalUtil;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionProvider;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrar;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrarParameter;
import fr.adrienbrault.idea.symfony2plugin.config.yaml.YamlElementPatternHelper;
import fr.adrienbrault.idea.symfony2plugin.util.PhpIndexUtil;
import org.jetbrains.annotations.NotNull;
import java.util.*; | package de.espend.idea.php.drupal.registrar;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class ControllerCompletion implements GotoCompletionRegistrar {
@Override
public void register(GotoCompletionRegistrarParameter registrar) {
registrar.register(YamlElementPatternHelper.getSingleLineScalarKey("_controller"), psiElement -> {
if(!DrupalProjectComponent.isEnabled(psiElement)) {
return null;
}
return new MyGotoCompletionProvider(psiElement);
});
}
private static class MyGotoCompletionProvider extends GotoCompletionProvider {
MyGotoCompletionProvider(PsiElement psiElement) {
super(psiElement);
}
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {
Collection<LookupElement> lookupElements = new ArrayList<>();
| // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/DrupalUtil.java
// public class DrupalUtil {
//
// @NotNull
// public static Set<String> getModuleNames(@NotNull Project project) {
// Set<String> allFilesByExt = new HashSet<>();
//
// for (VirtualFile virtualFile : FilenameIndex.getAllFilesByExt(project, "yml")) {
// if(!virtualFile.getName().endsWith(".info.yml")) {
// continue;
// }
//
// allFilesByExt.add(StringUtils.stripEnd(virtualFile.getName(), ".info.yml"));
// }
//
// allFilesByExt.addAll(FilenameIndex.getAllFilesByExt(project, "module").stream()
// .map(virtualFile -> StringUtils.stripEnd(virtualFile.getName(), ".module"))
// .collect(Collectors.toList()));
//
// return allFilesByExt;
// }
//
// }
// Path: src/de/espend/idea/php/drupal/registrar/ControllerCompletion.java
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.PhpIndex;
import com.jetbrains.php.lang.psi.elements.Method;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.DrupalUtil;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionProvider;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrar;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrarParameter;
import fr.adrienbrault.idea.symfony2plugin.config.yaml.YamlElementPatternHelper;
import fr.adrienbrault.idea.symfony2plugin.util.PhpIndexUtil;
import org.jetbrains.annotations.NotNull;
import java.util.*;
package de.espend.idea.php.drupal.registrar;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class ControllerCompletion implements GotoCompletionRegistrar {
@Override
public void register(GotoCompletionRegistrarParameter registrar) {
registrar.register(YamlElementPatternHelper.getSingleLineScalarKey("_controller"), psiElement -> {
if(!DrupalProjectComponent.isEnabled(psiElement)) {
return null;
}
return new MyGotoCompletionProvider(psiElement);
});
}
private static class MyGotoCompletionProvider extends GotoCompletionProvider {
MyGotoCompletionProvider(PsiElement psiElement) {
super(psiElement);
}
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {
Collection<LookupElement> lookupElements = new ArrayList<>();
| Set<String> moduleNames = DrupalUtil.getModuleNames(getProject()); |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/index/GetTextFileIndex.java | // Path: src/de/espend/idea/php/drupal/gettext/GettextResourceBundle.java
// public class GettextResourceBundle extends ResourceBundle {
//
// private static final Logger LOG = Logger
// .getLogger(GettextResourceBundle.class);
//
// private static final Pattern LINE_PATTERN = Pattern
// .compile("^([\\w_\\[\\]]*)\\s*\\\"(.*)\\\"$");
//
// private Map<String, Object> resources = new HashMap<>();
//
// public GettextResourceBundle(InputStream inputStream) {
// init(new LineNumberReader(new InputStreamReader(inputStream)));
// }
//
// public GettextResourceBundle(Reader reader) {
// init(new LineNumberReader(reader));
// }
//
// public GettextResourceBundle(File file) {
// try {
// init(new LineNumberReader(new FileReader(file)));
// } catch (FileNotFoundException e) {
// LOG.error("GettextResourceBundle could not be initialized", e);
// }
// }
//
// /**
// * initialize the ResourceBundle from a PO file
// *
// * if
// *
// * @param reader
// * the reader to read the contents of the PO file from
// */
// private void init(LineNumberReader reader) {
// if (reader != null) {
// String line = null;
// String key = null;
// String value = null;
// try {
// while ((line = reader.readLine()) != null) {
// if (line.startsWith("#")) {
// LOG.trace(reader.getLineNumber()
// + ": Parsing PO file, comment skipped [" + line
// + "]");
// } else if (line.trim().length() == 0) {
// LOG.trace(reader.getLineNumber()
// + ": Parsing PO file, whitespace line skipped");
// } else {
// Matcher matcher = LINE_PATTERN.matcher(line);
// if (matcher.matches()) {
// String type = matcher.group(1);
// String str = matcher.group(2);
// if ("msgid".equals(type)) {
// if ( key != null && value != null ) {
// LOG.debug("Parsing PO file, key,value pair found [" + key + " => " + value + "]");
// resources.put(StringEscapeUtils.unescapeJava(key), StringEscapeUtils.unescapeJava(value));
// key = null;
// value = null;
// }
// key = str;
// LOG.trace(reader.getLineNumber()
// + ": Parsing PO file, msgid found [" + key
// + "]");
// }
// else if ("msgstr".equals(type)) {
// value = str;
// LOG.trace(reader.getLineNumber()
// + ": Parsing PO file, msgstr found [" + value
// + "]");
// }
// else if ( type == null || type.length()==0 ) {
// if ( value == null ) {
// LOG.trace(reader.getLineNumber()
// + ": Parsing PO file, addition to msgid found [" + str
// + "]");
// key += str;
// }
// else {
// LOG.trace(reader.getLineNumber()
// + ": Parsing PO file, addition to msgstr found [" + str
// + "]");
// value += str;
// }
//
//
// }
// } else {
// LOG.error(reader.getLineNumber()
// + ": Parsing PO file, invalid syntax ["
// + line + "]");
// }
// }
//
// }
//
// if ( key != null && value != null ) {
// LOG.debug("Parsing PO file, key,value pair found [" + key + " => " + value + "]");
// resources.put(StringEscapeUtils.unescapeJava(key), StringEscapeUtils.unescapeJava(value));
// key = null;
// value = null;
// }
// } catch (IOException e) {
// LOG.error("GettextResourceBundle could not be initialized", e);
// }
//
// } else {
// LOG.warn("GettextResourceBundle could not be initialized, input was null");
// }
// LOG.info("GettextResourceBundle initialization complete, " + resources.size() + " resources loaded");
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.util.ResourceBundle#getKeys()
// */
// @NotNull
// @Override
// public Enumeration<String> getKeys() {
// return Collections.enumeration(resources.keySet());
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.util.ResourceBundle#handleGetObject(java.lang.String)
// */
// @Override
// protected Object handleGetObject(@NotNull String key) {
// return resources.get(key);
// }
//
// }
| import com.intellij.util.indexing.*;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.EnumeratorStringDescriptor;
import com.intellij.util.io.KeyDescriptor;
import com.intellij.util.io.VoidDataExternalizer;
import de.espend.idea.php.drupal.gettext.GettextResourceBundle;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.*; | package de.espend.idea.php.drupal.index;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class GetTextFileIndex extends FileBasedIndexExtension<String, Void> {
public static final ID<String, Void> KEY = ID.create("de.espend.idea.php.drupal.gettext");
private final KeyDescriptor<String> myKeyDescriptor = new EnumeratorStringDescriptor();
@NotNull
@Override
public ID<String, Void> getName() {
return KEY;
}
@NotNull
@Override
public DataIndexer<String, Void, FileContent> getIndexer() {
return fileContent -> {
Map<String, Void> msgId = new HashMap<>();
try { | // Path: src/de/espend/idea/php/drupal/gettext/GettextResourceBundle.java
// public class GettextResourceBundle extends ResourceBundle {
//
// private static final Logger LOG = Logger
// .getLogger(GettextResourceBundle.class);
//
// private static final Pattern LINE_PATTERN = Pattern
// .compile("^([\\w_\\[\\]]*)\\s*\\\"(.*)\\\"$");
//
// private Map<String, Object> resources = new HashMap<>();
//
// public GettextResourceBundle(InputStream inputStream) {
// init(new LineNumberReader(new InputStreamReader(inputStream)));
// }
//
// public GettextResourceBundle(Reader reader) {
// init(new LineNumberReader(reader));
// }
//
// public GettextResourceBundle(File file) {
// try {
// init(new LineNumberReader(new FileReader(file)));
// } catch (FileNotFoundException e) {
// LOG.error("GettextResourceBundle could not be initialized", e);
// }
// }
//
// /**
// * initialize the ResourceBundle from a PO file
// *
// * if
// *
// * @param reader
// * the reader to read the contents of the PO file from
// */
// private void init(LineNumberReader reader) {
// if (reader != null) {
// String line = null;
// String key = null;
// String value = null;
// try {
// while ((line = reader.readLine()) != null) {
// if (line.startsWith("#")) {
// LOG.trace(reader.getLineNumber()
// + ": Parsing PO file, comment skipped [" + line
// + "]");
// } else if (line.trim().length() == 0) {
// LOG.trace(reader.getLineNumber()
// + ": Parsing PO file, whitespace line skipped");
// } else {
// Matcher matcher = LINE_PATTERN.matcher(line);
// if (matcher.matches()) {
// String type = matcher.group(1);
// String str = matcher.group(2);
// if ("msgid".equals(type)) {
// if ( key != null && value != null ) {
// LOG.debug("Parsing PO file, key,value pair found [" + key + " => " + value + "]");
// resources.put(StringEscapeUtils.unescapeJava(key), StringEscapeUtils.unescapeJava(value));
// key = null;
// value = null;
// }
// key = str;
// LOG.trace(reader.getLineNumber()
// + ": Parsing PO file, msgid found [" + key
// + "]");
// }
// else if ("msgstr".equals(type)) {
// value = str;
// LOG.trace(reader.getLineNumber()
// + ": Parsing PO file, msgstr found [" + value
// + "]");
// }
// else if ( type == null || type.length()==0 ) {
// if ( value == null ) {
// LOG.trace(reader.getLineNumber()
// + ": Parsing PO file, addition to msgid found [" + str
// + "]");
// key += str;
// }
// else {
// LOG.trace(reader.getLineNumber()
// + ": Parsing PO file, addition to msgstr found [" + str
// + "]");
// value += str;
// }
//
//
// }
// } else {
// LOG.error(reader.getLineNumber()
// + ": Parsing PO file, invalid syntax ["
// + line + "]");
// }
// }
//
// }
//
// if ( key != null && value != null ) {
// LOG.debug("Parsing PO file, key,value pair found [" + key + " => " + value + "]");
// resources.put(StringEscapeUtils.unescapeJava(key), StringEscapeUtils.unescapeJava(value));
// key = null;
// value = null;
// }
// } catch (IOException e) {
// LOG.error("GettextResourceBundle could not be initialized", e);
// }
//
// } else {
// LOG.warn("GettextResourceBundle could not be initialized, input was null");
// }
// LOG.info("GettextResourceBundle initialization complete, " + resources.size() + " resources loaded");
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.util.ResourceBundle#getKeys()
// */
// @NotNull
// @Override
// public Enumeration<String> getKeys() {
// return Collections.enumeration(resources.keySet());
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.util.ResourceBundle#handleGetObject(java.lang.String)
// */
// @Override
// protected Object handleGetObject(@NotNull String key) {
// return resources.get(key);
// }
//
// }
// Path: src/de/espend/idea/php/drupal/index/GetTextFileIndex.java
import com.intellij.util.indexing.*;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.EnumeratorStringDescriptor;
import com.intellij.util.io.KeyDescriptor;
import com.intellij.util.io.VoidDataExternalizer;
import de.espend.idea.php.drupal.gettext.GettextResourceBundle;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.*;
package de.espend.idea.php.drupal.index;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class GetTextFileIndex extends FileBasedIndexExtension<String, Void> {
public static final ID<String, Void> KEY = ID.create("de.espend.idea.php.drupal.gettext");
private final KeyDescriptor<String> myKeyDescriptor = new EnumeratorStringDescriptor();
@NotNull
@Override
public ID<String, Void> getName() {
return KEY;
}
@NotNull
@Override
public DataIndexer<String, Void, FileContent> getIndexer() {
return fileContent -> {
Map<String, Void> msgId = new HashMap<>();
try { | GettextResourceBundle gettextResourceBundle = new GettextResourceBundle(fileContent.getFile().getInputStream()); |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/completion/TwigCompletionContributor.java | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/TranslationUtil.java
// public class TranslationUtil {
// public static void attachGetTextLookupKeys(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) {
// for(String phpClassName: SymfonyProcessors.createResult(project, GetTextFileIndex.KEY)) {
// completionResultSet.addElement(LookupElementBuilder.create(phpClassName).withIcon(DrupalIcons.DRUPAL));
// }
// }
// }
| import com.intellij.codeInsight.completion.*;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.TranslationUtil;
import fr.adrienbrault.idea.symfony2plugin.templating.TwigPattern;
import org.jetbrains.annotations.NotNull; | package de.espend.idea.php.drupal.completion;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class TwigCompletionContributor extends CompletionContributor {
public TwigCompletionContributor() {
// ''|t;
extend(CompletionType.BASIC, TwigPattern.getTranslationPattern("t"), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
PsiElement psiElement = completionParameters.getOriginalPosition(); | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/TranslationUtil.java
// public class TranslationUtil {
// public static void attachGetTextLookupKeys(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) {
// for(String phpClassName: SymfonyProcessors.createResult(project, GetTextFileIndex.KEY)) {
// completionResultSet.addElement(LookupElementBuilder.create(phpClassName).withIcon(DrupalIcons.DRUPAL));
// }
// }
// }
// Path: src/de/espend/idea/php/drupal/completion/TwigCompletionContributor.java
import com.intellij.codeInsight.completion.*;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.TranslationUtil;
import fr.adrienbrault.idea.symfony2plugin.templating.TwigPattern;
import org.jetbrains.annotations.NotNull;
package de.espend.idea.php.drupal.completion;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class TwigCompletionContributor extends CompletionContributor {
public TwigCompletionContributor() {
// ''|t;
extend(CompletionType.BASIC, TwigPattern.getTranslationPattern("t"), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
PsiElement psiElement = completionParameters.getOriginalPosition(); | if(psiElement == null || !DrupalProjectComponent.isEnabled(psiElement)) { |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/completion/TwigCompletionContributor.java | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/TranslationUtil.java
// public class TranslationUtil {
// public static void attachGetTextLookupKeys(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) {
// for(String phpClassName: SymfonyProcessors.createResult(project, GetTextFileIndex.KEY)) {
// completionResultSet.addElement(LookupElementBuilder.create(phpClassName).withIcon(DrupalIcons.DRUPAL));
// }
// }
// }
| import com.intellij.codeInsight.completion.*;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.TranslationUtil;
import fr.adrienbrault.idea.symfony2plugin.templating.TwigPattern;
import org.jetbrains.annotations.NotNull; | package de.espend.idea.php.drupal.completion;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class TwigCompletionContributor extends CompletionContributor {
public TwigCompletionContributor() {
// ''|t;
extend(CompletionType.BASIC, TwigPattern.getTranslationPattern("t"), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
PsiElement psiElement = completionParameters.getOriginalPosition();
if(psiElement == null || !DrupalProjectComponent.isEnabled(psiElement)) {
return;
}
| // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/TranslationUtil.java
// public class TranslationUtil {
// public static void attachGetTextLookupKeys(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) {
// for(String phpClassName: SymfonyProcessors.createResult(project, GetTextFileIndex.KEY)) {
// completionResultSet.addElement(LookupElementBuilder.create(phpClassName).withIcon(DrupalIcons.DRUPAL));
// }
// }
// }
// Path: src/de/espend/idea/php/drupal/completion/TwigCompletionContributor.java
import com.intellij.codeInsight.completion.*;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.TranslationUtil;
import fr.adrienbrault.idea.symfony2plugin.templating.TwigPattern;
import org.jetbrains.annotations.NotNull;
package de.espend.idea.php.drupal.completion;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class TwigCompletionContributor extends CompletionContributor {
public TwigCompletionContributor() {
// ''|t;
extend(CompletionType.BASIC, TwigPattern.getTranslationPattern("t"), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
PsiElement psiElement = completionParameters.getOriginalPosition();
if(psiElement == null || !DrupalProjectComponent.isEnabled(psiElement)) {
return;
}
| TranslationUtil.attachGetTextLookupKeys(completionResultSet, psiElement.getProject()); |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/annotation/TranslationAnnotationReference.java | // Path: src/de/espend/idea/php/drupal/utils/TranslationUtil.java
// public class TranslationUtil {
// public static void attachGetTextLookupKeys(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) {
// for(String phpClassName: SymfonyProcessors.createResult(project, GetTextFileIndex.KEY)) {
// completionResultSet.addElement(LookupElementBuilder.create(phpClassName).withIcon(DrupalIcons.DRUPAL));
// }
// }
// }
| import com.jetbrains.php.lang.PhpLangUtil;
import de.espend.idea.php.annotation.extension.PhpAnnotationCompletionProvider;
import de.espend.idea.php.annotation.extension.parameter.AnnotationCompletionProviderParameter;
import de.espend.idea.php.annotation.extension.parameter.AnnotationPropertyParameter;
import de.espend.idea.php.drupal.utils.TranslationUtil;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull; | package de.espend.idea.php.drupal.annotation;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*
* "@Translation("<caret>")"
*/
public class TranslationAnnotationReference implements PhpAnnotationCompletionProvider {
@Override
public void getPropertyValueCompletions(AnnotationPropertyParameter parameter, AnnotationCompletionProviderParameter annotationCompletionProviderParameter) {
if(!isSupported(parameter)) {
return;
}
| // Path: src/de/espend/idea/php/drupal/utils/TranslationUtil.java
// public class TranslationUtil {
// public static void attachGetTextLookupKeys(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) {
// for(String phpClassName: SymfonyProcessors.createResult(project, GetTextFileIndex.KEY)) {
// completionResultSet.addElement(LookupElementBuilder.create(phpClassName).withIcon(DrupalIcons.DRUPAL));
// }
// }
// }
// Path: src/de/espend/idea/php/drupal/annotation/TranslationAnnotationReference.java
import com.jetbrains.php.lang.PhpLangUtil;
import de.espend.idea.php.annotation.extension.PhpAnnotationCompletionProvider;
import de.espend.idea.php.annotation.extension.parameter.AnnotationCompletionProviderParameter;
import de.espend.idea.php.annotation.extension.parameter.AnnotationPropertyParameter;
import de.espend.idea.php.drupal.utils.TranslationUtil;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
package de.espend.idea.php.drupal.annotation;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*
* "@Translation("<caret>")"
*/
public class TranslationAnnotationReference implements PhpAnnotationCompletionProvider {
@Override
public void getPropertyValueCompletions(AnnotationPropertyParameter parameter, AnnotationCompletionProviderParameter annotationCompletionProviderParameter) {
if(!isSupported(parameter)) {
return;
}
| TranslationUtil.attachGetTextLookupKeys(annotationCompletionProviderParameter.getResult(), parameter.getProject()); |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/utils/TranslationUtil.java | // Path: src/de/espend/idea/php/drupal/DrupalIcons.java
// public class DrupalIcons {
// public static final Icon DRUPAL = IconLoader.getIcon("icons/drupal.png");
// }
//
// Path: src/de/espend/idea/php/drupal/index/GetTextFileIndex.java
// public class GetTextFileIndex extends FileBasedIndexExtension<String, Void> {
//
// public static final ID<String, Void> KEY = ID.create("de.espend.idea.php.drupal.gettext");
// private final KeyDescriptor<String> myKeyDescriptor = new EnumeratorStringDescriptor();
//
// @NotNull
// @Override
// public ID<String, Void> getName() {
// return KEY;
// }
//
// @NotNull
// @Override
// public DataIndexer<String, Void, FileContent> getIndexer() {
// return fileContent -> {
// Map<String, Void> msgId = new HashMap<>();
//
// try {
// GettextResourceBundle gettextResourceBundle = new GettextResourceBundle(fileContent.getFile().getInputStream());
// Enumeration<String> tests = gettextResourceBundle.getKeys();
// for(String test: new HashSet<>(Collections.list(tests))) {
// if(StringUtils.isNotBlank(test)) {
// msgId.put(test, null);
// }
// }
// } catch (IOException e) {
// return msgId;
// }
// return msgId;
// };
// }
//
// @NotNull
// @Override
// public KeyDescriptor<String> getKeyDescriptor() {
// return this.myKeyDescriptor;
// }
//
// @NotNull
// @Override
// public DataExternalizer<Void> getValueExternalizer() {
// return VoidDataExternalizer.INSTANCE;
// }
//
// @NotNull
// @Override
// public FileBasedIndex.InputFilter getInputFilter() {
// return file -> "po".equals(file.getExtension());
// }
//
// @Override
// public boolean dependsOnFileContent() {
// return true;
// }
//
// @Override
// public int getVersion() {
// return 1;
// }
// }
| import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.project.Project;
import de.espend.idea.php.drupal.DrupalIcons;
import de.espend.idea.php.drupal.index.GetTextFileIndex;
import fr.adrienbrault.idea.symfony2plugin.stubs.SymfonyProcessors;
import org.jetbrains.annotations.NotNull; | package de.espend.idea.php.drupal.utils;
public class TranslationUtil {
public static void attachGetTextLookupKeys(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) { | // Path: src/de/espend/idea/php/drupal/DrupalIcons.java
// public class DrupalIcons {
// public static final Icon DRUPAL = IconLoader.getIcon("icons/drupal.png");
// }
//
// Path: src/de/espend/idea/php/drupal/index/GetTextFileIndex.java
// public class GetTextFileIndex extends FileBasedIndexExtension<String, Void> {
//
// public static final ID<String, Void> KEY = ID.create("de.espend.idea.php.drupal.gettext");
// private final KeyDescriptor<String> myKeyDescriptor = new EnumeratorStringDescriptor();
//
// @NotNull
// @Override
// public ID<String, Void> getName() {
// return KEY;
// }
//
// @NotNull
// @Override
// public DataIndexer<String, Void, FileContent> getIndexer() {
// return fileContent -> {
// Map<String, Void> msgId = new HashMap<>();
//
// try {
// GettextResourceBundle gettextResourceBundle = new GettextResourceBundle(fileContent.getFile().getInputStream());
// Enumeration<String> tests = gettextResourceBundle.getKeys();
// for(String test: new HashSet<>(Collections.list(tests))) {
// if(StringUtils.isNotBlank(test)) {
// msgId.put(test, null);
// }
// }
// } catch (IOException e) {
// return msgId;
// }
// return msgId;
// };
// }
//
// @NotNull
// @Override
// public KeyDescriptor<String> getKeyDescriptor() {
// return this.myKeyDescriptor;
// }
//
// @NotNull
// @Override
// public DataExternalizer<Void> getValueExternalizer() {
// return VoidDataExternalizer.INSTANCE;
// }
//
// @NotNull
// @Override
// public FileBasedIndex.InputFilter getInputFilter() {
// return file -> "po".equals(file.getExtension());
// }
//
// @Override
// public boolean dependsOnFileContent() {
// return true;
// }
//
// @Override
// public int getVersion() {
// return 1;
// }
// }
// Path: src/de/espend/idea/php/drupal/utils/TranslationUtil.java
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.project.Project;
import de.espend.idea.php.drupal.DrupalIcons;
import de.espend.idea.php.drupal.index.GetTextFileIndex;
import fr.adrienbrault.idea.symfony2plugin.stubs.SymfonyProcessors;
import org.jetbrains.annotations.NotNull;
package de.espend.idea.php.drupal.utils;
public class TranslationUtil {
public static void attachGetTextLookupKeys(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) { | for(String phpClassName: SymfonyProcessors.createResult(project, GetTextFileIndex.KEY)) { |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/utils/TranslationUtil.java | // Path: src/de/espend/idea/php/drupal/DrupalIcons.java
// public class DrupalIcons {
// public static final Icon DRUPAL = IconLoader.getIcon("icons/drupal.png");
// }
//
// Path: src/de/espend/idea/php/drupal/index/GetTextFileIndex.java
// public class GetTextFileIndex extends FileBasedIndexExtension<String, Void> {
//
// public static final ID<String, Void> KEY = ID.create("de.espend.idea.php.drupal.gettext");
// private final KeyDescriptor<String> myKeyDescriptor = new EnumeratorStringDescriptor();
//
// @NotNull
// @Override
// public ID<String, Void> getName() {
// return KEY;
// }
//
// @NotNull
// @Override
// public DataIndexer<String, Void, FileContent> getIndexer() {
// return fileContent -> {
// Map<String, Void> msgId = new HashMap<>();
//
// try {
// GettextResourceBundle gettextResourceBundle = new GettextResourceBundle(fileContent.getFile().getInputStream());
// Enumeration<String> tests = gettextResourceBundle.getKeys();
// for(String test: new HashSet<>(Collections.list(tests))) {
// if(StringUtils.isNotBlank(test)) {
// msgId.put(test, null);
// }
// }
// } catch (IOException e) {
// return msgId;
// }
// return msgId;
// };
// }
//
// @NotNull
// @Override
// public KeyDescriptor<String> getKeyDescriptor() {
// return this.myKeyDescriptor;
// }
//
// @NotNull
// @Override
// public DataExternalizer<Void> getValueExternalizer() {
// return VoidDataExternalizer.INSTANCE;
// }
//
// @NotNull
// @Override
// public FileBasedIndex.InputFilter getInputFilter() {
// return file -> "po".equals(file.getExtension());
// }
//
// @Override
// public boolean dependsOnFileContent() {
// return true;
// }
//
// @Override
// public int getVersion() {
// return 1;
// }
// }
| import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.project.Project;
import de.espend.idea.php.drupal.DrupalIcons;
import de.espend.idea.php.drupal.index.GetTextFileIndex;
import fr.adrienbrault.idea.symfony2plugin.stubs.SymfonyProcessors;
import org.jetbrains.annotations.NotNull; | package de.espend.idea.php.drupal.utils;
public class TranslationUtil {
public static void attachGetTextLookupKeys(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) {
for(String phpClassName: SymfonyProcessors.createResult(project, GetTextFileIndex.KEY)) { | // Path: src/de/espend/idea/php/drupal/DrupalIcons.java
// public class DrupalIcons {
// public static final Icon DRUPAL = IconLoader.getIcon("icons/drupal.png");
// }
//
// Path: src/de/espend/idea/php/drupal/index/GetTextFileIndex.java
// public class GetTextFileIndex extends FileBasedIndexExtension<String, Void> {
//
// public static final ID<String, Void> KEY = ID.create("de.espend.idea.php.drupal.gettext");
// private final KeyDescriptor<String> myKeyDescriptor = new EnumeratorStringDescriptor();
//
// @NotNull
// @Override
// public ID<String, Void> getName() {
// return KEY;
// }
//
// @NotNull
// @Override
// public DataIndexer<String, Void, FileContent> getIndexer() {
// return fileContent -> {
// Map<String, Void> msgId = new HashMap<>();
//
// try {
// GettextResourceBundle gettextResourceBundle = new GettextResourceBundle(fileContent.getFile().getInputStream());
// Enumeration<String> tests = gettextResourceBundle.getKeys();
// for(String test: new HashSet<>(Collections.list(tests))) {
// if(StringUtils.isNotBlank(test)) {
// msgId.put(test, null);
// }
// }
// } catch (IOException e) {
// return msgId;
// }
// return msgId;
// };
// }
//
// @NotNull
// @Override
// public KeyDescriptor<String> getKeyDescriptor() {
// return this.myKeyDescriptor;
// }
//
// @NotNull
// @Override
// public DataExternalizer<Void> getValueExternalizer() {
// return VoidDataExternalizer.INSTANCE;
// }
//
// @NotNull
// @Override
// public FileBasedIndex.InputFilter getInputFilter() {
// return file -> "po".equals(file.getExtension());
// }
//
// @Override
// public boolean dependsOnFileContent() {
// return true;
// }
//
// @Override
// public int getVersion() {
// return 1;
// }
// }
// Path: src/de/espend/idea/php/drupal/utils/TranslationUtil.java
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.project.Project;
import de.espend.idea.php.drupal.DrupalIcons;
import de.espend.idea.php.drupal.index.GetTextFileIndex;
import fr.adrienbrault.idea.symfony2plugin.stubs.SymfonyProcessors;
import org.jetbrains.annotations.NotNull;
package de.espend.idea.php.drupal.utils;
public class TranslationUtil {
public static void attachGetTextLookupKeys(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) {
for(String phpClassName: SymfonyProcessors.createResult(project, GetTextFileIndex.KEY)) { | completionResultSet.addElement(LookupElementBuilder.create(phpClassName).withIcon(DrupalIcons.DRUPAL)); |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/completion/YamlCompletionContributor.java | // Path: src/de/espend/idea/php/drupal/DrupalIcons.java
// public class DrupalIcons {
// public static final Icon DRUPAL = IconLoader.getIcon("icons/drupal.png");
// }
//
// Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
| import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.util.ProcessingContext;
import de.espend.idea.php.drupal.DrupalIcons;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.yaml.psi.YAMLDocument; | package de.espend.idea.php.drupal.completion;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class YamlCompletionContributor extends CompletionContributor {
final private static String[] MODULE_KEYS = new String[] {"name", "type", "description", "package", "version", "core", "configure", "dependencies", "required"};
public YamlCompletionContributor() {
extend(
CompletionType.BASIC, PlatformPatterns.psiElement().withParent(PlatformPatterns.psiElement(YAMLDocument.class)).inFile(
PlatformPatterns.psiFile().withName(PlatformPatterns.string().endsWith(".info.yml"))
),
new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
| // Path: src/de/espend/idea/php/drupal/DrupalIcons.java
// public class DrupalIcons {
// public static final Icon DRUPAL = IconLoader.getIcon("icons/drupal.png");
// }
//
// Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
// Path: src/de/espend/idea/php/drupal/completion/YamlCompletionContributor.java
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.util.ProcessingContext;
import de.espend.idea.php.drupal.DrupalIcons;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.yaml.psi.YAMLDocument;
package de.espend.idea.php.drupal.completion;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class YamlCompletionContributor extends CompletionContributor {
final private static String[] MODULE_KEYS = new String[] {"name", "type", "description", "package", "version", "core", "configure", "dependencies", "required"};
public YamlCompletionContributor() {
extend(
CompletionType.BASIC, PlatformPatterns.psiElement().withParent(PlatformPatterns.psiElement(YAMLDocument.class)).inFile(
PlatformPatterns.psiFile().withName(PlatformPatterns.string().endsWith(".info.yml"))
),
new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
| if(!DrupalProjectComponent.isEnabled(completionParameters.getOriginalPosition())) { |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/completion/YamlCompletionContributor.java | // Path: src/de/espend/idea/php/drupal/DrupalIcons.java
// public class DrupalIcons {
// public static final Icon DRUPAL = IconLoader.getIcon("icons/drupal.png");
// }
//
// Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
| import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.util.ProcessingContext;
import de.espend.idea.php.drupal.DrupalIcons;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.yaml.psi.YAMLDocument; | package de.espend.idea.php.drupal.completion;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class YamlCompletionContributor extends CompletionContributor {
final private static String[] MODULE_KEYS = new String[] {"name", "type", "description", "package", "version", "core", "configure", "dependencies", "required"};
public YamlCompletionContributor() {
extend(
CompletionType.BASIC, PlatformPatterns.psiElement().withParent(PlatformPatterns.psiElement(YAMLDocument.class)).inFile(
PlatformPatterns.psiFile().withName(PlatformPatterns.string().endsWith(".info.yml"))
),
new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
if(!DrupalProjectComponent.isEnabled(completionParameters.getOriginalPosition())) {
return;
}
for(String key: MODULE_KEYS) { | // Path: src/de/espend/idea/php/drupal/DrupalIcons.java
// public class DrupalIcons {
// public static final Icon DRUPAL = IconLoader.getIcon("icons/drupal.png");
// }
//
// Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
// Path: src/de/espend/idea/php/drupal/completion/YamlCompletionContributor.java
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.util.ProcessingContext;
import de.espend.idea.php.drupal.DrupalIcons;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.yaml.psi.YAMLDocument;
package de.espend.idea.php.drupal.completion;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class YamlCompletionContributor extends CompletionContributor {
final private static String[] MODULE_KEYS = new String[] {"name", "type", "description", "package", "version", "core", "configure", "dependencies", "required"};
public YamlCompletionContributor() {
extend(
CompletionType.BASIC, PlatformPatterns.psiElement().withParent(PlatformPatterns.psiElement(YAMLDocument.class)).inFile(
PlatformPatterns.psiFile().withName(PlatformPatterns.string().endsWith(".info.yml"))
),
new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
if(!DrupalProjectComponent.isEnabled(completionParameters.getOriginalPosition())) {
return;
}
for(String key: MODULE_KEYS) { | completionResultSet.addElement(LookupElementBuilder.create(key).withIcon(DrupalIcons.DRUPAL)); |
Haehnchen/idea-php-drupal-symfony2-bridge | src/de/espend/idea/php/drupal/linemarker/RouteFormLineMarkerProvider.java | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/IndexUtil.java
// public class IndexUtil {
//
// @NotNull
// public static Collection<PhpClass> getFormClassForId(@NotNull Project project, @NotNull String id) {
// Collection<PhpClass> phpClasses = new ArrayList<>();
//
// for (String key : SymfonyProcessors.createResult(project, ConfigEntityTypeAnnotationIndex.KEY)) {
// if(!id.equals(key)) {
// continue;
// }
//
// for (String value : FileBasedIndex.getInstance().getValues(ConfigEntityTypeAnnotationIndex.KEY, key, GlobalSearchScope.allScope(project))) {
// phpClasses.addAll(PhpElementsUtil.getClassesInterface(project, value));
// }
// }
//
// return phpClasses;
// }
//
// @NotNull
// public static Collection<PsiElement> getMenuForId(@NotNull Project project, @NotNull String text) {
// Collection<VirtualFile> virtualFiles = new ArrayList<>();
//
// FileBasedIndex.getInstance().getFilesWithKey(MenuIndex.KEY, new HashSet<>(Collections.singletonList(text)), virtualFile -> {
// virtualFiles.add(virtualFile);
// return true;
// }, GlobalSearchScope.allScope(project));
//
// Collection<PsiElement> targets = new ArrayList<>();
//
// for (VirtualFile virtualFile : virtualFiles) {
// PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
// if(!(file instanceof YAMLFile)) {
// continue;
// }
//
// ContainerUtil.addIfNotNull(targets, YAMLUtil.getQualifiedKeyInFile((YAMLFile) file, text));
// }
//
// return targets;
// }
//
// @NotNull
// public static Collection<LookupElement> getIndexedKeyLookup(@NotNull Project project, @NotNull ID<String, ?> var1) {
// Collection<LookupElement> lookupElements = new ArrayList<>();
//
// lookupElements.addAll(SymfonyProcessors.createResult(project, var1).stream().map(
// s -> LookupElementBuilder.create(s).withIcon(DrupalIcons.DRUPAL)).collect(Collectors.toList())
// );
//
// return lookupElements;
// }
//
// public static boolean isValidForIndex(@NotNull FileContent inputData, @NotNull PsiFile psiFile) {
//
// String fileName = psiFile.getName();
// if(fileName.startsWith(".") || fileName.endsWith("Test")) {
// return false;
// }
//
// VirtualFile baseDir = inputData.getProject().getBaseDir();
// if(baseDir == null) {
// return false;
// }
//
// // is Test file in path name
// String relativePath = VfsUtil.getRelativePath(inputData.getFile(), baseDir, '/');
// if(relativePath != null && (relativePath.contains("/Test/") || relativePath.contains("/Fixtures/"))) {
// return false;
// }
//
// return true;
// }
// }
| import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.codeInsight.daemon.LineMarkerProvider;
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.IndexUtil;
import fr.adrienbrault.idea.symfony2plugin.Symfony2Icons;
import fr.adrienbrault.idea.symfony2plugin.config.yaml.YamlElementPatternHelper;
import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.psi.YAMLKeyValue;
import org.jetbrains.yaml.psi.YAMLMapping;
import org.jetbrains.yaml.psi.YAMLScalar;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; | package de.espend.idea.php.drupal.linemarker;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class RouteFormLineMarkerProvider implements LineMarkerProvider {
@Nullable
@Override
public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement psiElement) {
return null;
}
@Override
public void collectSlowLineMarkers(@NotNull List<PsiElement> psiElements, @NotNull Collection<LineMarkerInfo> results) {
if(psiElements.size() == 0) {
return;
}
Project project = psiElements.get(0).getProject(); | // Path: src/de/espend/idea/php/drupal/DrupalProjectComponent.java
// public class DrupalProjectComponent {
//
// public static boolean isEnabled(Project project) {
// return Symfony2ProjectComponent.isEnabled(project);
// }
//
// public static boolean isEnabled(@Nullable PsiElement psiElement) {
// return psiElement != null && isEnabled(psiElement.getProject());
// }
//
// }
//
// Path: src/de/espend/idea/php/drupal/utils/IndexUtil.java
// public class IndexUtil {
//
// @NotNull
// public static Collection<PhpClass> getFormClassForId(@NotNull Project project, @NotNull String id) {
// Collection<PhpClass> phpClasses = new ArrayList<>();
//
// for (String key : SymfonyProcessors.createResult(project, ConfigEntityTypeAnnotationIndex.KEY)) {
// if(!id.equals(key)) {
// continue;
// }
//
// for (String value : FileBasedIndex.getInstance().getValues(ConfigEntityTypeAnnotationIndex.KEY, key, GlobalSearchScope.allScope(project))) {
// phpClasses.addAll(PhpElementsUtil.getClassesInterface(project, value));
// }
// }
//
// return phpClasses;
// }
//
// @NotNull
// public static Collection<PsiElement> getMenuForId(@NotNull Project project, @NotNull String text) {
// Collection<VirtualFile> virtualFiles = new ArrayList<>();
//
// FileBasedIndex.getInstance().getFilesWithKey(MenuIndex.KEY, new HashSet<>(Collections.singletonList(text)), virtualFile -> {
// virtualFiles.add(virtualFile);
// return true;
// }, GlobalSearchScope.allScope(project));
//
// Collection<PsiElement> targets = new ArrayList<>();
//
// for (VirtualFile virtualFile : virtualFiles) {
// PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
// if(!(file instanceof YAMLFile)) {
// continue;
// }
//
// ContainerUtil.addIfNotNull(targets, YAMLUtil.getQualifiedKeyInFile((YAMLFile) file, text));
// }
//
// return targets;
// }
//
// @NotNull
// public static Collection<LookupElement> getIndexedKeyLookup(@NotNull Project project, @NotNull ID<String, ?> var1) {
// Collection<LookupElement> lookupElements = new ArrayList<>();
//
// lookupElements.addAll(SymfonyProcessors.createResult(project, var1).stream().map(
// s -> LookupElementBuilder.create(s).withIcon(DrupalIcons.DRUPAL)).collect(Collectors.toList())
// );
//
// return lookupElements;
// }
//
// public static boolean isValidForIndex(@NotNull FileContent inputData, @NotNull PsiFile psiFile) {
//
// String fileName = psiFile.getName();
// if(fileName.startsWith(".") || fileName.endsWith("Test")) {
// return false;
// }
//
// VirtualFile baseDir = inputData.getProject().getBaseDir();
// if(baseDir == null) {
// return false;
// }
//
// // is Test file in path name
// String relativePath = VfsUtil.getRelativePath(inputData.getFile(), baseDir, '/');
// if(relativePath != null && (relativePath.contains("/Test/") || relativePath.contains("/Fixtures/"))) {
// return false;
// }
//
// return true;
// }
// }
// Path: src/de/espend/idea/php/drupal/linemarker/RouteFormLineMarkerProvider.java
import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.codeInsight.daemon.LineMarkerProvider;
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import de.espend.idea.php.drupal.DrupalProjectComponent;
import de.espend.idea.php.drupal.utils.IndexUtil;
import fr.adrienbrault.idea.symfony2plugin.Symfony2Icons;
import fr.adrienbrault.idea.symfony2plugin.config.yaml.YamlElementPatternHelper;
import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.psi.YAMLKeyValue;
import org.jetbrains.yaml.psi.YAMLMapping;
import org.jetbrains.yaml.psi.YAMLScalar;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
package de.espend.idea.php.drupal.linemarker;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class RouteFormLineMarkerProvider implements LineMarkerProvider {
@Nullable
@Override
public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement psiElement) {
return null;
}
@Override
public void collectSlowLineMarkers(@NotNull List<PsiElement> psiElements, @NotNull Collection<LineMarkerInfo> results) {
if(psiElements.size() == 0) {
return;
}
Project project = psiElements.get(0).getProject(); | if(!DrupalProjectComponent.isEnabled(project)) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.