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
|
---|---|---|---|---|---|---|
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/expr/Date.java | // Path: src/main/java/org/psidnell/omnifocus/ConfigParams.java
// public class ConfigParams {
//
// private String dueSoon;
// private String flattenedRootName;
// private String expressionDateFormat;
// private int icsAlarmMinutes;
// private boolean icsAlarm;
// private String icsStart;
// private String icsEnd;
// private boolean icsAllDay;
//
// public void setDueSoon(String dueSoon) {
// this.dueSoon = dueSoon;
// }
//
// public String getDueSoon() {
// return dueSoon;
// }
//
// public void setFlattenedRootName(String name) {
// this.flattenedRootName = name;
// }
//
// public String getFlattenedRootName() {
// return flattenedRootName;
// }
//
// public void setExpressionDateFormat(String format) {
// this.expressionDateFormat = format;
// }
//
// public String getExpressionDateFormat() {
// return expressionDateFormat;
// }
//
// public int getIcsAlarmMinutes() {
// return icsAlarmMinutes;
// }
//
// public void setIcsAlarmMinutes(int icsAlarmMinutes) {
// this.icsAlarmMinutes = icsAlarmMinutes;
// }
//
// public boolean getIcsAlarm() {
// return icsAlarm;
// }
//
// public void setIcsAlarm(boolean icsAlarm) {
// this.icsAlarm = icsAlarm;
// }
//
// public String getIcsStart() {
// return icsStart;
// }
//
// public void setIcsStart(String icsStart) {
// this.icsStart = icsStart;
// }
//
// public String getIcsEnd() {
// return icsEnd;
// }
//
// public void setIcsEnd(String icsEnd) {
// this.icsEnd = icsEnd;
// }
//
// public boolean getIcsAllDay() {
// return icsAllDay;
// }
//
// public void setIcsAllDay(boolean icsAllDay) {
// this.icsAllDay = icsAllDay;
// }
//
// }
| import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.psidnell.omnifocus.ConfigParams; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
/**
* @author psidnell
*
* A wrapper for dates that makes the OGNL expressions more convenient.
*/
public class Date extends ExpressionFunctions implements Comparable<Date> {
private static final SimpleDateFormat ICS_LONG = new SimpleDateFormat("yyyyMMdd'T'HHmm'00Z'");
private static final SimpleDateFormat ICS_SHORT = new SimpleDateFormat("yyyyMMdd");
private java.util.Date date;
private java.util.Date roundedDate;
| // Path: src/main/java/org/psidnell/omnifocus/ConfigParams.java
// public class ConfigParams {
//
// private String dueSoon;
// private String flattenedRootName;
// private String expressionDateFormat;
// private int icsAlarmMinutes;
// private boolean icsAlarm;
// private String icsStart;
// private String icsEnd;
// private boolean icsAllDay;
//
// public void setDueSoon(String dueSoon) {
// this.dueSoon = dueSoon;
// }
//
// public String getDueSoon() {
// return dueSoon;
// }
//
// public void setFlattenedRootName(String name) {
// this.flattenedRootName = name;
// }
//
// public String getFlattenedRootName() {
// return flattenedRootName;
// }
//
// public void setExpressionDateFormat(String format) {
// this.expressionDateFormat = format;
// }
//
// public String getExpressionDateFormat() {
// return expressionDateFormat;
// }
//
// public int getIcsAlarmMinutes() {
// return icsAlarmMinutes;
// }
//
// public void setIcsAlarmMinutes(int icsAlarmMinutes) {
// this.icsAlarmMinutes = icsAlarmMinutes;
// }
//
// public boolean getIcsAlarm() {
// return icsAlarm;
// }
//
// public void setIcsAlarm(boolean icsAlarm) {
// this.icsAlarm = icsAlarm;
// }
//
// public String getIcsStart() {
// return icsStart;
// }
//
// public void setIcsStart(String icsStart) {
// this.icsStart = icsStart;
// }
//
// public String getIcsEnd() {
// return icsEnd;
// }
//
// public void setIcsEnd(String icsEnd) {
// this.icsEnd = icsEnd;
// }
//
// public boolean getIcsAllDay() {
// return icsAllDay;
// }
//
// public void setIcsAllDay(boolean icsAllDay) {
// this.icsAllDay = icsAllDay;
// }
//
// }
// Path: src/main/java/org/psidnell/omnifocus/expr/Date.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.psidnell.omnifocus.ConfigParams;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
/**
* @author psidnell
*
* A wrapper for dates that makes the OGNL expressions more convenient.
*/
public class Date extends ExpressionFunctions implements Comparable<Date> {
private static final SimpleDateFormat ICS_LONG = new SimpleDateFormat("yyyyMMdd'T'HHmm'00Z'");
private static final SimpleDateFormat ICS_SHORT = new SimpleDateFormat("yyyyMMdd");
private java.util.Date date;
private java.util.Date roundedDate;
| public Date(java.util.Date date, ConfigParams config) { |
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/expr/ExprAttributePrinter.java | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/StringUtils.java
// public class StringUtils {
//
// public static String join(Collection<String> data, String delimiter) {
// return join(data, new StringJoiner(delimiter));
// }
//
// public static String join(Collection<String> data, String delimiter, String prefix, String suffix) {
// return join(data, new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(String data[], String delimiter) {
// return join(Arrays.asList(data), new StringJoiner(delimiter));
// }
//
// public static String join(String data[], String delimiter, String prefix, String suffix) {
// return join(Arrays.asList(data), new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(Collection<String> data, StringJoiner sj) {
// data.stream().forEachOrdered((s) -> sj.add(s));
// return sj.toString();
// }
//
// public static String times(String str, int n) {
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < n; i++) {
// result.append(str);
// }
// return result.toString();
// }
// }
| import java.lang.reflect.Method;
import java.util.TreeMap;
import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.util.StringUtils; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
/**
* @author psidnell
*
* Prints help from ExprAttribute annotations in a class.
*/
public class ExprAttributePrinter {
private int maxTypeLen = 0;
private int maxNameAndArgsLen = 0; | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/StringUtils.java
// public class StringUtils {
//
// public static String join(Collection<String> data, String delimiter) {
// return join(data, new StringJoiner(delimiter));
// }
//
// public static String join(Collection<String> data, String delimiter, String prefix, String suffix) {
// return join(data, new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(String data[], String delimiter) {
// return join(Arrays.asList(data), new StringJoiner(delimiter));
// }
//
// public static String join(String data[], String delimiter, String prefix, String suffix) {
// return join(Arrays.asList(data), new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(Collection<String> data, StringJoiner sj) {
// data.stream().forEachOrdered((s) -> sj.add(s));
// return sj.toString();
// }
//
// public static String times(String str, int n) {
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < n; i++) {
// result.append(str);
// }
// return result.toString();
// }
// }
// Path: src/main/java/org/psidnell/omnifocus/expr/ExprAttributePrinter.java
import java.lang.reflect.Method;
import java.util.TreeMap;
import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.util.StringUtils;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
/**
* @author psidnell
*
* Prints help from ExprAttribute annotations in a class.
*/
public class ExprAttributePrinter {
private int maxTypeLen = 0;
private int maxNameAndArgsLen = 0; | private Class<? extends Node>[] classes; |
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/expr/ExprAttributePrinter.java | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/StringUtils.java
// public class StringUtils {
//
// public static String join(Collection<String> data, String delimiter) {
// return join(data, new StringJoiner(delimiter));
// }
//
// public static String join(Collection<String> data, String delimiter, String prefix, String suffix) {
// return join(data, new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(String data[], String delimiter) {
// return join(Arrays.asList(data), new StringJoiner(delimiter));
// }
//
// public static String join(String data[], String delimiter, String prefix, String suffix) {
// return join(Arrays.asList(data), new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(Collection<String> data, StringJoiner sj) {
// data.stream().forEachOrdered((s) -> sj.add(s));
// return sj.toString();
// }
//
// public static String times(String str, int n) {
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < n; i++) {
// result.append(str);
// }
// return result.toString();
// }
// }
| import java.lang.reflect.Method;
import java.util.TreeMap;
import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.util.StringUtils; | String type = m.getReturnType().getSimpleName().toLowerCase();
String nameAndArgs = name + processArgs(attrib);
v.process(type, nameAndArgs, attrib.help());
}
}
}
private static String padL(String val, int pad) {
String result = val;
while (result.length() < pad) {
result = " " + result;
}
return result;
}
private static String padR(String val, int pad) {
String result = val;
while (result.length() < pad) {
result = result + " ";
}
return result;
}
private static String processArgs(ExprAttribute attrib) {
if (attrib.args().length == 0) {
return "";
}
else { | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/StringUtils.java
// public class StringUtils {
//
// public static String join(Collection<String> data, String delimiter) {
// return join(data, new StringJoiner(delimiter));
// }
//
// public static String join(Collection<String> data, String delimiter, String prefix, String suffix) {
// return join(data, new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(String data[], String delimiter) {
// return join(Arrays.asList(data), new StringJoiner(delimiter));
// }
//
// public static String join(String data[], String delimiter, String prefix, String suffix) {
// return join(Arrays.asList(data), new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(Collection<String> data, StringJoiner sj) {
// data.stream().forEachOrdered((s) -> sj.add(s));
// return sj.toString();
// }
//
// public static String times(String str, int n) {
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < n; i++) {
// result.append(str);
// }
// return result.toString();
// }
// }
// Path: src/main/java/org/psidnell/omnifocus/expr/ExprAttributePrinter.java
import java.lang.reflect.Method;
import java.util.TreeMap;
import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.util.StringUtils;
String type = m.getReturnType().getSimpleName().toLowerCase();
String nameAndArgs = name + processArgs(attrib);
v.process(type, nameAndArgs, attrib.help());
}
}
}
private static String padL(String val, int pad) {
String result = val;
while (result.length() < pad) {
result = " " + result;
}
return result;
}
private static String padR(String val, int pad) {
String result = val;
while (result.length() < pad) {
result = result + " ";
}
return result;
}
private static String processArgs(ExprAttribute attrib) {
if (attrib.args().length == 0) {
return "";
}
else { | return StringUtils.join(attrib.args(), ",", " (",")"); |
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/sqlite/SQLiteClassDescriptor.java | // Path: src/main/java/org/psidnell/omnifocus/model/NodeFactory.java
// public class NodeFactory {
//
// private ConfigParams config;
//
// @SuppressWarnings({"unchecked", "deprecation"})
// public <T> T create(String name, Class<T> clazz) {
// Node node;
// switch (clazz.getSimpleName()) {
// case "ProjectInfo":
// // Not really a node
// return (T) new ProjectInfo();
// case "Task":
// node = new Task();
// break;
// case "Project":
// node = new Project();
// break;
// case "Folder":
// node = new Folder();
// break;
// case "Context":
// node = new Context();
// break;
// default:
// throw new IllegalArgumentException("" + clazz);
// }
//
// initialise(node);
//
// return (T) node;
// }
//
// public Task createTask(String name) {
// @SuppressWarnings("deprecation")
// Task node = new Task();
// node.setName(name);
// initialise(node);
// return node;
// }
//
// public Folder createFolder(String name) {
// @SuppressWarnings("deprecation")
// Folder node = new Folder();
// node.setName(name);
// initialise(node);
// return node;
// }
//
// public Project createProject(String name) {
// @SuppressWarnings("deprecation")
// Project node = new Project();
// node.setName(name);
// initialise(node);
// return node;
// }
//
// public Project createProject(ProjectInfo pi, Task rootTask) {
// @SuppressWarnings("deprecation")
// Project node = new Project(pi, rootTask);
// initialise(node);
// return node;
// }
//
// public Context createContext(String name) {
// @SuppressWarnings("deprecation")
// Context node = new Context();
// node.setName(name);
// initialise(node);
// return node;
// }
//
// public void initialise(Node node) {
// node.setConfigParams(config);
// }
//
// public void setConfigParams(ConfigParams config) {
// this.config = config;
// }
// }
| import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import org.psidnell.omnifocus.model.NodeFactory; | if (methodName.startsWith("is")) {
propName = propertyName("is", m.getName());
setterName = m.getName().replaceFirst("^is", "set");
} else if (methodName.startsWith("get")) {
propName = propertyName("get", m.getName());
setterName = m.getName().replaceFirst("^get", "set");
} else {
throw new IllegalArgumentException("bad property accessor: " + m);
}
if (p.name().length() != 0) {
propName = p.name();
}
Method setter = clazz.getMethod(setterName, m.getReturnType());
columns.append(columns.length() != 0 ? ',' : "");
columns.append(propName);
SQLITEPropertyDescriptor pd = new SQLITEPropertyDescriptor(propName, setter, m.getReturnType());
properties.add(pd);
}
}
columnsForSelect = columns.toString();
}
private String propertyName(String prefix, String methodName) {
int prefixLen = prefix.length();
return Character.toLowerCase(methodName.charAt(prefixLen)) + methodName.substring(prefixLen + 1);
}
| // Path: src/main/java/org/psidnell/omnifocus/model/NodeFactory.java
// public class NodeFactory {
//
// private ConfigParams config;
//
// @SuppressWarnings({"unchecked", "deprecation"})
// public <T> T create(String name, Class<T> clazz) {
// Node node;
// switch (clazz.getSimpleName()) {
// case "ProjectInfo":
// // Not really a node
// return (T) new ProjectInfo();
// case "Task":
// node = new Task();
// break;
// case "Project":
// node = new Project();
// break;
// case "Folder":
// node = new Folder();
// break;
// case "Context":
// node = new Context();
// break;
// default:
// throw new IllegalArgumentException("" + clazz);
// }
//
// initialise(node);
//
// return (T) node;
// }
//
// public Task createTask(String name) {
// @SuppressWarnings("deprecation")
// Task node = new Task();
// node.setName(name);
// initialise(node);
// return node;
// }
//
// public Folder createFolder(String name) {
// @SuppressWarnings("deprecation")
// Folder node = new Folder();
// node.setName(name);
// initialise(node);
// return node;
// }
//
// public Project createProject(String name) {
// @SuppressWarnings("deprecation")
// Project node = new Project();
// node.setName(name);
// initialise(node);
// return node;
// }
//
// public Project createProject(ProjectInfo pi, Task rootTask) {
// @SuppressWarnings("deprecation")
// Project node = new Project(pi, rootTask);
// initialise(node);
// return node;
// }
//
// public Context createContext(String name) {
// @SuppressWarnings("deprecation")
// Context node = new Context();
// node.setName(name);
// initialise(node);
// return node;
// }
//
// public void initialise(Node node) {
// node.setConfigParams(config);
// }
//
// public void setConfigParams(ConfigParams config) {
// this.config = config;
// }
// }
// Path: src/main/java/org/psidnell/omnifocus/sqlite/SQLiteClassDescriptor.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import org.psidnell.omnifocus.model.NodeFactory;
if (methodName.startsWith("is")) {
propName = propertyName("is", m.getName());
setterName = m.getName().replaceFirst("^is", "set");
} else if (methodName.startsWith("get")) {
propName = propertyName("get", m.getName());
setterName = m.getName().replaceFirst("^get", "set");
} else {
throw new IllegalArgumentException("bad property accessor: " + m);
}
if (p.name().length() != 0) {
propName = p.name();
}
Method setter = clazz.getMethod(setterName, m.getReturnType());
columns.append(columns.length() != 0 ? ',' : "");
columns.append(propName);
SQLITEPropertyDescriptor pd = new SQLITEPropertyDescriptor(propName, setter, m.getReturnType());
properties.add(pd);
}
}
columnsForSelect = columns.toString();
}
private String propertyName(String prefix, String methodName) {
int prefixLen = prefix.length();
return Character.toLowerCase(methodName.charAt(prefixLen)) + methodName.substring(prefixLen + 1);
}
| public LinkedList<T> load(ResultSet rs, NodeFactory nodeFactory) throws SQLException, InvocationTargetException, InstantiationException, |
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/model/Node.java | // Path: src/main/java/org/psidnell/omnifocus/ConfigParams.java
// public class ConfigParams {
//
// private String dueSoon;
// private String flattenedRootName;
// private String expressionDateFormat;
// private int icsAlarmMinutes;
// private boolean icsAlarm;
// private String icsStart;
// private String icsEnd;
// private boolean icsAllDay;
//
// public void setDueSoon(String dueSoon) {
// this.dueSoon = dueSoon;
// }
//
// public String getDueSoon() {
// return dueSoon;
// }
//
// public void setFlattenedRootName(String name) {
// this.flattenedRootName = name;
// }
//
// public String getFlattenedRootName() {
// return flattenedRootName;
// }
//
// public void setExpressionDateFormat(String format) {
// this.expressionDateFormat = format;
// }
//
// public String getExpressionDateFormat() {
// return expressionDateFormat;
// }
//
// public int getIcsAlarmMinutes() {
// return icsAlarmMinutes;
// }
//
// public void setIcsAlarmMinutes(int icsAlarmMinutes) {
// this.icsAlarmMinutes = icsAlarmMinutes;
// }
//
// public boolean getIcsAlarm() {
// return icsAlarm;
// }
//
// public void setIcsAlarm(boolean icsAlarm) {
// this.icsAlarm = icsAlarm;
// }
//
// public String getIcsStart() {
// return icsStart;
// }
//
// public void setIcsStart(String icsStart) {
// this.icsStart = icsStart;
// }
//
// public String getIcsEnd() {
// return icsEnd;
// }
//
// public void setIcsEnd(String icsEnd) {
// this.icsEnd = icsEnd;
// }
//
// public boolean getIcsAllDay() {
// return icsAllDay;
// }
//
// public void setIcsAllDay(boolean icsAllDay) {
// this.icsAllDay = icsAllDay;
// }
//
// }
| import org.psidnell.omnifocus.ConfigParams; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.model;
/**
* @author psidnell
*
* Root node interface.
*/
public interface Node {
String getName();
void setName(String name);
String getId();
void setId(String id);
int getRank();
void setRank(int rank);
String getType();
boolean isRoot();
boolean isMarked();
void setMarked(boolean marked);
void cascadeMarked();
| // Path: src/main/java/org/psidnell/omnifocus/ConfigParams.java
// public class ConfigParams {
//
// private String dueSoon;
// private String flattenedRootName;
// private String expressionDateFormat;
// private int icsAlarmMinutes;
// private boolean icsAlarm;
// private String icsStart;
// private String icsEnd;
// private boolean icsAllDay;
//
// public void setDueSoon(String dueSoon) {
// this.dueSoon = dueSoon;
// }
//
// public String getDueSoon() {
// return dueSoon;
// }
//
// public void setFlattenedRootName(String name) {
// this.flattenedRootName = name;
// }
//
// public String getFlattenedRootName() {
// return flattenedRootName;
// }
//
// public void setExpressionDateFormat(String format) {
// this.expressionDateFormat = format;
// }
//
// public String getExpressionDateFormat() {
// return expressionDateFormat;
// }
//
// public int getIcsAlarmMinutes() {
// return icsAlarmMinutes;
// }
//
// public void setIcsAlarmMinutes(int icsAlarmMinutes) {
// this.icsAlarmMinutes = icsAlarmMinutes;
// }
//
// public boolean getIcsAlarm() {
// return icsAlarm;
// }
//
// public void setIcsAlarm(boolean icsAlarm) {
// this.icsAlarm = icsAlarm;
// }
//
// public String getIcsStart() {
// return icsStart;
// }
//
// public void setIcsStart(String icsStart) {
// this.icsStart = icsStart;
// }
//
// public String getIcsEnd() {
// return icsEnd;
// }
//
// public void setIcsEnd(String icsEnd) {
// this.icsEnd = icsEnd;
// }
//
// public boolean getIcsAllDay() {
// return icsAllDay;
// }
//
// public void setIcsAllDay(boolean icsAllDay) {
// this.icsAllDay = icsAllDay;
// }
//
// }
// Path: src/main/java/org/psidnell/omnifocus/model/Node.java
import org.psidnell.omnifocus.ConfigParams;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.model;
/**
* @author psidnell
*
* Root node interface.
*/
public interface Node {
String getName();
void setName(String name);
String getId();
void setId(String id);
int getRank();
void setRank(int rank);
String getType();
boolean isRoot();
boolean isMarked();
void setMarked(boolean marked);
void cascadeMarked();
| void setConfigParams(ConfigParams config); |
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/expr/ExprMarkVisitor.java | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/visitor/VisitorDescriptor.java
// public class VisitorDescriptor {
// private boolean visitTasks = false;
// private boolean visitProjects = false;
// private boolean visitContexts = false;
// private boolean filterTasks = false;
// private boolean filterProjects = false;
// private boolean filterContexts = false;
// private boolean visitFolders = false;
// private boolean filterFolders;
//
// public VisitorDescriptor visitAll() {
// visitTasks = true;
// visitContexts = true;
// visitProjects = true;
// visitFolders = true;
// return this;
// }
//
// public VisitorDescriptor filterAll() {
// filterTasks = true;
// filterContexts = true;
// filterProjects = true;
// filterFolders = true;
// return this;
// }
//
// @SafeVarargs
// public final VisitorDescriptor visit(Class<? extends NodeImpl>... classes) {
// for (Class<? extends NodeImpl> clazz : classes) {
// switch (clazz.getSimpleName()) {
// case "Folder":
// visitFolders = true;
// break;
// case "Project":
// visitProjects = true;
// break;
// case "Task":
// visitTasks = true;
// break;
// case "Context":
// visitContexts = true;
// break;
// default:
// break;
// }
// }
// return this;
// }
//
// @SafeVarargs
// public final VisitorDescriptor filter(Class<? extends NodeImpl>... classes) {
// for (Class<? extends NodeImpl> clazz : classes) {
// switch (clazz.getSimpleName()) {
// case "Folder":
// filterFolders = true;
// break;
// case "Project":
// filterProjects = true;
// break;
// case "Task":
// filterTasks = true;
// break;
// case "Context":
// filterContexts = true;
// break;
// default:
// break;
// }
// }
// return this;
// }
//
// public boolean getFoldersTasks() {
// return visitTasks;
// }
//
// public boolean getVisitTasks() {
// return visitTasks;
// }
//
// public boolean getVisitProjects() {
// return visitProjects;
// }
//
// public boolean getVisitContexts() {
// return visitContexts;
// }
//
// public boolean getVisitFolders() {
// return visitFolders;
// }
//
// public boolean getFilterTasks() {
// return filterTasks;
// }
//
// public boolean getFilterProjects() {
// return filterProjects;
// }
//
// public boolean getFilterContexts() {
// return filterContexts;
// }
//
// public boolean getFilterFolders() {
// return filterFolders;
// }
// }
| import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.visitor.VisitorDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
/**
* @author psidnell
*
* Traverses the node tree including only those nodes where the OGNL expression evaluates
* true.
*/
public class ExprMarkVisitor extends ExprVisitor {
private static final Logger LOGGER = LoggerFactory.getLogger(ExprMarkVisitor.class);
private boolean includeMode = true;
| // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/visitor/VisitorDescriptor.java
// public class VisitorDescriptor {
// private boolean visitTasks = false;
// private boolean visitProjects = false;
// private boolean visitContexts = false;
// private boolean filterTasks = false;
// private boolean filterProjects = false;
// private boolean filterContexts = false;
// private boolean visitFolders = false;
// private boolean filterFolders;
//
// public VisitorDescriptor visitAll() {
// visitTasks = true;
// visitContexts = true;
// visitProjects = true;
// visitFolders = true;
// return this;
// }
//
// public VisitorDescriptor filterAll() {
// filterTasks = true;
// filterContexts = true;
// filterProjects = true;
// filterFolders = true;
// return this;
// }
//
// @SafeVarargs
// public final VisitorDescriptor visit(Class<? extends NodeImpl>... classes) {
// for (Class<? extends NodeImpl> clazz : classes) {
// switch (clazz.getSimpleName()) {
// case "Folder":
// visitFolders = true;
// break;
// case "Project":
// visitProjects = true;
// break;
// case "Task":
// visitTasks = true;
// break;
// case "Context":
// visitContexts = true;
// break;
// default:
// break;
// }
// }
// return this;
// }
//
// @SafeVarargs
// public final VisitorDescriptor filter(Class<? extends NodeImpl>... classes) {
// for (Class<? extends NodeImpl> clazz : classes) {
// switch (clazz.getSimpleName()) {
// case "Folder":
// filterFolders = true;
// break;
// case "Project":
// filterProjects = true;
// break;
// case "Task":
// filterTasks = true;
// break;
// case "Context":
// filterContexts = true;
// break;
// default:
// break;
// }
// }
// return this;
// }
//
// public boolean getFoldersTasks() {
// return visitTasks;
// }
//
// public boolean getVisitTasks() {
// return visitTasks;
// }
//
// public boolean getVisitProjects() {
// return visitProjects;
// }
//
// public boolean getVisitContexts() {
// return visitContexts;
// }
//
// public boolean getVisitFolders() {
// return visitFolders;
// }
//
// public boolean getFilterTasks() {
// return filterTasks;
// }
//
// public boolean getFilterProjects() {
// return filterProjects;
// }
//
// public boolean getFilterContexts() {
// return filterContexts;
// }
//
// public boolean getFilterFolders() {
// return filterFolders;
// }
// }
// Path: src/main/java/org/psidnell/omnifocus/expr/ExprMarkVisitor.java
import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.visitor.VisitorDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
/**
* @author psidnell
*
* Traverses the node tree including only those nodes where the OGNL expression evaluates
* true.
*/
public class ExprMarkVisitor extends ExprVisitor {
private static final Logger LOGGER = LoggerFactory.getLogger(ExprMarkVisitor.class);
private boolean includeMode = true;
| public ExprMarkVisitor(String expr, boolean includeMode, VisitorDescriptor visitWhat, |
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/expr/ExprMarkVisitor.java | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/visitor/VisitorDescriptor.java
// public class VisitorDescriptor {
// private boolean visitTasks = false;
// private boolean visitProjects = false;
// private boolean visitContexts = false;
// private boolean filterTasks = false;
// private boolean filterProjects = false;
// private boolean filterContexts = false;
// private boolean visitFolders = false;
// private boolean filterFolders;
//
// public VisitorDescriptor visitAll() {
// visitTasks = true;
// visitContexts = true;
// visitProjects = true;
// visitFolders = true;
// return this;
// }
//
// public VisitorDescriptor filterAll() {
// filterTasks = true;
// filterContexts = true;
// filterProjects = true;
// filterFolders = true;
// return this;
// }
//
// @SafeVarargs
// public final VisitorDescriptor visit(Class<? extends NodeImpl>... classes) {
// for (Class<? extends NodeImpl> clazz : classes) {
// switch (clazz.getSimpleName()) {
// case "Folder":
// visitFolders = true;
// break;
// case "Project":
// visitProjects = true;
// break;
// case "Task":
// visitTasks = true;
// break;
// case "Context":
// visitContexts = true;
// break;
// default:
// break;
// }
// }
// return this;
// }
//
// @SafeVarargs
// public final VisitorDescriptor filter(Class<? extends NodeImpl>... classes) {
// for (Class<? extends NodeImpl> clazz : classes) {
// switch (clazz.getSimpleName()) {
// case "Folder":
// filterFolders = true;
// break;
// case "Project":
// filterProjects = true;
// break;
// case "Task":
// filterTasks = true;
// break;
// case "Context":
// filterContexts = true;
// break;
// default:
// break;
// }
// }
// return this;
// }
//
// public boolean getFoldersTasks() {
// return visitTasks;
// }
//
// public boolean getVisitTasks() {
// return visitTasks;
// }
//
// public boolean getVisitProjects() {
// return visitProjects;
// }
//
// public boolean getVisitContexts() {
// return visitContexts;
// }
//
// public boolean getVisitFolders() {
// return visitFolders;
// }
//
// public boolean getFilterTasks() {
// return filterTasks;
// }
//
// public boolean getFilterProjects() {
// return filterProjects;
// }
//
// public boolean getFilterContexts() {
// return filterContexts;
// }
//
// public boolean getFilterFolders() {
// return filterFolders;
// }
// }
| import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.visitor.VisitorDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
/**
* @author psidnell
*
* Traverses the node tree including only those nodes where the OGNL expression evaluates
* true.
*/
public class ExprMarkVisitor extends ExprVisitor {
private static final Logger LOGGER = LoggerFactory.getLogger(ExprMarkVisitor.class);
private boolean includeMode = true;
public ExprMarkVisitor(String expr, boolean includeMode, VisitorDescriptor visitWhat,
VisitorDescriptor applyToWhat) {
super(expr, visitWhat, applyToWhat);
this.includeMode = includeMode;
}
@Override | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/visitor/VisitorDescriptor.java
// public class VisitorDescriptor {
// private boolean visitTasks = false;
// private boolean visitProjects = false;
// private boolean visitContexts = false;
// private boolean filterTasks = false;
// private boolean filterProjects = false;
// private boolean filterContexts = false;
// private boolean visitFolders = false;
// private boolean filterFolders;
//
// public VisitorDescriptor visitAll() {
// visitTasks = true;
// visitContexts = true;
// visitProjects = true;
// visitFolders = true;
// return this;
// }
//
// public VisitorDescriptor filterAll() {
// filterTasks = true;
// filterContexts = true;
// filterProjects = true;
// filterFolders = true;
// return this;
// }
//
// @SafeVarargs
// public final VisitorDescriptor visit(Class<? extends NodeImpl>... classes) {
// for (Class<? extends NodeImpl> clazz : classes) {
// switch (clazz.getSimpleName()) {
// case "Folder":
// visitFolders = true;
// break;
// case "Project":
// visitProjects = true;
// break;
// case "Task":
// visitTasks = true;
// break;
// case "Context":
// visitContexts = true;
// break;
// default:
// break;
// }
// }
// return this;
// }
//
// @SafeVarargs
// public final VisitorDescriptor filter(Class<? extends NodeImpl>... classes) {
// for (Class<? extends NodeImpl> clazz : classes) {
// switch (clazz.getSimpleName()) {
// case "Folder":
// filterFolders = true;
// break;
// case "Project":
// filterProjects = true;
// break;
// case "Task":
// filterTasks = true;
// break;
// case "Context":
// filterContexts = true;
// break;
// default:
// break;
// }
// }
// return this;
// }
//
// public boolean getFoldersTasks() {
// return visitTasks;
// }
//
// public boolean getVisitTasks() {
// return visitTasks;
// }
//
// public boolean getVisitProjects() {
// return visitProjects;
// }
//
// public boolean getVisitContexts() {
// return visitContexts;
// }
//
// public boolean getVisitFolders() {
// return visitFolders;
// }
//
// public boolean getFilterTasks() {
// return filterTasks;
// }
//
// public boolean getFilterProjects() {
// return filterProjects;
// }
//
// public boolean getFilterContexts() {
// return filterContexts;
// }
//
// public boolean getFilterFolders() {
// return filterFolders;
// }
// }
// Path: src/main/java/org/psidnell/omnifocus/expr/ExprMarkVisitor.java
import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.visitor.VisitorDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
/**
* @author psidnell
*
* Traverses the node tree including only those nodes where the OGNL expression evaluates
* true.
*/
public class ExprMarkVisitor extends ExprVisitor {
private static final Logger LOGGER = LoggerFactory.getLogger(ExprMarkVisitor.class);
private boolean includeMode = true;
public ExprMarkVisitor(String expr, boolean includeMode, VisitorDescriptor visitWhat,
VisitorDescriptor applyToWhat) {
super(expr, visitWhat, applyToWhat);
this.includeMode = includeMode;
}
@Override | protected void evaluate(Node node) { |
psidnell/ofexport2 | src/test/java/org/psidnell/omnifocus/model/ContextTest.java | // Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java
// public class ApplicationContextFactory {
//
// public static final String CONFIG_XML = "/config.xml";
// private static final String CONFIG_PROPERTIES = "/config.properties";
//
// public static ApplicationContext getContext() {
// return new ClassPathXmlApplicationContext(CONFIG_XML);
// }
//
// public static Properties getConfigProperties() throws IOException {
// try (
// InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) {
// if (in == null) {
// throw new IOException("config not found");
// }
// Properties config = new Properties();
// config.load(in);
// return config;
// }
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.psidnell.omnifocus.ApplicationContextFactory;
import org.springframework.context.ApplicationContext; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.model;
public class ContextTest {
private NodeFactory nodeFactory;
@Before
public void setUp () { | // Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java
// public class ApplicationContextFactory {
//
// public static final String CONFIG_XML = "/config.xml";
// private static final String CONFIG_PROPERTIES = "/config.properties";
//
// public static ApplicationContext getContext() {
// return new ClassPathXmlApplicationContext(CONFIG_XML);
// }
//
// public static Properties getConfigProperties() throws IOException {
// try (
// InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) {
// if (in == null) {
// throw new IOException("config not found");
// }
// Properties config = new Properties();
// config.load(in);
// return config;
// }
// }
// }
// Path: src/test/java/org/psidnell/omnifocus/model/ContextTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.psidnell.omnifocus.ApplicationContextFactory;
import org.springframework.context.ApplicationContext;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.model;
public class ContextTest {
private NodeFactory nodeFactory;
@Before
public void setUp () { | ApplicationContext appContext = ApplicationContextFactory.getContext(); |
psidnell/ofexport2 | src/test/java/org/psidnell/omnifocus/model/DataCacheTest.java | // Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java
// public class ApplicationContextFactory {
//
// public static final String CONFIG_XML = "/config.xml";
// private static final String CONFIG_PROPERTIES = "/config.properties";
//
// public static ApplicationContext getContext() {
// return new ClassPathXmlApplicationContext(CONFIG_XML);
// }
//
// public static Properties getConfigProperties() throws IOException {
// try (
// InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) {
// if (in == null) {
// throw new IOException("config not found");
// }
// Properties config = new Properties();
// config.load(in);
// return config;
// }
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.psidnell.omnifocus.ApplicationContextFactory;
import org.springframework.context.ApplicationContext; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.model;
public class DataCacheTest {
private NodeFactory nodeFactory;
@Before
public void setUp () { | // Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java
// public class ApplicationContextFactory {
//
// public static final String CONFIG_XML = "/config.xml";
// private static final String CONFIG_PROPERTIES = "/config.properties";
//
// public static ApplicationContext getContext() {
// return new ClassPathXmlApplicationContext(CONFIG_XML);
// }
//
// public static Properties getConfigProperties() throws IOException {
// try (
// InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) {
// if (in == null) {
// throw new IOException("config not found");
// }
// Properties config = new Properties();
// config.load(in);
// return config;
// }
// }
// }
// Path: src/test/java/org/psidnell/omnifocus/model/DataCacheTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.psidnell.omnifocus.ApplicationContextFactory;
import org.springframework.context.ApplicationContext;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.model;
public class DataCacheTest {
private NodeFactory nodeFactory;
@Before
public void setUp () { | ApplicationContext appContext = ApplicationContextFactory.getContext(); |
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/model/CommonProjectAndTaskAttributes.java | // Path: src/main/java/org/psidnell/omnifocus/ConfigParams.java
// public class ConfigParams {
//
// private String dueSoon;
// private String flattenedRootName;
// private String expressionDateFormat;
// private int icsAlarmMinutes;
// private boolean icsAlarm;
// private String icsStart;
// private String icsEnd;
// private boolean icsAllDay;
//
// public void setDueSoon(String dueSoon) {
// this.dueSoon = dueSoon;
// }
//
// public String getDueSoon() {
// return dueSoon;
// }
//
// public void setFlattenedRootName(String name) {
// this.flattenedRootName = name;
// }
//
// public String getFlattenedRootName() {
// return flattenedRootName;
// }
//
// public void setExpressionDateFormat(String format) {
// this.expressionDateFormat = format;
// }
//
// public String getExpressionDateFormat() {
// return expressionDateFormat;
// }
//
// public int getIcsAlarmMinutes() {
// return icsAlarmMinutes;
// }
//
// public void setIcsAlarmMinutes(int icsAlarmMinutes) {
// this.icsAlarmMinutes = icsAlarmMinutes;
// }
//
// public boolean getIcsAlarm() {
// return icsAlarm;
// }
//
// public void setIcsAlarm(boolean icsAlarm) {
// this.icsAlarm = icsAlarm;
// }
//
// public String getIcsStart() {
// return icsStart;
// }
//
// public void setIcsStart(String icsStart) {
// this.icsStart = icsStart;
// }
//
// public String getIcsEnd() {
// return icsEnd;
// }
//
// public void setIcsEnd(String icsEnd) {
// this.icsEnd = icsEnd;
// }
//
// public boolean getIcsAllDay() {
// return icsAllDay;
// }
//
// public void setIcsAllDay(boolean icsAllDay) {
// this.icsAllDay = icsAllDay;
// }
//
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/StringUtils.java
// public class StringUtils {
//
// public static String join(Collection<String> data, String delimiter) {
// return join(data, new StringJoiner(delimiter));
// }
//
// public static String join(Collection<String> data, String delimiter, String prefix, String suffix) {
// return join(data, new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(String data[], String delimiter) {
// return join(Arrays.asList(data), new StringJoiner(delimiter));
// }
//
// public static String join(String data[], String delimiter, String prefix, String suffix) {
// return join(Arrays.asList(data), new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(Collection<String> data, StringJoiner sj) {
// data.stream().forEachOrdered((s) -> sj.add(s));
// return sj.toString();
// }
//
// public static String times(String str, int n) {
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < n; i++) {
// result.append(str);
// }
// return result.toString();
// }
// }
| import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import org.psidnell.omnifocus.ConfigParams;
import org.psidnell.omnifocus.expr.ExprAttribute;
import org.psidnell.omnifocus.sqlite.SQLiteProperty;
import org.psidnell.omnifocus.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonIgnore; |
@JsonIgnore
@ExprAttribute(help = "item is not flagged.")
public boolean isUnflagged() {
return !flagged;
}
@SQLiteProperty
@ExprAttribute(help = "estimated minutes.")
public Integer getEstimatedMinutes() {
return estimatedMinutes;
}
public void setEstimatedMinutes(Integer estimatedMinutes) {
this.estimatedMinutes = estimatedMinutes == null ? -1 : estimatedMinutes;
}
@Override
@JsonIgnore
public List<ContextHierarchyNode> getContextPath() {
return getContextPath(context);
}
public String formatNote(int depth, String indent) {
return formatNote(depth, indent, "");
}
public String formatNote(int depth, String indent, String lineSuffix) {
String[] lines = note.replaceAll("\r", "").split("\n");
String eol = lineSuffix + "\n"; | // Path: src/main/java/org/psidnell/omnifocus/ConfigParams.java
// public class ConfigParams {
//
// private String dueSoon;
// private String flattenedRootName;
// private String expressionDateFormat;
// private int icsAlarmMinutes;
// private boolean icsAlarm;
// private String icsStart;
// private String icsEnd;
// private boolean icsAllDay;
//
// public void setDueSoon(String dueSoon) {
// this.dueSoon = dueSoon;
// }
//
// public String getDueSoon() {
// return dueSoon;
// }
//
// public void setFlattenedRootName(String name) {
// this.flattenedRootName = name;
// }
//
// public String getFlattenedRootName() {
// return flattenedRootName;
// }
//
// public void setExpressionDateFormat(String format) {
// this.expressionDateFormat = format;
// }
//
// public String getExpressionDateFormat() {
// return expressionDateFormat;
// }
//
// public int getIcsAlarmMinutes() {
// return icsAlarmMinutes;
// }
//
// public void setIcsAlarmMinutes(int icsAlarmMinutes) {
// this.icsAlarmMinutes = icsAlarmMinutes;
// }
//
// public boolean getIcsAlarm() {
// return icsAlarm;
// }
//
// public void setIcsAlarm(boolean icsAlarm) {
// this.icsAlarm = icsAlarm;
// }
//
// public String getIcsStart() {
// return icsStart;
// }
//
// public void setIcsStart(String icsStart) {
// this.icsStart = icsStart;
// }
//
// public String getIcsEnd() {
// return icsEnd;
// }
//
// public void setIcsEnd(String icsEnd) {
// this.icsEnd = icsEnd;
// }
//
// public boolean getIcsAllDay() {
// return icsAllDay;
// }
//
// public void setIcsAllDay(boolean icsAllDay) {
// this.icsAllDay = icsAllDay;
// }
//
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/StringUtils.java
// public class StringUtils {
//
// public static String join(Collection<String> data, String delimiter) {
// return join(data, new StringJoiner(delimiter));
// }
//
// public static String join(Collection<String> data, String delimiter, String prefix, String suffix) {
// return join(data, new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(String data[], String delimiter) {
// return join(Arrays.asList(data), new StringJoiner(delimiter));
// }
//
// public static String join(String data[], String delimiter, String prefix, String suffix) {
// return join(Arrays.asList(data), new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(Collection<String> data, StringJoiner sj) {
// data.stream().forEachOrdered((s) -> sj.add(s));
// return sj.toString();
// }
//
// public static String times(String str, int n) {
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < n; i++) {
// result.append(str);
// }
// return result.toString();
// }
// }
// Path: src/main/java/org/psidnell/omnifocus/model/CommonProjectAndTaskAttributes.java
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import org.psidnell.omnifocus.ConfigParams;
import org.psidnell.omnifocus.expr.ExprAttribute;
import org.psidnell.omnifocus.sqlite.SQLiteProperty;
import org.psidnell.omnifocus.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonIgnore;
@JsonIgnore
@ExprAttribute(help = "item is not flagged.")
public boolean isUnflagged() {
return !flagged;
}
@SQLiteProperty
@ExprAttribute(help = "estimated minutes.")
public Integer getEstimatedMinutes() {
return estimatedMinutes;
}
public void setEstimatedMinutes(Integer estimatedMinutes) {
this.estimatedMinutes = estimatedMinutes == null ? -1 : estimatedMinutes;
}
@Override
@JsonIgnore
public List<ContextHierarchyNode> getContextPath() {
return getContextPath(context);
}
public String formatNote(int depth, String indent) {
return formatNote(depth, indent, "");
}
public String formatNote(int depth, String indent, String lineSuffix) {
String[] lines = note.replaceAll("\r", "").split("\n");
String eol = lineSuffix + "\n"; | String indentChars = StringUtils.times(indent, depth); |
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/model/CommonProjectAndTaskAttributes.java | // Path: src/main/java/org/psidnell/omnifocus/ConfigParams.java
// public class ConfigParams {
//
// private String dueSoon;
// private String flattenedRootName;
// private String expressionDateFormat;
// private int icsAlarmMinutes;
// private boolean icsAlarm;
// private String icsStart;
// private String icsEnd;
// private boolean icsAllDay;
//
// public void setDueSoon(String dueSoon) {
// this.dueSoon = dueSoon;
// }
//
// public String getDueSoon() {
// return dueSoon;
// }
//
// public void setFlattenedRootName(String name) {
// this.flattenedRootName = name;
// }
//
// public String getFlattenedRootName() {
// return flattenedRootName;
// }
//
// public void setExpressionDateFormat(String format) {
// this.expressionDateFormat = format;
// }
//
// public String getExpressionDateFormat() {
// return expressionDateFormat;
// }
//
// public int getIcsAlarmMinutes() {
// return icsAlarmMinutes;
// }
//
// public void setIcsAlarmMinutes(int icsAlarmMinutes) {
// this.icsAlarmMinutes = icsAlarmMinutes;
// }
//
// public boolean getIcsAlarm() {
// return icsAlarm;
// }
//
// public void setIcsAlarm(boolean icsAlarm) {
// this.icsAlarm = icsAlarm;
// }
//
// public String getIcsStart() {
// return icsStart;
// }
//
// public void setIcsStart(String icsStart) {
// this.icsStart = icsStart;
// }
//
// public String getIcsEnd() {
// return icsEnd;
// }
//
// public void setIcsEnd(String icsEnd) {
// this.icsEnd = icsEnd;
// }
//
// public boolean getIcsAllDay() {
// return icsAllDay;
// }
//
// public void setIcsAllDay(boolean icsAllDay) {
// this.icsAllDay = icsAllDay;
// }
//
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/StringUtils.java
// public class StringUtils {
//
// public static String join(Collection<String> data, String delimiter) {
// return join(data, new StringJoiner(delimiter));
// }
//
// public static String join(Collection<String> data, String delimiter, String prefix, String suffix) {
// return join(data, new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(String data[], String delimiter) {
// return join(Arrays.asList(data), new StringJoiner(delimiter));
// }
//
// public static String join(String data[], String delimiter, String prefix, String suffix) {
// return join(Arrays.asList(data), new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(Collection<String> data, StringJoiner sj) {
// data.stream().forEachOrdered((s) -> sj.add(s));
// return sj.toString();
// }
//
// public static String times(String str, int n) {
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < n; i++) {
// result.append(str);
// }
// return result.toString();
// }
// }
| import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import org.psidnell.omnifocus.ConfigParams;
import org.psidnell.omnifocus.expr.ExprAttribute;
import org.psidnell.omnifocus.sqlite.SQLiteProperty;
import org.psidnell.omnifocus.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonIgnore; | return cal.getTime();
} catch (NumberFormatException e) {
LOGGER.warn(e.getMessage());
}
}
return date;
}
@JsonIgnore
public String getIcsModified() {
return getModified().getIcs();
}
@JsonIgnore
public boolean getIcsHasAlarm() {
return icsAlarm && !icsAllDay;
}
@JsonIgnore
public int getIcsAlarmMinutes() {
return icsAlarmMinutes;
}
@JsonIgnore
public boolean getIcsHasCalendarData() {
return dueDate != null || deferDate != null;
}
@Override | // Path: src/main/java/org/psidnell/omnifocus/ConfigParams.java
// public class ConfigParams {
//
// private String dueSoon;
// private String flattenedRootName;
// private String expressionDateFormat;
// private int icsAlarmMinutes;
// private boolean icsAlarm;
// private String icsStart;
// private String icsEnd;
// private boolean icsAllDay;
//
// public void setDueSoon(String dueSoon) {
// this.dueSoon = dueSoon;
// }
//
// public String getDueSoon() {
// return dueSoon;
// }
//
// public void setFlattenedRootName(String name) {
// this.flattenedRootName = name;
// }
//
// public String getFlattenedRootName() {
// return flattenedRootName;
// }
//
// public void setExpressionDateFormat(String format) {
// this.expressionDateFormat = format;
// }
//
// public String getExpressionDateFormat() {
// return expressionDateFormat;
// }
//
// public int getIcsAlarmMinutes() {
// return icsAlarmMinutes;
// }
//
// public void setIcsAlarmMinutes(int icsAlarmMinutes) {
// this.icsAlarmMinutes = icsAlarmMinutes;
// }
//
// public boolean getIcsAlarm() {
// return icsAlarm;
// }
//
// public void setIcsAlarm(boolean icsAlarm) {
// this.icsAlarm = icsAlarm;
// }
//
// public String getIcsStart() {
// return icsStart;
// }
//
// public void setIcsStart(String icsStart) {
// this.icsStart = icsStart;
// }
//
// public String getIcsEnd() {
// return icsEnd;
// }
//
// public void setIcsEnd(String icsEnd) {
// this.icsEnd = icsEnd;
// }
//
// public boolean getIcsAllDay() {
// return icsAllDay;
// }
//
// public void setIcsAllDay(boolean icsAllDay) {
// this.icsAllDay = icsAllDay;
// }
//
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/StringUtils.java
// public class StringUtils {
//
// public static String join(Collection<String> data, String delimiter) {
// return join(data, new StringJoiner(delimiter));
// }
//
// public static String join(Collection<String> data, String delimiter, String prefix, String suffix) {
// return join(data, new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(String data[], String delimiter) {
// return join(Arrays.asList(data), new StringJoiner(delimiter));
// }
//
// public static String join(String data[], String delimiter, String prefix, String suffix) {
// return join(Arrays.asList(data), new StringJoiner(delimiter, prefix, suffix));
// }
//
// public static String join(Collection<String> data, StringJoiner sj) {
// data.stream().forEachOrdered((s) -> sj.add(s));
// return sj.toString();
// }
//
// public static String times(String str, int n) {
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < n; i++) {
// result.append(str);
// }
// return result.toString();
// }
// }
// Path: src/main/java/org/psidnell/omnifocus/model/CommonProjectAndTaskAttributes.java
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import org.psidnell.omnifocus.ConfigParams;
import org.psidnell.omnifocus.expr.ExprAttribute;
import org.psidnell.omnifocus.sqlite.SQLiteProperty;
import org.psidnell.omnifocus.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonIgnore;
return cal.getTime();
} catch (NumberFormatException e) {
LOGGER.warn(e.getMessage());
}
}
return date;
}
@JsonIgnore
public String getIcsModified() {
return getModified().getIcs();
}
@JsonIgnore
public boolean getIcsHasAlarm() {
return icsAlarm && !icsAllDay;
}
@JsonIgnore
public int getIcsAlarmMinutes() {
return icsAlarmMinutes;
}
@JsonIgnore
public boolean getIcsHasCalendarData() {
return dueDate != null || deferDate != null;
}
@Override | public void setConfigParams(ConfigParams config) { |
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/expr/Expression.java | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
| import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;
import org.psidnell.omnifocus.model.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
/**
* @author psidnell
*
* A minimal adaptor around the OGNL expression parser.
*/
public class Expression {
private static final Logger LOGGER = LoggerFactory.getLogger(Expression.class);
private static final OgnlContext OGNL_CONTEXT = new OgnlContext();
private Object expression;
private String expressionStr;
public Expression(String expression) {
try {
LOGGER.debug("new Expression(\"{}\")", expression);
this.expression = Ognl.parseExpression(expression);
this.expressionStr = expression;
} catch (OgnlException e) {
throw new IllegalArgumentException(e);
}
}
| // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
// Path: src/main/java/org/psidnell/omnifocus/expr/Expression.java
import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;
import org.psidnell.omnifocus.model.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
/**
* @author psidnell
*
* A minimal adaptor around the OGNL expression parser.
*/
public class Expression {
private static final Logger LOGGER = LoggerFactory.getLogger(Expression.class);
private static final OgnlContext OGNL_CONTEXT = new OgnlContext();
private Object expression;
private String expressionStr;
public Expression(String expression) {
try {
LOGGER.debug("new Expression(\"{}\")", expression);
this.expression = Ognl.parseExpression(expression);
this.expressionStr = expression;
} catch (OgnlException e) {
throw new IllegalArgumentException(e);
}
}
| public Object eval(Node node) { |
psidnell/ofexport2 | src/test/java/org/psidnell/omnifocus/model/FolderTest.java | // Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java
// public class ApplicationContextFactory {
//
// public static final String CONFIG_XML = "/config.xml";
// private static final String CONFIG_PROPERTIES = "/config.properties";
//
// public static ApplicationContext getContext() {
// return new ClassPathXmlApplicationContext(CONFIG_XML);
// }
//
// public static Properties getConfigProperties() throws IOException {
// try (
// InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) {
// if (in == null) {
// throw new IOException("config not found");
// }
// Properties config = new Properties();
// config.load(in);
// return config;
// }
// }
// }
| import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.psidnell.omnifocus.ApplicationContextFactory;
import org.springframework.context.ApplicationContext; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.model;
public class FolderTest {
private NodeFactory nodeFactory;
@Before
public void setup () { | // Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java
// public class ApplicationContextFactory {
//
// public static final String CONFIG_XML = "/config.xml";
// private static final String CONFIG_PROPERTIES = "/config.properties";
//
// public static ApplicationContext getContext() {
// return new ClassPathXmlApplicationContext(CONFIG_XML);
// }
//
// public static Properties getConfigProperties() throws IOException {
// try (
// InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) {
// if (in == null) {
// throw new IOException("config not found");
// }
// Properties config = new Properties();
// config.load(in);
// return config;
// }
// }
// }
// Path: src/test/java/org/psidnell/omnifocus/model/FolderTest.java
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.psidnell.omnifocus.ApplicationContextFactory;
import org.springframework.context.ApplicationContext;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.model;
public class FolderTest {
private NodeFactory nodeFactory;
@Before
public void setup () { | ApplicationContext appContext = ApplicationContextFactory.getContext(); |
psidnell/ofexport2 | src/test/java/org/psidnell/omnifocus/expr/ExpressionFunctionsTest.java | // Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java
// public class ApplicationContextFactory {
//
// public static final String CONFIG_XML = "/config.xml";
// private static final String CONFIG_PROPERTIES = "/config.properties";
//
// public static ApplicationContext getContext() {
// return new ClassPathXmlApplicationContext(CONFIG_XML);
// }
//
// public static Properties getConfigProperties() throws IOException {
// try (
// InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) {
// if (in == null) {
// throw new IOException("config not found");
// }
// Properties config = new Properties();
// config.load(in);
// return config;
// }
// }
// }
//
// Path: src/main/java/org/psidnell/omnifocus/ConfigParams.java
// public class ConfigParams {
//
// private String dueSoon;
// private String flattenedRootName;
// private String expressionDateFormat;
// private int icsAlarmMinutes;
// private boolean icsAlarm;
// private String icsStart;
// private String icsEnd;
// private boolean icsAllDay;
//
// public void setDueSoon(String dueSoon) {
// this.dueSoon = dueSoon;
// }
//
// public String getDueSoon() {
// return dueSoon;
// }
//
// public void setFlattenedRootName(String name) {
// this.flattenedRootName = name;
// }
//
// public String getFlattenedRootName() {
// return flattenedRootName;
// }
//
// public void setExpressionDateFormat(String format) {
// this.expressionDateFormat = format;
// }
//
// public String getExpressionDateFormat() {
// return expressionDateFormat;
// }
//
// public int getIcsAlarmMinutes() {
// return icsAlarmMinutes;
// }
//
// public void setIcsAlarmMinutes(int icsAlarmMinutes) {
// this.icsAlarmMinutes = icsAlarmMinutes;
// }
//
// public boolean getIcsAlarm() {
// return icsAlarm;
// }
//
// public void setIcsAlarm(boolean icsAlarm) {
// this.icsAlarm = icsAlarm;
// }
//
// public String getIcsStart() {
// return icsStart;
// }
//
// public void setIcsStart(String icsStart) {
// this.icsStart = icsStart;
// }
//
// public String getIcsEnd() {
// return icsEnd;
// }
//
// public void setIcsEnd(String icsEnd) {
// this.icsEnd = icsEnd;
// }
//
// public boolean getIcsAllDay() {
// return icsAllDay;
// }
//
// public void setIcsAllDay(boolean icsAllDay) {
// this.icsAllDay = icsAllDay;
// }
//
// }
| import static org.junit.Assert.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
import org.psidnell.omnifocus.ApplicationContextFactory;
import org.psidnell.omnifocus.ConfigParams;
import org.springframework.context.ApplicationContext; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
public class ExpressionFunctionsTest {
private SimpleDateFormat dateFormat; | // Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java
// public class ApplicationContextFactory {
//
// public static final String CONFIG_XML = "/config.xml";
// private static final String CONFIG_PROPERTIES = "/config.properties";
//
// public static ApplicationContext getContext() {
// return new ClassPathXmlApplicationContext(CONFIG_XML);
// }
//
// public static Properties getConfigProperties() throws IOException {
// try (
// InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) {
// if (in == null) {
// throw new IOException("config not found");
// }
// Properties config = new Properties();
// config.load(in);
// return config;
// }
// }
// }
//
// Path: src/main/java/org/psidnell/omnifocus/ConfigParams.java
// public class ConfigParams {
//
// private String dueSoon;
// private String flattenedRootName;
// private String expressionDateFormat;
// private int icsAlarmMinutes;
// private boolean icsAlarm;
// private String icsStart;
// private String icsEnd;
// private boolean icsAllDay;
//
// public void setDueSoon(String dueSoon) {
// this.dueSoon = dueSoon;
// }
//
// public String getDueSoon() {
// return dueSoon;
// }
//
// public void setFlattenedRootName(String name) {
// this.flattenedRootName = name;
// }
//
// public String getFlattenedRootName() {
// return flattenedRootName;
// }
//
// public void setExpressionDateFormat(String format) {
// this.expressionDateFormat = format;
// }
//
// public String getExpressionDateFormat() {
// return expressionDateFormat;
// }
//
// public int getIcsAlarmMinutes() {
// return icsAlarmMinutes;
// }
//
// public void setIcsAlarmMinutes(int icsAlarmMinutes) {
// this.icsAlarmMinutes = icsAlarmMinutes;
// }
//
// public boolean getIcsAlarm() {
// return icsAlarm;
// }
//
// public void setIcsAlarm(boolean icsAlarm) {
// this.icsAlarm = icsAlarm;
// }
//
// public String getIcsStart() {
// return icsStart;
// }
//
// public void setIcsStart(String icsStart) {
// this.icsStart = icsStart;
// }
//
// public String getIcsEnd() {
// return icsEnd;
// }
//
// public void setIcsEnd(String icsEnd) {
// this.icsEnd = icsEnd;
// }
//
// public boolean getIcsAllDay() {
// return icsAllDay;
// }
//
// public void setIcsAllDay(boolean icsAllDay) {
// this.icsAllDay = icsAllDay;
// }
//
// }
// Path: src/test/java/org/psidnell/omnifocus/expr/ExpressionFunctionsTest.java
import static org.junit.Assert.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
import org.psidnell.omnifocus.ApplicationContextFactory;
import org.psidnell.omnifocus.ConfigParams;
import org.springframework.context.ApplicationContext;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
public class ExpressionFunctionsTest {
private SimpleDateFormat dateFormat; | private ConfigParams config; |
psidnell/ofexport2 | src/test/java/org/psidnell/omnifocus/expr/ExpressionFunctionsTest.java | // Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java
// public class ApplicationContextFactory {
//
// public static final String CONFIG_XML = "/config.xml";
// private static final String CONFIG_PROPERTIES = "/config.properties";
//
// public static ApplicationContext getContext() {
// return new ClassPathXmlApplicationContext(CONFIG_XML);
// }
//
// public static Properties getConfigProperties() throws IOException {
// try (
// InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) {
// if (in == null) {
// throw new IOException("config not found");
// }
// Properties config = new Properties();
// config.load(in);
// return config;
// }
// }
// }
//
// Path: src/main/java/org/psidnell/omnifocus/ConfigParams.java
// public class ConfigParams {
//
// private String dueSoon;
// private String flattenedRootName;
// private String expressionDateFormat;
// private int icsAlarmMinutes;
// private boolean icsAlarm;
// private String icsStart;
// private String icsEnd;
// private boolean icsAllDay;
//
// public void setDueSoon(String dueSoon) {
// this.dueSoon = dueSoon;
// }
//
// public String getDueSoon() {
// return dueSoon;
// }
//
// public void setFlattenedRootName(String name) {
// this.flattenedRootName = name;
// }
//
// public String getFlattenedRootName() {
// return flattenedRootName;
// }
//
// public void setExpressionDateFormat(String format) {
// this.expressionDateFormat = format;
// }
//
// public String getExpressionDateFormat() {
// return expressionDateFormat;
// }
//
// public int getIcsAlarmMinutes() {
// return icsAlarmMinutes;
// }
//
// public void setIcsAlarmMinutes(int icsAlarmMinutes) {
// this.icsAlarmMinutes = icsAlarmMinutes;
// }
//
// public boolean getIcsAlarm() {
// return icsAlarm;
// }
//
// public void setIcsAlarm(boolean icsAlarm) {
// this.icsAlarm = icsAlarm;
// }
//
// public String getIcsStart() {
// return icsStart;
// }
//
// public void setIcsStart(String icsStart) {
// this.icsStart = icsStart;
// }
//
// public String getIcsEnd() {
// return icsEnd;
// }
//
// public void setIcsEnd(String icsEnd) {
// this.icsEnd = icsEnd;
// }
//
// public boolean getIcsAllDay() {
// return icsAllDay;
// }
//
// public void setIcsAllDay(boolean icsAllDay) {
// this.icsAllDay = icsAllDay;
// }
//
// }
| import static org.junit.Assert.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
import org.psidnell.omnifocus.ApplicationContextFactory;
import org.psidnell.omnifocus.ConfigParams;
import org.springframework.context.ApplicationContext; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
public class ExpressionFunctionsTest {
private SimpleDateFormat dateFormat;
private ConfigParams config;
private ExpressionFunctions fn;
@Before
public void setUp () { | // Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java
// public class ApplicationContextFactory {
//
// public static final String CONFIG_XML = "/config.xml";
// private static final String CONFIG_PROPERTIES = "/config.properties";
//
// public static ApplicationContext getContext() {
// return new ClassPathXmlApplicationContext(CONFIG_XML);
// }
//
// public static Properties getConfigProperties() throws IOException {
// try (
// InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) {
// if (in == null) {
// throw new IOException("config not found");
// }
// Properties config = new Properties();
// config.load(in);
// return config;
// }
// }
// }
//
// Path: src/main/java/org/psidnell/omnifocus/ConfigParams.java
// public class ConfigParams {
//
// private String dueSoon;
// private String flattenedRootName;
// private String expressionDateFormat;
// private int icsAlarmMinutes;
// private boolean icsAlarm;
// private String icsStart;
// private String icsEnd;
// private boolean icsAllDay;
//
// public void setDueSoon(String dueSoon) {
// this.dueSoon = dueSoon;
// }
//
// public String getDueSoon() {
// return dueSoon;
// }
//
// public void setFlattenedRootName(String name) {
// this.flattenedRootName = name;
// }
//
// public String getFlattenedRootName() {
// return flattenedRootName;
// }
//
// public void setExpressionDateFormat(String format) {
// this.expressionDateFormat = format;
// }
//
// public String getExpressionDateFormat() {
// return expressionDateFormat;
// }
//
// public int getIcsAlarmMinutes() {
// return icsAlarmMinutes;
// }
//
// public void setIcsAlarmMinutes(int icsAlarmMinutes) {
// this.icsAlarmMinutes = icsAlarmMinutes;
// }
//
// public boolean getIcsAlarm() {
// return icsAlarm;
// }
//
// public void setIcsAlarm(boolean icsAlarm) {
// this.icsAlarm = icsAlarm;
// }
//
// public String getIcsStart() {
// return icsStart;
// }
//
// public void setIcsStart(String icsStart) {
// this.icsStart = icsStart;
// }
//
// public String getIcsEnd() {
// return icsEnd;
// }
//
// public void setIcsEnd(String icsEnd) {
// this.icsEnd = icsEnd;
// }
//
// public boolean getIcsAllDay() {
// return icsAllDay;
// }
//
// public void setIcsAllDay(boolean icsAllDay) {
// this.icsAllDay = icsAllDay;
// }
//
// }
// Path: src/test/java/org/psidnell/omnifocus/expr/ExpressionFunctionsTest.java
import static org.junit.Assert.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
import org.psidnell.omnifocus.ApplicationContextFactory;
import org.psidnell.omnifocus.ConfigParams;
import org.springframework.context.ApplicationContext;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
public class ExpressionFunctionsTest {
private SimpleDateFormat dateFormat;
private ConfigParams config;
private ExpressionFunctions fn;
@Before
public void setUp () { | ApplicationContext appContext = ApplicationContextFactory.getContext(); |
psidnell/ofexport2 | src/test/java/org/psidnell/omnifocus/model/NodeImplTest.java | // Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java
// public class ApplicationContextFactory {
//
// public static final String CONFIG_XML = "/config.xml";
// private static final String CONFIG_PROPERTIES = "/config.properties";
//
// public static ApplicationContext getContext() {
// return new ClassPathXmlApplicationContext(CONFIG_XML);
// }
//
// public static Properties getConfigProperties() throws IOException {
// try (
// InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) {
// if (in == null) {
// throw new IOException("config not found");
// }
// Properties config = new Properties();
// config.load(in);
// return config;
// }
// }
// }
| import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.psidnell.omnifocus.ApplicationContextFactory;
import org.springframework.context.ApplicationContext; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.model;
public class NodeImplTest {
private NodeFactory nodeFactory;
@Before
public void setup () { | // Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java
// public class ApplicationContextFactory {
//
// public static final String CONFIG_XML = "/config.xml";
// private static final String CONFIG_PROPERTIES = "/config.properties";
//
// public static ApplicationContext getContext() {
// return new ClassPathXmlApplicationContext(CONFIG_XML);
// }
//
// public static Properties getConfigProperties() throws IOException {
// try (
// InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) {
// if (in == null) {
// throw new IOException("config not found");
// }
// Properties config = new Properties();
// config.load(in);
// return config;
// }
// }
// }
// Path: src/test/java/org/psidnell/omnifocus/model/NodeImplTest.java
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.psidnell.omnifocus.ApplicationContextFactory;
import org.springframework.context.ApplicationContext;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.model;
public class NodeImplTest {
private NodeFactory nodeFactory;
@Before
public void setup () { | ApplicationContext appContext = ApplicationContextFactory.getContext(); |
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/format/JSONFormatter.java | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/IOUtils.java
// public class IOUtils {
//
// public static Writer systemOutWriter() {
// return closeProofWriter(new OutputStreamWriter(System.out));
// }
//
// public static Writer closeProofWriter(Writer out) {
// return new Writer(out) {
// @Override
// public void close() throws IOException {
// // Don't want to close underlying writer
// }
//
// @Override
// public void write(char[] cbuf, int off, int len) throws IOException {
// out.write(cbuf, off, len);
// }
//
// @Override
// public void flush() throws IOException {
// out.flush();
// }
// };
// }
// }
| import java.io.IOException;
import java.io.Writer;
import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.format;
/**
* @author psidnell
*
* Formats the node by dumping the entire tree with Jackson.
*
*/
public class JSONFormatter implements Formatter {
private static final Logger LOGGER = LoggerFactory.getLogger(JSONFormatter.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
@Override | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/IOUtils.java
// public class IOUtils {
//
// public static Writer systemOutWriter() {
// return closeProofWriter(new OutputStreamWriter(System.out));
// }
//
// public static Writer closeProofWriter(Writer out) {
// return new Writer(out) {
// @Override
// public void close() throws IOException {
// // Don't want to close underlying writer
// }
//
// @Override
// public void write(char[] cbuf, int off, int len) throws IOException {
// out.write(cbuf, off, len);
// }
//
// @Override
// public void flush() throws IOException {
// out.flush();
// }
// };
// }
// }
// Path: src/main/java/org/psidnell/omnifocus/format/JSONFormatter.java
import java.io.IOException;
import java.io.Writer;
import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.format;
/**
* @author psidnell
*
* Formats the node by dumping the entire tree with Jackson.
*
*/
public class JSONFormatter implements Formatter {
private static final Logger LOGGER = LoggerFactory.getLogger(JSONFormatter.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
@Override | public void format(Node node, Writer out) throws IOException { |
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/format/JSONFormatter.java | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/IOUtils.java
// public class IOUtils {
//
// public static Writer systemOutWriter() {
// return closeProofWriter(new OutputStreamWriter(System.out));
// }
//
// public static Writer closeProofWriter(Writer out) {
// return new Writer(out) {
// @Override
// public void close() throws IOException {
// // Don't want to close underlying writer
// }
//
// @Override
// public void write(char[] cbuf, int off, int len) throws IOException {
// out.write(cbuf, off, len);
// }
//
// @Override
// public void flush() throws IOException {
// out.flush();
// }
// };
// }
// }
| import java.io.IOException;
import java.io.Writer;
import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.format;
/**
* @author psidnell
*
* Formats the node by dumping the entire tree with Jackson.
*
*/
public class JSONFormatter implements Formatter {
private static final Logger LOGGER = LoggerFactory.getLogger(JSONFormatter.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
@Override
public void format(Node node, Writer out) throws IOException {
LOGGER.info("Formatting: {}", node);
// Mapper closes the stream - don't want that here | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/IOUtils.java
// public class IOUtils {
//
// public static Writer systemOutWriter() {
// return closeProofWriter(new OutputStreamWriter(System.out));
// }
//
// public static Writer closeProofWriter(Writer out) {
// return new Writer(out) {
// @Override
// public void close() throws IOException {
// // Don't want to close underlying writer
// }
//
// @Override
// public void write(char[] cbuf, int off, int len) throws IOException {
// out.write(cbuf, off, len);
// }
//
// @Override
// public void flush() throws IOException {
// out.flush();
// }
// };
// }
// }
// Path: src/main/java/org/psidnell/omnifocus/format/JSONFormatter.java
import java.io.IOException;
import java.io.Writer;
import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.format;
/**
* @author psidnell
*
* Formats the node by dumping the entire tree with Jackson.
*
*/
public class JSONFormatter implements Formatter {
private static final Logger LOGGER = LoggerFactory.getLogger(JSONFormatter.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
@Override
public void format(Node node, Writer out) throws IOException {
LOGGER.info("Formatting: {}", node);
// Mapper closes the stream - don't want that here | Writer closeProofWriter = IOUtils.closeProofWriter(out); |
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/format/XMLFormatter.java | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/IOUtils.java
// public class IOUtils {
//
// public static Writer systemOutWriter() {
// return closeProofWriter(new OutputStreamWriter(System.out));
// }
//
// public static Writer closeProofWriter(Writer out) {
// return new Writer(out) {
// @Override
// public void close() throws IOException {
// // Don't want to close underlying writer
// }
//
// @Override
// public void write(char[] cbuf, int off, int len) throws IOException {
// out.write(cbuf, off, len);
// }
//
// @Override
// public void flush() throws IOException {
// out.flush();
// }
// };
// }
// }
| import java.io.IOException;
import java.io.Writer;
import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.format;
/**
* @author psidnell
*
* Formats the node by dumping the entire tree with Jackson.
*
*/
public class XMLFormatter implements Formatter {
private static final Logger LOGGER = LoggerFactory.getLogger(XMLFormatter.class);
private static final XmlMapper MAPPER = new XmlMapper();
@Override | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/IOUtils.java
// public class IOUtils {
//
// public static Writer systemOutWriter() {
// return closeProofWriter(new OutputStreamWriter(System.out));
// }
//
// public static Writer closeProofWriter(Writer out) {
// return new Writer(out) {
// @Override
// public void close() throws IOException {
// // Don't want to close underlying writer
// }
//
// @Override
// public void write(char[] cbuf, int off, int len) throws IOException {
// out.write(cbuf, off, len);
// }
//
// @Override
// public void flush() throws IOException {
// out.flush();
// }
// };
// }
// }
// Path: src/main/java/org/psidnell/omnifocus/format/XMLFormatter.java
import java.io.IOException;
import java.io.Writer;
import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.format;
/**
* @author psidnell
*
* Formats the node by dumping the entire tree with Jackson.
*
*/
public class XMLFormatter implements Formatter {
private static final Logger LOGGER = LoggerFactory.getLogger(XMLFormatter.class);
private static final XmlMapper MAPPER = new XmlMapper();
@Override | public void format(Node node, Writer out) throws IOException { |
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/format/XMLFormatter.java | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/IOUtils.java
// public class IOUtils {
//
// public static Writer systemOutWriter() {
// return closeProofWriter(new OutputStreamWriter(System.out));
// }
//
// public static Writer closeProofWriter(Writer out) {
// return new Writer(out) {
// @Override
// public void close() throws IOException {
// // Don't want to close underlying writer
// }
//
// @Override
// public void write(char[] cbuf, int off, int len) throws IOException {
// out.write(cbuf, off, len);
// }
//
// @Override
// public void flush() throws IOException {
// out.flush();
// }
// };
// }
// }
| import java.io.IOException;
import java.io.Writer;
import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.format;
/**
* @author psidnell
*
* Formats the node by dumping the entire tree with Jackson.
*
*/
public class XMLFormatter implements Formatter {
private static final Logger LOGGER = LoggerFactory.getLogger(XMLFormatter.class);
private static final XmlMapper MAPPER = new XmlMapper();
@Override
public void format(Node node, Writer out) throws IOException {
LOGGER.info("Formatting: {}", node);
// Mapper closes the stream - don't want that here | // Path: src/main/java/org/psidnell/omnifocus/model/Node.java
// public interface Node {
//
// String getName();
//
// void setName(String name);
//
// String getId();
//
// void setId(String id);
//
// int getRank();
//
// void setRank(int rank);
//
// String getType();
//
// boolean isRoot();
//
// boolean isMarked();
//
// void setMarked(boolean marked);
//
// void cascadeMarked();
//
// void setConfigParams(ConfigParams config);
//
// java.util.Date getDateAdded();
//
// void setDateAdded(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getAdded();
//
// java.util.Date getDateModified();
//
// void setDateModified(java.util.Date date);
//
// org.psidnell.omnifocus.expr.Date getModified();
// }
//
// Path: src/main/java/org/psidnell/omnifocus/util/IOUtils.java
// public class IOUtils {
//
// public static Writer systemOutWriter() {
// return closeProofWriter(new OutputStreamWriter(System.out));
// }
//
// public static Writer closeProofWriter(Writer out) {
// return new Writer(out) {
// @Override
// public void close() throws IOException {
// // Don't want to close underlying writer
// }
//
// @Override
// public void write(char[] cbuf, int off, int len) throws IOException {
// out.write(cbuf, off, len);
// }
//
// @Override
// public void flush() throws IOException {
// out.flush();
// }
// };
// }
// }
// Path: src/main/java/org/psidnell/omnifocus/format/XMLFormatter.java
import java.io.IOException;
import java.io.Writer;
import org.psidnell.omnifocus.model.Node;
import org.psidnell.omnifocus.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.format;
/**
* @author psidnell
*
* Formats the node by dumping the entire tree with Jackson.
*
*/
public class XMLFormatter implements Formatter {
private static final Logger LOGGER = LoggerFactory.getLogger(XMLFormatter.class);
private static final XmlMapper MAPPER = new XmlMapper();
@Override
public void format(Node node, Writer out) throws IOException {
LOGGER.info("Formatting: {}", node);
// Mapper closes the stream - don't want that here | Writer closeProofWriter = IOUtils.closeProofWriter(out); |
psidnell/ofexport2 | src/main/java/org/psidnell/omnifocus/expr/ExpressionFunctions.java | // Path: src/main/java/org/psidnell/omnifocus/ConfigParams.java
// public class ConfigParams {
//
// private String dueSoon;
// private String flattenedRootName;
// private String expressionDateFormat;
// private int icsAlarmMinutes;
// private boolean icsAlarm;
// private String icsStart;
// private String icsEnd;
// private boolean icsAllDay;
//
// public void setDueSoon(String dueSoon) {
// this.dueSoon = dueSoon;
// }
//
// public String getDueSoon() {
// return dueSoon;
// }
//
// public void setFlattenedRootName(String name) {
// this.flattenedRootName = name;
// }
//
// public String getFlattenedRootName() {
// return flattenedRootName;
// }
//
// public void setExpressionDateFormat(String format) {
// this.expressionDateFormat = format;
// }
//
// public String getExpressionDateFormat() {
// return expressionDateFormat;
// }
//
// public int getIcsAlarmMinutes() {
// return icsAlarmMinutes;
// }
//
// public void setIcsAlarmMinutes(int icsAlarmMinutes) {
// this.icsAlarmMinutes = icsAlarmMinutes;
// }
//
// public boolean getIcsAlarm() {
// return icsAlarm;
// }
//
// public void setIcsAlarm(boolean icsAlarm) {
// this.icsAlarm = icsAlarm;
// }
//
// public String getIcsStart() {
// return icsStart;
// }
//
// public void setIcsStart(String icsStart) {
// this.icsStart = icsStart;
// }
//
// public String getIcsEnd() {
// return icsEnd;
// }
//
// public void setIcsEnd(String icsEnd) {
// this.icsEnd = icsEnd;
// }
//
// public boolean getIcsAllDay() {
// return icsAllDay;
// }
//
// public void setIcsAllDay(boolean icsAllDay) {
// this.icsAllDay = icsAllDay;
// }
//
// }
| import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.psidnell.omnifocus.ConfigParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
/**
* @author psidnell
*
* A utility base class that provides methods that simplify using OGNL expressions in
* command line options, for example creating Date objects from strings to allow filters to
* be expressed more easily.
*/
public class ExpressionFunctions {
private static final Logger LOGGER = LoggerFactory.getLogger(ExpressionFunctions.class);
private static final int MONTHS_IN_YEAR = 12;
private static final int DAYS_IN_WEEK = 7;
private SimpleDateFormat dateFormat;
| // Path: src/main/java/org/psidnell/omnifocus/ConfigParams.java
// public class ConfigParams {
//
// private String dueSoon;
// private String flattenedRootName;
// private String expressionDateFormat;
// private int icsAlarmMinutes;
// private boolean icsAlarm;
// private String icsStart;
// private String icsEnd;
// private boolean icsAllDay;
//
// public void setDueSoon(String dueSoon) {
// this.dueSoon = dueSoon;
// }
//
// public String getDueSoon() {
// return dueSoon;
// }
//
// public void setFlattenedRootName(String name) {
// this.flattenedRootName = name;
// }
//
// public String getFlattenedRootName() {
// return flattenedRootName;
// }
//
// public void setExpressionDateFormat(String format) {
// this.expressionDateFormat = format;
// }
//
// public String getExpressionDateFormat() {
// return expressionDateFormat;
// }
//
// public int getIcsAlarmMinutes() {
// return icsAlarmMinutes;
// }
//
// public void setIcsAlarmMinutes(int icsAlarmMinutes) {
// this.icsAlarmMinutes = icsAlarmMinutes;
// }
//
// public boolean getIcsAlarm() {
// return icsAlarm;
// }
//
// public void setIcsAlarm(boolean icsAlarm) {
// this.icsAlarm = icsAlarm;
// }
//
// public String getIcsStart() {
// return icsStart;
// }
//
// public void setIcsStart(String icsStart) {
// this.icsStart = icsStart;
// }
//
// public String getIcsEnd() {
// return icsEnd;
// }
//
// public void setIcsEnd(String icsEnd) {
// this.icsEnd = icsEnd;
// }
//
// public boolean getIcsAllDay() {
// return icsAllDay;
// }
//
// public void setIcsAllDay(boolean icsAllDay) {
// this.icsAllDay = icsAllDay;
// }
//
// }
// Path: src/main/java/org/psidnell/omnifocus/expr/ExpressionFunctions.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.psidnell.omnifocus.ConfigParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.expr;
/**
* @author psidnell
*
* A utility base class that provides methods that simplify using OGNL expressions in
* command line options, for example creating Date objects from strings to allow filters to
* be expressed more easily.
*/
public class ExpressionFunctions {
private static final Logger LOGGER = LoggerFactory.getLogger(ExpressionFunctions.class);
private static final int MONTHS_IN_YEAR = 12;
private static final int DAYS_IN_WEEK = 7;
private SimpleDateFormat dateFormat;
| protected ConfigParams config; |
psidnell/ofexport2 | src/test/java/org/psidnell/omnifocus/model/TaskTest.java | // Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java
// public class ApplicationContextFactory {
//
// public static final String CONFIG_XML = "/config.xml";
// private static final String CONFIG_PROPERTIES = "/config.properties";
//
// public static ApplicationContext getContext() {
// return new ClassPathXmlApplicationContext(CONFIG_XML);
// }
//
// public static Properties getConfigProperties() throws IOException {
// try (
// InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) {
// if (in == null) {
// throw new IOException("config not found");
// }
// Properties config = new Properties();
// config.load(in);
// return config;
// }
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.text.ParseException;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import org.psidnell.omnifocus.ApplicationContextFactory;
import org.springframework.context.ApplicationContext; | /*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.model;
public class TaskTest {
private NodeFactory nodeFactory;
@Before
public void setup () { | // Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java
// public class ApplicationContextFactory {
//
// public static final String CONFIG_XML = "/config.xml";
// private static final String CONFIG_PROPERTIES = "/config.properties";
//
// public static ApplicationContext getContext() {
// return new ClassPathXmlApplicationContext(CONFIG_XML);
// }
//
// public static Properties getConfigProperties() throws IOException {
// try (
// InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) {
// if (in == null) {
// throw new IOException("config not found");
// }
// Properties config = new Properties();
// config.load(in);
// return config;
// }
// }
// }
// Path: src/test/java/org/psidnell/omnifocus/model/TaskTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.text.ParseException;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import org.psidnell.omnifocus.ApplicationContextFactory;
import org.springframework.context.ApplicationContext;
/*
* Copyright 2015 Paul Sidnell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.psidnell.omnifocus.model;
public class TaskTest {
private NodeFactory nodeFactory;
@Before
public void setup () { | ApplicationContext appContext = ApplicationContextFactory.getContext(); |
martint/jmxutils | src/main/java/org/weakref/jmx/MBeanExporter.java | // Path: src/main/java/org/weakref/jmx/JmxException.java
// public enum Reason
// {
// INVALID_ANNOTATION,
// MALFORMED_OBJECT_NAME,
// INSTANCE_ALREADY_EXISTS,
// INSTANCE_NOT_FOUND,
// MBEAN_REGISTRATION
// }
| import com.google.common.collect.ImmutableMap;
import com.google.common.collect.MapMaker;
import com.google.inject.Inject;
import org.weakref.jmx.JmxException.Reason;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import static java.util.Objects.requireNonNull; | requireNonNull(type, "type is null");
requireNonNull(name, "name is null");
ObjectName objectName = createObjectName(objectNameGenerator.generatedNameOf(type, name));
export(objectName, object);
return new MBeanExport(objectName, () -> unexport(objectName));
}
public MBeanExport exportWithGeneratedName(Object object, Class<?> type, Map<String, String> properties)
{
requireNonNull(object, "object is null");
requireNonNull(type, "type is null");
requireNonNull(properties, "properties is null");
ObjectName objectName = createObjectName(objectNameGenerator.generatedNameOf(type, properties));
export(objectName, object);
return new MBeanExport(objectName, () -> unexport(objectName));
}
public void export(String name, Object object)
{
export(createObjectName(name), object);
}
public void export(ObjectName objectName, Object object)
{
try {
MBeanBuilder builder = new MBeanBuilder(object);
MBean mbean = builder.build();
synchronized(exportedObjects) {
if(exportedObjects.containsKey(objectName)) { | // Path: src/main/java/org/weakref/jmx/JmxException.java
// public enum Reason
// {
// INVALID_ANNOTATION,
// MALFORMED_OBJECT_NAME,
// INSTANCE_ALREADY_EXISTS,
// INSTANCE_NOT_FOUND,
// MBEAN_REGISTRATION
// }
// Path: src/main/java/org/weakref/jmx/MBeanExporter.java
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.MapMaker;
import com.google.inject.Inject;
import org.weakref.jmx.JmxException.Reason;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import static java.util.Objects.requireNonNull;
requireNonNull(type, "type is null");
requireNonNull(name, "name is null");
ObjectName objectName = createObjectName(objectNameGenerator.generatedNameOf(type, name));
export(objectName, object);
return new MBeanExport(objectName, () -> unexport(objectName));
}
public MBeanExport exportWithGeneratedName(Object object, Class<?> type, Map<String, String> properties)
{
requireNonNull(object, "object is null");
requireNonNull(type, "type is null");
requireNonNull(properties, "properties is null");
ObjectName objectName = createObjectName(objectNameGenerator.generatedNameOf(type, properties));
export(objectName, object);
return new MBeanExport(objectName, () -> unexport(objectName));
}
public void export(String name, Object object)
{
export(createObjectName(name), object);
}
public void export(ObjectName objectName, Object object)
{
try {
MBeanBuilder builder = new MBeanBuilder(object);
MBean mbean = builder.build();
synchronized(exportedObjects) {
if(exportedObjects.containsKey(objectName)) { | throw new JmxException(Reason.INSTANCE_ALREADY_EXISTS, "key already exported: %s", objectName); |
martint/jmxutils | src/main/java/org/weakref/jmx/guice/NamedExportBinder.java | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
| import com.google.inject.Key;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Named;
import org.weakref.jmx.ObjectNameGenerator;
import java.util.function.Function; | this.binder = binder;
this.key = key;
}
/**
* Names the MBean according to {@link org.weakref.jmx.ObjectNames} name generator methods.
*/
public void withGeneratedName()
{
if (key.getAnnotation() != null) {
if (key.getAnnotation() instanceof Named) {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType(), ((Named) key.getAnnotation()).value()));
}
else {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType(), key.getAnnotation().annotationType().getSimpleName()));
}
}
else if (key.getAnnotationType() != null) {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType(), key.getAnnotationType().getSimpleName()));
}
else {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType()));
}
}
public void as(String name)
{
as(factory -> name);
}
| // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
// Path: src/main/java/org/weakref/jmx/guice/NamedExportBinder.java
import com.google.inject.Key;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Named;
import org.weakref.jmx.ObjectNameGenerator;
import java.util.function.Function;
this.binder = binder;
this.key = key;
}
/**
* Names the MBean according to {@link org.weakref.jmx.ObjectNames} name generator methods.
*/
public void withGeneratedName()
{
if (key.getAnnotation() != null) {
if (key.getAnnotation() instanceof Named) {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType(), ((Named) key.getAnnotation()).value()));
}
else {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType(), key.getAnnotation().annotationType().getSimpleName()));
}
}
else if (key.getAnnotationType() != null) {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType(), key.getAnnotationType().getSimpleName()));
}
else {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType()));
}
}
public void as(String name)
{
as(factory -> name);
}
| public void as(Function<ObjectNameGenerator, String> nameFactory) |
martint/jmxutils | src/main/java/org/weakref/jmx/guice/NamedBindingBuilder.java | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
| import com.google.inject.Key;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Named;
import org.weakref.jmx.ObjectNameGenerator;
import java.util.function.Function; | this.binder = binder;
this.key = key;
}
/**
* Names the MBean according to {@link org.weakref.jmx.ObjectNames} name generator methods.
*/
public void withGeneratedName()
{
if (key.getAnnotation() != null) {
if (key.getAnnotation() instanceof Named) {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType(), ((Named) key.getAnnotation()).value()));
}
else {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType(), key.getAnnotation().annotationType().getSimpleName()));
}
}
else if (key.getAnnotationType() != null) {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType(), key.getAnnotationType().getSimpleName()));
}
else {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType()));
}
}
public void as(String name)
{
as(factory -> name);
}
| // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
// Path: src/main/java/org/weakref/jmx/guice/NamedBindingBuilder.java
import com.google.inject.Key;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Named;
import org.weakref.jmx.ObjectNameGenerator;
import java.util.function.Function;
this.binder = binder;
this.key = key;
}
/**
* Names the MBean according to {@link org.weakref.jmx.ObjectNames} name generator methods.
*/
public void withGeneratedName()
{
if (key.getAnnotation() != null) {
if (key.getAnnotation() instanceof Named) {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType(), ((Named) key.getAnnotation()).value()));
}
else {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType(), key.getAnnotation().annotationType().getSimpleName()));
}
}
else if (key.getAnnotationType() != null) {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType(), key.getAnnotationType().getSimpleName()));
}
else {
as(factory -> factory.generatedNameOf(key.getTypeLiteral().getRawType()));
}
}
public void as(String name)
{
as(factory -> name);
}
| private void as(Function<ObjectNameGenerator, String> mappingNameFactory) |
martint/jmxutils | src/test/java/org/weakref/jmx/TestObjectNames.java | // Path: src/main/java/org/weakref/jmx/ObjectNames.java
// public static String generatedNameOf(Class<?> clazz)
// {
// return builder(clazz).build();
// }
| import com.google.inject.name.Names;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.weakref.jmx.ObjectNames.generatedNameOf; | package org.weakref.jmx;
public class TestObjectNames {
@interface Ann {}
static class AnnImpl implements Ann {
@Override
public Class<? extends Annotation> annotationType() {
return Ann.class;
}
}
static class Inner {}
@Test
public void testGeneratedNameOf1() {
assertEquals( | // Path: src/main/java/org/weakref/jmx/ObjectNames.java
// public static String generatedNameOf(Class<?> clazz)
// {
// return builder(clazz).build();
// }
// Path: src/test/java/org/weakref/jmx/TestObjectNames.java
import com.google.inject.name.Names;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.weakref.jmx.ObjectNames.generatedNameOf;
package org.weakref.jmx;
public class TestObjectNames {
@interface Ann {}
static class AnnImpl implements Ann {
@Override
public Class<? extends Annotation> annotationType() {
return Ann.class;
}
}
static class Inner {}
@Test
public void testGeneratedNameOf1() {
assertEquals( | generatedNameOf(SimpleObject.class), |
martint/jmxutils | src/main/java/org/weakref/jmx/guice/SetExportBinder.java | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
| import com.google.inject.multibindings.Multibinder;
import org.weakref.jmx.ObjectNameGenerator;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.util.function.BiFunction; | package org.weakref.jmx.guice;
public class SetExportBinder<T>
{
private final Multibinder<SetMapping<?>> binder;
private final Class<T> clazz;
SetExportBinder(Multibinder<SetMapping<?>> binder, Class<T> clazz)
{
this.binder = binder;
this.clazz = clazz;
}
public void withGeneratedName(final NamingFunction<T> itemNamingFunction)
{ | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
// Path: src/main/java/org/weakref/jmx/guice/SetExportBinder.java
import com.google.inject.multibindings.Multibinder;
import org.weakref.jmx.ObjectNameGenerator;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.util.function.BiFunction;
package org.weakref.jmx.guice;
public class SetExportBinder<T>
{
private final Multibinder<SetMapping<?>> binder;
private final Class<T> clazz;
SetExportBinder(Multibinder<SetMapping<?>> binder, Class<T> clazz)
{
this.binder = binder;
this.clazz = clazz;
}
public void withGeneratedName(final NamingFunction<T> itemNamingFunction)
{ | BiFunction<ObjectNameGenerator, T, ObjectName> nameFactory = (factory, object) -> { |
martint/jmxutils | src/main/java/org/weakref/jmx/testing/TestingMBeanModule.java | // Path: src/main/java/org/weakref/jmx/guice/MBeanModule.java
// public class MBeanModule
// extends AbstractModule
// {
// private ExportBuilder builder;
//
// @Override
// protected final void configure()
// {
// builder = newExporter(binder());
//
// bind(GuiceMBeanExporter.class).asEagerSingleton();
// bind(MBeanExporter.class).in(Scopes.SINGLETON);
//
// newOptionalBinder(binder(), ObjectNameGenerator.class);
// newSetBinder(binder(), new TypeLiteral<SetMapping<?>>() {});
// newSetBinder(binder(), new TypeLiteral<MapMapping<?, ?>>() {});
//
// configureMBeans();
// }
//
// /**
// * To be overridden by subclasses. E.g.,
// *
// * protected void configureMBeans() {
// * export(ManagedObject.class).as("test:name=X");
// * export(ManagedObject.class).annotatedWith(SomeAnnotation.class).as("test:name=Y");
// * }
// *
// * When ExportBuilder is used, a raw MBeanModule can be imported to trigger the
// * registration of exported mbeans:
// *
// * Injector injector = Guice.createInjector(new MBeanModule(),
// * new AbstractModule() {
// * @Override
// * protected void configure() {
// * ExportBuilder builder = MBeanModule.newExporter();
// * builder.export(AnotherManagedObject.class).as("test:name="Z");
// * }
// * });
// *
// * @deprecated subclassing no longer supported. Use ExportBinder instead
// */
// @Deprecated
// protected void configureMBeans() {
// }
//
// @Deprecated
// protected NamedBindingBuilder export(Key<?> key)
// {
// return builder.export(key);
// }
//
// @Deprecated
// protected AnnotatedExportBuilder export(Class<?> clazz)
// {
// return builder.export(clazz);
// }
//
// @Deprecated
// public static ExportBuilder newExporter(Binder binder)
// {
// return new ExportBuilder(newSetBinder(binder, Mapping.class));
// }
//
// }
| import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import org.weakref.jmx.guice.MBeanModule;
import javax.management.MBeanServer; | package org.weakref.jmx.testing;
public class TestingMBeanModule
extends AbstractModule
{
@Override
protected void configure()
{ | // Path: src/main/java/org/weakref/jmx/guice/MBeanModule.java
// public class MBeanModule
// extends AbstractModule
// {
// private ExportBuilder builder;
//
// @Override
// protected final void configure()
// {
// builder = newExporter(binder());
//
// bind(GuiceMBeanExporter.class).asEagerSingleton();
// bind(MBeanExporter.class).in(Scopes.SINGLETON);
//
// newOptionalBinder(binder(), ObjectNameGenerator.class);
// newSetBinder(binder(), new TypeLiteral<SetMapping<?>>() {});
// newSetBinder(binder(), new TypeLiteral<MapMapping<?, ?>>() {});
//
// configureMBeans();
// }
//
// /**
// * To be overridden by subclasses. E.g.,
// *
// * protected void configureMBeans() {
// * export(ManagedObject.class).as("test:name=X");
// * export(ManagedObject.class).annotatedWith(SomeAnnotation.class).as("test:name=Y");
// * }
// *
// * When ExportBuilder is used, a raw MBeanModule can be imported to trigger the
// * registration of exported mbeans:
// *
// * Injector injector = Guice.createInjector(new MBeanModule(),
// * new AbstractModule() {
// * @Override
// * protected void configure() {
// * ExportBuilder builder = MBeanModule.newExporter();
// * builder.export(AnotherManagedObject.class).as("test:name="Z");
// * }
// * });
// *
// * @deprecated subclassing no longer supported. Use ExportBinder instead
// */
// @Deprecated
// protected void configureMBeans() {
// }
//
// @Deprecated
// protected NamedBindingBuilder export(Key<?> key)
// {
// return builder.export(key);
// }
//
// @Deprecated
// protected AnnotatedExportBuilder export(Class<?> clazz)
// {
// return builder.export(clazz);
// }
//
// @Deprecated
// public static ExportBuilder newExporter(Binder binder)
// {
// return new ExportBuilder(newSetBinder(binder, Mapping.class));
// }
//
// }
// Path: src/main/java/org/weakref/jmx/testing/TestingMBeanModule.java
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import org.weakref.jmx.guice.MBeanModule;
import javax.management.MBeanServer;
package org.weakref.jmx.testing;
public class TestingMBeanModule
extends AbstractModule
{
@Override
protected void configure()
{ | install(new MBeanModule()); |
martint/jmxutils | src/main/java/org/weakref/jmx/MBeanAttributeBuilder.java | // Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isValidGetter(Method getter)
// {
// if (getter == null) {
// throw new NullPointerException("getter is null");
// }
// if (getter.getParameterTypes().length != 0) {
// return false;
// }
// if (getter.getReturnType().equals(Void.TYPE)) {
// return false;
// }
// return true;
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isValidSetter(Method setter)
// {
// if (setter == null) {
// throw new NullPointerException("setter is null");
// }
// if (setter.getParameterTypes().length != 1) {
// return false;
// }
// return true;
// }
| import javax.management.Descriptor;
import javax.management.ImmutableDescriptor;
import javax.management.MBeanAttributeInfo;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.weakref.jmx.ReflectionUtils.isValidGetter;
import static org.weakref.jmx.ReflectionUtils.isValidSetter; | private Method concreteGetter;
private Method annotatedGetter;
private Method concreteSetter;
private Method annotatedSetter;
private boolean flatten;
private boolean nested;
public MBeanAttributeBuilder onInstance(Object target)
{
if (target == null) {
throw new NullPointerException("target is null");
}
this.target = target;
return this;
}
public MBeanAttributeBuilder named(String name)
{
if (name == null) {
throw new NullPointerException("name is null");
}
this.name = name;
return this;
}
public MBeanAttributeBuilder withConcreteGetter(Method concreteGetter)
{
if (concreteGetter == null) {
throw new NullPointerException("concreteGetter is null");
} | // Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isValidGetter(Method getter)
// {
// if (getter == null) {
// throw new NullPointerException("getter is null");
// }
// if (getter.getParameterTypes().length != 0) {
// return false;
// }
// if (getter.getReturnType().equals(Void.TYPE)) {
// return false;
// }
// return true;
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isValidSetter(Method setter)
// {
// if (setter == null) {
// throw new NullPointerException("setter is null");
// }
// if (setter.getParameterTypes().length != 1) {
// return false;
// }
// return true;
// }
// Path: src/main/java/org/weakref/jmx/MBeanAttributeBuilder.java
import javax.management.Descriptor;
import javax.management.ImmutableDescriptor;
import javax.management.MBeanAttributeInfo;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.weakref.jmx.ReflectionUtils.isValidGetter;
import static org.weakref.jmx.ReflectionUtils.isValidSetter;
private Method concreteGetter;
private Method annotatedGetter;
private Method concreteSetter;
private Method annotatedSetter;
private boolean flatten;
private boolean nested;
public MBeanAttributeBuilder onInstance(Object target)
{
if (target == null) {
throw new NullPointerException("target is null");
}
this.target = target;
return this;
}
public MBeanAttributeBuilder named(String name)
{
if (name == null) {
throw new NullPointerException("name is null");
}
this.name = name;
return this;
}
public MBeanAttributeBuilder withConcreteGetter(Method concreteGetter)
{
if (concreteGetter == null) {
throw new NullPointerException("concreteGetter is null");
} | if (!isValidGetter(concreteGetter)) { |
martint/jmxutils | src/main/java/org/weakref/jmx/MBeanAttributeBuilder.java | // Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isValidGetter(Method getter)
// {
// if (getter == null) {
// throw new NullPointerException("getter is null");
// }
// if (getter.getParameterTypes().length != 0) {
// return false;
// }
// if (getter.getReturnType().equals(Void.TYPE)) {
// return false;
// }
// return true;
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isValidSetter(Method setter)
// {
// if (setter == null) {
// throw new NullPointerException("setter is null");
// }
// if (setter.getParameterTypes().length != 1) {
// return false;
// }
// return true;
// }
| import javax.management.Descriptor;
import javax.management.ImmutableDescriptor;
import javax.management.MBeanAttributeInfo;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.weakref.jmx.ReflectionUtils.isValidGetter;
import static org.weakref.jmx.ReflectionUtils.isValidSetter; |
public MBeanAttributeBuilder withConcreteGetter(Method concreteGetter)
{
if (concreteGetter == null) {
throw new NullPointerException("concreteGetter is null");
}
if (!isValidGetter(concreteGetter)) {
throw new IllegalArgumentException("Method is not a valid getter: " + concreteGetter);
}
this.concreteGetter = concreteGetter;
return this;
}
public MBeanAttributeBuilder withAnnotatedGetter(Method annotatedGetter)
{
if (annotatedGetter == null) {
throw new NullPointerException("annotatedGetter is null");
}
if (!isValidGetter(annotatedGetter)) {
throw new IllegalArgumentException("Method is not a valid getter: " + annotatedGetter);
}
this.annotatedGetter = annotatedGetter;
return this;
}
public MBeanAttributeBuilder withConcreteSetter(Method concreteSetter)
{
if (concreteSetter == null) {
throw new NullPointerException("concreteSetter is null");
} | // Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isValidGetter(Method getter)
// {
// if (getter == null) {
// throw new NullPointerException("getter is null");
// }
// if (getter.getParameterTypes().length != 0) {
// return false;
// }
// if (getter.getReturnType().equals(Void.TYPE)) {
// return false;
// }
// return true;
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isValidSetter(Method setter)
// {
// if (setter == null) {
// throw new NullPointerException("setter is null");
// }
// if (setter.getParameterTypes().length != 1) {
// return false;
// }
// return true;
// }
// Path: src/main/java/org/weakref/jmx/MBeanAttributeBuilder.java
import javax.management.Descriptor;
import javax.management.ImmutableDescriptor;
import javax.management.MBeanAttributeInfo;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.weakref.jmx.ReflectionUtils.isValidGetter;
import static org.weakref.jmx.ReflectionUtils.isValidSetter;
public MBeanAttributeBuilder withConcreteGetter(Method concreteGetter)
{
if (concreteGetter == null) {
throw new NullPointerException("concreteGetter is null");
}
if (!isValidGetter(concreteGetter)) {
throw new IllegalArgumentException("Method is not a valid getter: " + concreteGetter);
}
this.concreteGetter = concreteGetter;
return this;
}
public MBeanAttributeBuilder withAnnotatedGetter(Method annotatedGetter)
{
if (annotatedGetter == null) {
throw new NullPointerException("annotatedGetter is null");
}
if (!isValidGetter(annotatedGetter)) {
throw new IllegalArgumentException("Method is not a valid getter: " + annotatedGetter);
}
this.annotatedGetter = annotatedGetter;
return this;
}
public MBeanAttributeBuilder withConcreteSetter(Method concreteSetter)
{
if (concreteSetter == null) {
throw new NullPointerException("concreteSetter is null");
} | if (!isValidSetter(concreteSetter)) { |
martint/jmxutils | src/main/java/org/weakref/jmx/guice/SetMapping.java | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
| import com.google.common.reflect.TypeParameter;
import com.google.common.reflect.TypeToken;
import com.google.inject.Key;
import org.weakref.jmx.ObjectNameGenerator;
import javax.management.ObjectName;
import java.lang.reflect.Type;
import java.util.Set;
import java.util.function.BiFunction; | package org.weakref.jmx.guice;
class SetMapping<T>
{ | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
// Path: src/main/java/org/weakref/jmx/guice/SetMapping.java
import com.google.common.reflect.TypeParameter;
import com.google.common.reflect.TypeToken;
import com.google.inject.Key;
import org.weakref.jmx.ObjectNameGenerator;
import javax.management.ObjectName;
import java.lang.reflect.Type;
import java.util.Set;
import java.util.function.BiFunction;
package org.weakref.jmx.guice;
class SetMapping<T>
{ | private final BiFunction<ObjectNameGenerator, T, ObjectName> objectNameFunction; |
martint/jmxutils | src/main/java/org/weakref/jmx/guice/MapExportBinder.java | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
| import com.google.inject.multibindings.Multibinder;
import org.weakref.jmx.ObjectNameGenerator;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.util.Map.Entry;
import java.util.function.BiFunction; | package org.weakref.jmx.guice;
public class MapExportBinder<K, V>
{
protected final Multibinder<MapMapping<?, ?>> binder;
protected final Class<K> keyClass;
private final Class<V> valueClass;
MapExportBinder(Multibinder<MapMapping<?, ?>> binder, Class<K> keyClass, Class<V> valueClass)
{
this.binder = binder;
this.keyClass = keyClass;
this.valueClass = valueClass;
}
public void withGeneratedName(NamingFunction<V> valueNamingFunction)
{ | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
// Path: src/main/java/org/weakref/jmx/guice/MapExportBinder.java
import com.google.inject.multibindings.Multibinder;
import org.weakref.jmx.ObjectNameGenerator;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.util.Map.Entry;
import java.util.function.BiFunction;
package org.weakref.jmx.guice;
public class MapExportBinder<K, V>
{
protected final Multibinder<MapMapping<?, ?>> binder;
protected final Class<K> keyClass;
private final Class<V> valueClass;
MapExportBinder(Multibinder<MapMapping<?, ?>> binder, Class<K> keyClass, Class<V> valueClass)
{
this.binder = binder;
this.keyClass = keyClass;
this.valueClass = valueClass;
}
public void withGeneratedName(NamingFunction<V> valueNamingFunction)
{ | BiFunction<ObjectNameGenerator, Entry<K, V>, ObjectName> nameFactory = (factory, entry) -> { |
martint/jmxutils | src/main/java/org/weakref/jmx/ObjectNameBuilder.java | // Path: src/main/java/org/weakref/jmx/ObjectNames.java
// static String quoteValueIfNecessary(String name)
// {
// boolean needQuote = false;
// StringBuilder builder = new StringBuilder("\"");
// for (int i = 0; i < name.length(); ++i) {
// char c = name.charAt(i);
// switch (c) {
// case ':':
// case ',':
// case '=':
// needQuote = true;
// builder.append(c);
// break;
// case '\"':
// case '?':
// case '*':
// needQuote = true;
// builder.append('\\');
// builder.append(c);
// break;
// case '\n':
// needQuote = true;
// builder.append("\\n");
// break;
// case '\\':
// builder.append("\\\\");
// break;
// default:
// builder.append(c);
// }
// }
//
// if (needQuote) {
// name = builder.append('\"').toString();
// }
// return name;
// }
| import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import static org.weakref.jmx.ObjectNames.quoteValueIfNecessary; | package org.weakref.jmx;
public class ObjectNameBuilder
{
private static final Pattern BAD_PACKAGENAME_PATTERN = Pattern.compile("[:?*]");
private final StringBuilder objectName;
private final Set<String> properties = new HashSet<>();
public ObjectNameBuilder(String domain)
{
requireNonNull(domain, "domain is null");
checkArgument(!BAD_PACKAGENAME_PATTERN.matcher(domain).find(), "domain is invalid");
this.objectName = new StringBuilder(domain);
}
public ObjectNameBuilder withProperty(String name, String value)
{
checkArgument(!properties.contains(name), "Duplicate property name: %s", name);
if (properties.isEmpty()) {
objectName.append(":");
}
else {
objectName.append(",");
}
| // Path: src/main/java/org/weakref/jmx/ObjectNames.java
// static String quoteValueIfNecessary(String name)
// {
// boolean needQuote = false;
// StringBuilder builder = new StringBuilder("\"");
// for (int i = 0; i < name.length(); ++i) {
// char c = name.charAt(i);
// switch (c) {
// case ':':
// case ',':
// case '=':
// needQuote = true;
// builder.append(c);
// break;
// case '\"':
// case '?':
// case '*':
// needQuote = true;
// builder.append('\\');
// builder.append(c);
// break;
// case '\n':
// needQuote = true;
// builder.append("\\n");
// break;
// case '\\':
// builder.append("\\\\");
// break;
// default:
// builder.append(c);
// }
// }
//
// if (needQuote) {
// name = builder.append('\"').toString();
// }
// return name;
// }
// Path: src/main/java/org/weakref/jmx/ObjectNameBuilder.java
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import static org.weakref.jmx.ObjectNames.quoteValueIfNecessary;
package org.weakref.jmx;
public class ObjectNameBuilder
{
private static final Pattern BAD_PACKAGENAME_PATTERN = Pattern.compile("[:?*]");
private final StringBuilder objectName;
private final Set<String> properties = new HashSet<>();
public ObjectNameBuilder(String domain)
{
requireNonNull(domain, "domain is null");
checkArgument(!BAD_PACKAGENAME_PATTERN.matcher(domain).find(), "domain is invalid");
this.objectName = new StringBuilder(domain);
}
public ObjectNameBuilder withProperty(String name, String value)
{
checkArgument(!properties.contains(name), "Duplicate property name: %s", name);
if (properties.isEmpty()) {
objectName.append(":");
}
else {
objectName.append(",");
}
| objectName.append(name).append('=').append(quoteValueIfNecessary(value)); |
martint/jmxutils | src/main/java/org/weakref/jmx/guice/Mapping.java | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
| import com.google.inject.Key;
import org.weakref.jmx.ObjectNameGenerator;
import java.util.function.Function; | /**
* Copyright 2009 Martin Traverso
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.weakref.jmx.guice;
class Mapping
{ | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
// Path: src/main/java/org/weakref/jmx/guice/Mapping.java
import com.google.inject.Key;
import org.weakref.jmx.ObjectNameGenerator;
import java.util.function.Function;
/**
* Copyright 2009 Martin Traverso
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.weakref.jmx.guice;
class Mapping
{ | private final Function<ObjectNameGenerator, String> nameFactory; |
martint/jmxutils | src/main/java/org/weakref/jmx/AnnotationUtils.java | // Path: src/main/java/org/weakref/jmx/JmxException.java
// public enum Reason
// {
// INVALID_ANNOTATION,
// MALFORMED_OBJECT_NAME,
// INSTANCE_ALREADY_EXISTS,
// INSTANCE_NOT_FOUND,
// MBEAN_REGISTRATION
// }
| import java.util.Set;
import java.util.TreeMap;
import static java.util.Arrays.asList;
import org.weakref.jmx.JmxException.Reason;
import javax.management.Descriptor;
import javax.management.DescriptorKey;
import javax.management.ImmutableDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map; | }
}
}
Collections.addAll(result, annotations);
}
private static void processAnnotation(Annotation annotation, Map<String, Object> fieldsCollector)
{
// for each field in the annotation
for (Method field : annotation.annotationType().getMethods()) {
// if the field is annotated with the descriptor key
DescriptorKey descriptorKey = field.getAnnotation(DescriptorKey.class);
if (descriptorKey == null) {
continue;
}
// name is the name of the method
String name = descriptorKey.value();
// invoke method to get the value
Object value;
try {
value = field.invoke(annotation);
}
catch (Exception e) {
Throwable cause = e;
if (e instanceof InvocationTargetException) {
cause = e.getCause();
} | // Path: src/main/java/org/weakref/jmx/JmxException.java
// public enum Reason
// {
// INVALID_ANNOTATION,
// MALFORMED_OBJECT_NAME,
// INSTANCE_ALREADY_EXISTS,
// INSTANCE_NOT_FOUND,
// MBEAN_REGISTRATION
// }
// Path: src/main/java/org/weakref/jmx/AnnotationUtils.java
import java.util.Set;
import java.util.TreeMap;
import static java.util.Arrays.asList;
import org.weakref.jmx.JmxException.Reason;
import javax.management.Descriptor;
import javax.management.DescriptorKey;
import javax.management.ImmutableDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
}
}
}
Collections.addAll(result, annotations);
}
private static void processAnnotation(Annotation annotation, Map<String, Object> fieldsCollector)
{
// for each field in the annotation
for (Method field : annotation.annotationType().getMethods()) {
// if the field is annotated with the descriptor key
DescriptorKey descriptorKey = field.getAnnotation(DescriptorKey.class);
if (descriptorKey == null) {
continue;
}
// name is the name of the method
String name = descriptorKey.value();
// invoke method to get the value
Object value;
try {
value = field.invoke(annotation);
}
catch (Exception e) {
Throwable cause = e;
if (e instanceof InvocationTargetException) {
cause = e.getCause();
} | throw new JmxException(Reason.INVALID_ANNOTATION, cause, |
martint/jmxutils | src/main/java/org/weakref/jmx/guice/MappingNameFactory.java | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
| import org.weakref.jmx.ObjectNameGenerator; | package org.weakref.jmx.guice;
interface MappingNameFactory
{ | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
// Path: src/main/java/org/weakref/jmx/guice/MappingNameFactory.java
import org.weakref.jmx.ObjectNameGenerator;
package org.weakref.jmx.guice;
interface MappingNameFactory
{ | String getName(ObjectNameGenerator objectNameGenerator); |
martint/jmxutils | src/main/java/org/weakref/jmx/guice/StringMapExportBinder.java | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
| import com.google.inject.multibindings.Multibinder;
import org.weakref.jmx.ObjectNameGenerator;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.util.Map.Entry;
import java.util.function.BiFunction; | package org.weakref.jmx.guice;
public class StringMapExportBinder<V>
extends MapExportBinder<String, V>
{
private final Class<V> valueClass;
StringMapExportBinder(Multibinder<MapMapping<?, ?>> binder, Class<V> valueClass)
{
super(binder, String.class, valueClass);
this.valueClass = valueClass;
}
public void withGeneratedName()
{ | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
// Path: src/main/java/org/weakref/jmx/guice/StringMapExportBinder.java
import com.google.inject.multibindings.Multibinder;
import org.weakref.jmx.ObjectNameGenerator;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.util.Map.Entry;
import java.util.function.BiFunction;
package org.weakref.jmx.guice;
public class StringMapExportBinder<V>
extends MapExportBinder<String, V>
{
private final Class<V> valueClass;
StringMapExportBinder(Multibinder<MapMapping<?, ?>> binder, Class<V> valueClass)
{
super(binder, String.class, valueClass);
this.valueClass = valueClass;
}
public void withGeneratedName()
{ | BiFunction<ObjectNameGenerator, Entry<String, V>, ObjectName> nameFactory = (factory, entry) -> { |
martint/jmxutils | src/main/java/org/weakref/jmx/guice/MapMapping.java | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
| import com.google.common.reflect.TypeParameter;
import com.google.common.reflect.TypeToken;
import com.google.inject.Key;
import org.weakref.jmx.ObjectNameGenerator;
import javax.management.ObjectName;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.BiFunction; | package org.weakref.jmx.guice;
class MapMapping<K, V>
{ | // Path: src/main/java/org/weakref/jmx/ObjectNameGenerator.java
// public interface ObjectNameGenerator
// {
// static ObjectNameGenerator defaultObjectNameGenerator()
// {
// return (type, properties) -> new ObjectNameBuilder(type.getPackage().getName())
// .withProperties(properties)
// .build();
// }
//
// default String generatedNameOf(Class<?> type)
// {
// return generatedNameOf(type, ImmutableMap.of("name", type.getSimpleName()));
// }
//
// default String generatedNameOf(Class<?> type, String name)
// {
// return generatedNameOf(type, ImmutableMap.<String, String>builder()
// .put("type", type.getSimpleName())
// .put("name", name)
// .build());
// }
//
// String generatedNameOf(Class<?> type, Map<String, String> properties);
// }
// Path: src/main/java/org/weakref/jmx/guice/MapMapping.java
import com.google.common.reflect.TypeParameter;
import com.google.common.reflect.TypeToken;
import com.google.inject.Key;
import org.weakref.jmx.ObjectNameGenerator;
import javax.management.ObjectName;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.BiFunction;
package org.weakref.jmx.guice;
class MapMapping<K, V>
{ | private final BiFunction<ObjectNameGenerator, Entry<K, V>, ObjectName> objectNameFunction; |
martint/jmxutils | src/main/java/org/weakref/jmx/MBeanBuilder.java | // Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static String getAttributeName(Method method)
// {
// Matcher matcher = getterOrSetterPattern.matcher(method.getName());
// if (!matcher.matches()) {
// throw new IllegalArgumentException("method does not represent a getter or setter");
// }
// return matcher.group(2);
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isGetter(Method method)
// {
// String methodName = method.getName();
// return (methodName.startsWith("get") || methodName.startsWith("is")) && isValidGetter(method);
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isSetter(Method method)
// {
// return method.getName().startsWith("set") && isValidSetter(method);
// }
| import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static org.weakref.jmx.ReflectionUtils.getAttributeName;
import static org.weakref.jmx.ReflectionUtils.isGetter;
import static org.weakref.jmx.ReflectionUtils.isSetter; | /**
* Copyright 2009 Martin Traverso
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.weakref.jmx;
final class MBeanBuilder
{
private final String className;
private final List<MBeanAttributeBuilder> attributeBuilders = new ArrayList<>();
private final List<MBeanOperationBuilder> operationBuilders = new ArrayList<>();
private String description;
private MBeanBuilder(String className)
{
this.className = className;
}
public static MBeanBuilder from(String className)
{
return new MBeanBuilder(className);
}
public static MBeanBuilder from(Object object)
{
return new MBeanBuilder(object);
}
public MBeanBuilder(Object target)
{
if (target == null) {
throw new NullPointerException("target is null");
}
Map<String, MBeanAttributeBuilder> attributeBuilders = new TreeMap<>();
for (Map.Entry<Method, Method> entry : AnnotationUtils.findManagedMethods(target.getClass()).entrySet()) {
Method concreteMethod = entry.getKey();
Method annotatedMethod = entry.getValue();
| // Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static String getAttributeName(Method method)
// {
// Matcher matcher = getterOrSetterPattern.matcher(method.getName());
// if (!matcher.matches()) {
// throw new IllegalArgumentException("method does not represent a getter or setter");
// }
// return matcher.group(2);
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isGetter(Method method)
// {
// String methodName = method.getName();
// return (methodName.startsWith("get") || methodName.startsWith("is")) && isValidGetter(method);
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isSetter(Method method)
// {
// return method.getName().startsWith("set") && isValidSetter(method);
// }
// Path: src/main/java/org/weakref/jmx/MBeanBuilder.java
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static org.weakref.jmx.ReflectionUtils.getAttributeName;
import static org.weakref.jmx.ReflectionUtils.isGetter;
import static org.weakref.jmx.ReflectionUtils.isSetter;
/**
* Copyright 2009 Martin Traverso
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.weakref.jmx;
final class MBeanBuilder
{
private final String className;
private final List<MBeanAttributeBuilder> attributeBuilders = new ArrayList<>();
private final List<MBeanOperationBuilder> operationBuilders = new ArrayList<>();
private String description;
private MBeanBuilder(String className)
{
this.className = className;
}
public static MBeanBuilder from(String className)
{
return new MBeanBuilder(className);
}
public static MBeanBuilder from(Object object)
{
return new MBeanBuilder(object);
}
public MBeanBuilder(Object target)
{
if (target == null) {
throw new NullPointerException("target is null");
}
Map<String, MBeanAttributeBuilder> attributeBuilders = new TreeMap<>();
for (Map.Entry<Method, Method> entry : AnnotationUtils.findManagedMethods(target.getClass()).entrySet()) {
Method concreteMethod = entry.getKey();
Method annotatedMethod = entry.getValue();
| if (isGetter(concreteMethod) || isSetter(concreteMethod)) { // is it an attribute? |
martint/jmxutils | src/main/java/org/weakref/jmx/MBeanBuilder.java | // Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static String getAttributeName(Method method)
// {
// Matcher matcher = getterOrSetterPattern.matcher(method.getName());
// if (!matcher.matches()) {
// throw new IllegalArgumentException("method does not represent a getter or setter");
// }
// return matcher.group(2);
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isGetter(Method method)
// {
// String methodName = method.getName();
// return (methodName.startsWith("get") || methodName.startsWith("is")) && isValidGetter(method);
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isSetter(Method method)
// {
// return method.getName().startsWith("set") && isValidSetter(method);
// }
| import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static org.weakref.jmx.ReflectionUtils.getAttributeName;
import static org.weakref.jmx.ReflectionUtils.isGetter;
import static org.weakref.jmx.ReflectionUtils.isSetter; | /**
* Copyright 2009 Martin Traverso
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.weakref.jmx;
final class MBeanBuilder
{
private final String className;
private final List<MBeanAttributeBuilder> attributeBuilders = new ArrayList<>();
private final List<MBeanOperationBuilder> operationBuilders = new ArrayList<>();
private String description;
private MBeanBuilder(String className)
{
this.className = className;
}
public static MBeanBuilder from(String className)
{
return new MBeanBuilder(className);
}
public static MBeanBuilder from(Object object)
{
return new MBeanBuilder(object);
}
public MBeanBuilder(Object target)
{
if (target == null) {
throw new NullPointerException("target is null");
}
Map<String, MBeanAttributeBuilder> attributeBuilders = new TreeMap<>();
for (Map.Entry<Method, Method> entry : AnnotationUtils.findManagedMethods(target.getClass()).entrySet()) {
Method concreteMethod = entry.getKey();
Method annotatedMethod = entry.getValue();
| // Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static String getAttributeName(Method method)
// {
// Matcher matcher = getterOrSetterPattern.matcher(method.getName());
// if (!matcher.matches()) {
// throw new IllegalArgumentException("method does not represent a getter or setter");
// }
// return matcher.group(2);
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isGetter(Method method)
// {
// String methodName = method.getName();
// return (methodName.startsWith("get") || methodName.startsWith("is")) && isValidGetter(method);
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isSetter(Method method)
// {
// return method.getName().startsWith("set") && isValidSetter(method);
// }
// Path: src/main/java/org/weakref/jmx/MBeanBuilder.java
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static org.weakref.jmx.ReflectionUtils.getAttributeName;
import static org.weakref.jmx.ReflectionUtils.isGetter;
import static org.weakref.jmx.ReflectionUtils.isSetter;
/**
* Copyright 2009 Martin Traverso
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.weakref.jmx;
final class MBeanBuilder
{
private final String className;
private final List<MBeanAttributeBuilder> attributeBuilders = new ArrayList<>();
private final List<MBeanOperationBuilder> operationBuilders = new ArrayList<>();
private String description;
private MBeanBuilder(String className)
{
this.className = className;
}
public static MBeanBuilder from(String className)
{
return new MBeanBuilder(className);
}
public static MBeanBuilder from(Object object)
{
return new MBeanBuilder(object);
}
public MBeanBuilder(Object target)
{
if (target == null) {
throw new NullPointerException("target is null");
}
Map<String, MBeanAttributeBuilder> attributeBuilders = new TreeMap<>();
for (Map.Entry<Method, Method> entry : AnnotationUtils.findManagedMethods(target.getClass()).entrySet()) {
Method concreteMethod = entry.getKey();
Method annotatedMethod = entry.getValue();
| if (isGetter(concreteMethod) || isSetter(concreteMethod)) { // is it an attribute? |
martint/jmxutils | src/main/java/org/weakref/jmx/MBeanBuilder.java | // Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static String getAttributeName(Method method)
// {
// Matcher matcher = getterOrSetterPattern.matcher(method.getName());
// if (!matcher.matches()) {
// throw new IllegalArgumentException("method does not represent a getter or setter");
// }
// return matcher.group(2);
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isGetter(Method method)
// {
// String methodName = method.getName();
// return (methodName.startsWith("get") || methodName.startsWith("is")) && isValidGetter(method);
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isSetter(Method method)
// {
// return method.getName().startsWith("set") && isValidSetter(method);
// }
| import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static org.weakref.jmx.ReflectionUtils.getAttributeName;
import static org.weakref.jmx.ReflectionUtils.isGetter;
import static org.weakref.jmx.ReflectionUtils.isSetter; | /**
* Copyright 2009 Martin Traverso
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.weakref.jmx;
final class MBeanBuilder
{
private final String className;
private final List<MBeanAttributeBuilder> attributeBuilders = new ArrayList<>();
private final List<MBeanOperationBuilder> operationBuilders = new ArrayList<>();
private String description;
private MBeanBuilder(String className)
{
this.className = className;
}
public static MBeanBuilder from(String className)
{
return new MBeanBuilder(className);
}
public static MBeanBuilder from(Object object)
{
return new MBeanBuilder(object);
}
public MBeanBuilder(Object target)
{
if (target == null) {
throw new NullPointerException("target is null");
}
Map<String, MBeanAttributeBuilder> attributeBuilders = new TreeMap<>();
for (Map.Entry<Method, Method> entry : AnnotationUtils.findManagedMethods(target.getClass()).entrySet()) {
Method concreteMethod = entry.getKey();
Method annotatedMethod = entry.getValue();
if (isGetter(concreteMethod) || isSetter(concreteMethod)) { // is it an attribute? | // Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static String getAttributeName(Method method)
// {
// Matcher matcher = getterOrSetterPattern.matcher(method.getName());
// if (!matcher.matches()) {
// throw new IllegalArgumentException("method does not represent a getter or setter");
// }
// return matcher.group(2);
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isGetter(Method method)
// {
// String methodName = method.getName();
// return (methodName.startsWith("get") || methodName.startsWith("is")) && isValidGetter(method);
// }
//
// Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static boolean isSetter(Method method)
// {
// return method.getName().startsWith("set") && isValidSetter(method);
// }
// Path: src/main/java/org/weakref/jmx/MBeanBuilder.java
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static org.weakref.jmx.ReflectionUtils.getAttributeName;
import static org.weakref.jmx.ReflectionUtils.isGetter;
import static org.weakref.jmx.ReflectionUtils.isSetter;
/**
* Copyright 2009 Martin Traverso
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.weakref.jmx;
final class MBeanBuilder
{
private final String className;
private final List<MBeanAttributeBuilder> attributeBuilders = new ArrayList<>();
private final List<MBeanOperationBuilder> operationBuilders = new ArrayList<>();
private String description;
private MBeanBuilder(String className)
{
this.className = className;
}
public static MBeanBuilder from(String className)
{
return new MBeanBuilder(className);
}
public static MBeanBuilder from(Object object)
{
return new MBeanBuilder(object);
}
public MBeanBuilder(Object target)
{
if (target == null) {
throw new NullPointerException("target is null");
}
Map<String, MBeanAttributeBuilder> attributeBuilders = new TreeMap<>();
for (Map.Entry<Method, Method> entry : AnnotationUtils.findManagedMethods(target.getClass()).entrySet()) {
Method concreteMethod = entry.getKey();
Method annotatedMethod = entry.getValue();
if (isGetter(concreteMethod) || isSetter(concreteMethod)) { // is it an attribute? | String attributeName = getAttributeName(concreteMethod); |
martint/jmxutils | src/main/java/org/weakref/jmx/ReflectionMBeanAttribute.java | // Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static Object invoke(Object target, Method method, Object... params)
// throws MBeanException, ReflectionException
// {
// assertNotNull(target, "target");
// assertNotNull(target, "method");
// assertNotNull(target, "params");
//
// try {
// Object result = method.invoke(target, params);
// return result;
// }
// catch (InvocationTargetException e) {
// // unwrap exception
// Throwable targetException = e.getTargetException();
// if (targetException instanceof RuntimeException) {
// throw new MBeanException(
// (RuntimeException) targetException,
// "RuntimeException occurred while invoking " + toSimpleName(method));
// }
// else if (targetException instanceof ReflectionException) {
// // allow ReflectionException to passthrough
// throw (ReflectionException) targetException;
// }
// else if (targetException instanceof MBeanException) {
// // allow MBeanException to passthrough
// throw (MBeanException) targetException;
// }
// else if (targetException instanceof Exception) {
// throw new MBeanException(
// (Exception) targetException,
// "Exception occurred while invoking " + toSimpleName(method));
// }
// else if (targetException instanceof Error) {
// throw new RuntimeErrorException(
// (Error) targetException,
// "Error occurred while invoking " + toSimpleName(method));
// }
// else {
// throw new RuntimeErrorException(
// new AssertionError(targetException),
// "Unexpected throwable occurred while invoking " + toSimpleName(method));
// }
// }
// catch (RuntimeException e) {
// throw new RuntimeOperationsException(e, "RuntimeException occurred while invoking " + toSimpleName(method));
// }
// catch (IllegalAccessException e) {
// throw new ReflectionException(e, "IllegalAccessException occurred while invoking " + toSimpleName(method));
// }
// catch (Error err) {
// throw new RuntimeErrorException(err, "Error occurred while invoking " + toSimpleName(method));
// }
// catch (Exception e) {
// throw new ReflectionException(e, "Exception occurred while invoking " + toSimpleName(method));
// }
// }
| import static org.weakref.jmx.ReflectionUtils.invoke;
import javax.management.AttributeNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.ReflectionException;
import java.lang.reflect.Method; | this.target = target;
this.name = info.getName();
this.getter = getter;
this.setter = setter;
}
@Override
public MBeanAttributeInfo getInfo()
{
return info;
}
public Object getTarget()
{
return target;
}
@Override
public String getName()
{
return name;
}
@Override
public Object getValue()
throws AttributeNotFoundException, MBeanException, ReflectionException
{
if (getter == null) {
throw new AttributeNotFoundException(name + " is write-only");
} | // Path: src/main/java/org/weakref/jmx/ReflectionUtils.java
// public static Object invoke(Object target, Method method, Object... params)
// throws MBeanException, ReflectionException
// {
// assertNotNull(target, "target");
// assertNotNull(target, "method");
// assertNotNull(target, "params");
//
// try {
// Object result = method.invoke(target, params);
// return result;
// }
// catch (InvocationTargetException e) {
// // unwrap exception
// Throwable targetException = e.getTargetException();
// if (targetException instanceof RuntimeException) {
// throw new MBeanException(
// (RuntimeException) targetException,
// "RuntimeException occurred while invoking " + toSimpleName(method));
// }
// else if (targetException instanceof ReflectionException) {
// // allow ReflectionException to passthrough
// throw (ReflectionException) targetException;
// }
// else if (targetException instanceof MBeanException) {
// // allow MBeanException to passthrough
// throw (MBeanException) targetException;
// }
// else if (targetException instanceof Exception) {
// throw new MBeanException(
// (Exception) targetException,
// "Exception occurred while invoking " + toSimpleName(method));
// }
// else if (targetException instanceof Error) {
// throw new RuntimeErrorException(
// (Error) targetException,
// "Error occurred while invoking " + toSimpleName(method));
// }
// else {
// throw new RuntimeErrorException(
// new AssertionError(targetException),
// "Unexpected throwable occurred while invoking " + toSimpleName(method));
// }
// }
// catch (RuntimeException e) {
// throw new RuntimeOperationsException(e, "RuntimeException occurred while invoking " + toSimpleName(method));
// }
// catch (IllegalAccessException e) {
// throw new ReflectionException(e, "IllegalAccessException occurred while invoking " + toSimpleName(method));
// }
// catch (Error err) {
// throw new RuntimeErrorException(err, "Error occurred while invoking " + toSimpleName(method));
// }
// catch (Exception e) {
// throw new ReflectionException(e, "Exception occurred while invoking " + toSimpleName(method));
// }
// }
// Path: src/main/java/org/weakref/jmx/ReflectionMBeanAttribute.java
import static org.weakref.jmx.ReflectionUtils.invoke;
import javax.management.AttributeNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.ReflectionException;
import java.lang.reflect.Method;
this.target = target;
this.name = info.getName();
this.getter = getter;
this.setter = setter;
}
@Override
public MBeanAttributeInfo getInfo()
{
return info;
}
public Object getTarget()
{
return target;
}
@Override
public String getName()
{
return name;
}
@Override
public Object getValue()
throws AttributeNotFoundException, MBeanException, ReflectionException
{
if (getter == null) {
throw new AttributeNotFoundException(name + " is write-only");
} | Object result = invoke(target, getter); |
mickare/xserver | XServer-API/src/main/java/de/mickare/xserver/net/XServer.java | // Path: XServer-API/src/main/java/de/mickare/xserver/AbstractXServerManager.java
// public interface AbstractXServerManager {
//
// public abstract void start() throws IOException;
//
// public abstract void start_async();
//
// public abstract void reconnectAll_soft();
//
// public abstract void reconnectAll_forced();
//
// public abstract void stop() throws IOException;
//
// /**
// * Reload configuration
// *
// * @throws IOException
// *
// * @throws InvalidConfigurationException
// */
// public abstract void reload() throws IOException;
//
// public abstract XServer getHomeServer();
//
// public abstract XServer getServer(String servername);
//
// public abstract XServerPlugin getPlugin();
//
// public abstract Logger getLogger();
//
// public abstract ServerThreadPoolExecutor getThreadPool();
//
// public abstract SocketFactory getSocketFactory();
//
// public abstract XServer getXServer(String name);
//
// /**
// * Get the list of all available servers
// *
// * @return servers
// */
// public abstract Set<XServer> getServers();
//
// /**
// * Get a string list of all servernames
// *
// * @return
// */
// public abstract String[] getServernames();
//
// /**
// * Get the XServer Object with the servername name
// *
// * @param name servername
// * @return XServer with that name
// */
// public abstract XServer getServerIgnoreCase(String name);
//
// /**
// * Get the XServer Object via host and port
// *
// * @param host
// * @param port
// * @return XServer
// */
// public abstract XServer getServer(String host, int port);
//
// public abstract String getHomeServerName();
//
// public abstract Message createMessage(String subChannel, byte[] content);
//
// public abstract Message readMessage(XServer sender, byte[] data) throws IOException;
//
// public abstract EventHandler<?> getEventHandler();
//
// public abstract void registerOwnListeners();
//
// Set<XServer> getServers(XGroup group);
//
// Set<? extends XGroup> getGroups();
//
// XGroup getGroupByName(String name);
//
// }
//
// Path: XServer-API/src/main/java/de/mickare/xserver/Message.java
// public interface Message {
//
// /**
// * Get Sender Server Name
// *
// * @return sender name
// */
// public abstract XServer getSender();
//
// /**
// * SubChannel
// *
// * @return subchannel name
// */
// public abstract String getSubChannel();
//
// /**
// * Get the content of this message...
// *
// * @return byte array
// */
// public abstract byte[] getContent();
//
// /**
// * Get the compiled byte array of this message...
// *
// * @return byte array
// * @throws IOException
// */
// public abstract byte[] getData() throws IOException;
//
// }
//
// Path: XServer-API/src/main/java/de/mickare/xserver/XType.java
// public enum XType {
// Other(0, "Other"), Bukkit(1, "Bukkit"), BungeeCord(2, "BungeeCord");
//
// private final int number;
// private final String name;
//
// private XType(int number, String name) {
// this.number = number;
// this.name = name;
// }
//
// public static XType getByNumber(int number) {
// switch (number) {
// case 1:
// return Bukkit;
// case 2:
// return BungeeCord;
// default:
// return Other;
// }
// }
//
// public int getNumber() {
// return number;
// }
//
// public String getName() {
// return name;
// }
//
// }
//
// Path: XServer-API/src/main/java/de/mickare/xserver/exceptions/NotInitializedException.java
// @SuppressWarnings("serial")
// public class NotInitializedException extends RuntimeException {
//
// public NotInitializedException() {}
//
// public NotInitializedException(String reason) {
// super(reason);
// }
//
// public NotInitializedException(Throwable cause) {
// super(cause);
// }
//
// public NotInitializedException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// }
| import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Set;
import de.mickare.xserver.AbstractXServerManager;
import de.mickare.xserver.Message;
import de.mickare.xserver.XGroup;
import de.mickare.xserver.XType;
import de.mickare.xserver.exceptions.NotInitializedException; | package de.mickare.xserver.net;
public interface XServer {
/**
* Try to establish a connection to this server
*
* @throws UnknownHostException
* @throws IOException
* @throws InterruptedException
* @throws NotInitializedException
*/
public abstract void connect() throws UnknownHostException, IOException, InterruptedException, NotInitializedException;
/**
* Returns the connection status
*
* @return true if connected, otherwise false
*/
public abstract boolean isConnected();
/**
* Disconnect from this server
*/
public abstract void disconnect();
/**
* Get the Server Name
*
* @return name
*/
public abstract String getName();
/**
* Get the host/ip address
*
* @return host
*/
public abstract String getHost();
/**
* Get the port
*
* @return port
*/
public abstract int getPort();
/**
* Get the md5-encrypted password that is needed to login to this server
*
* @return
*/
public abstract String getPassword();
/**
* Send a data Message to this server
*
* @param message
* @return true, if queued for sending into connection (= did send); otherwise false (= message
* cached)
* @throws IOException
*/ | // Path: XServer-API/src/main/java/de/mickare/xserver/AbstractXServerManager.java
// public interface AbstractXServerManager {
//
// public abstract void start() throws IOException;
//
// public abstract void start_async();
//
// public abstract void reconnectAll_soft();
//
// public abstract void reconnectAll_forced();
//
// public abstract void stop() throws IOException;
//
// /**
// * Reload configuration
// *
// * @throws IOException
// *
// * @throws InvalidConfigurationException
// */
// public abstract void reload() throws IOException;
//
// public abstract XServer getHomeServer();
//
// public abstract XServer getServer(String servername);
//
// public abstract XServerPlugin getPlugin();
//
// public abstract Logger getLogger();
//
// public abstract ServerThreadPoolExecutor getThreadPool();
//
// public abstract SocketFactory getSocketFactory();
//
// public abstract XServer getXServer(String name);
//
// /**
// * Get the list of all available servers
// *
// * @return servers
// */
// public abstract Set<XServer> getServers();
//
// /**
// * Get a string list of all servernames
// *
// * @return
// */
// public abstract String[] getServernames();
//
// /**
// * Get the XServer Object with the servername name
// *
// * @param name servername
// * @return XServer with that name
// */
// public abstract XServer getServerIgnoreCase(String name);
//
// /**
// * Get the XServer Object via host and port
// *
// * @param host
// * @param port
// * @return XServer
// */
// public abstract XServer getServer(String host, int port);
//
// public abstract String getHomeServerName();
//
// public abstract Message createMessage(String subChannel, byte[] content);
//
// public abstract Message readMessage(XServer sender, byte[] data) throws IOException;
//
// public abstract EventHandler<?> getEventHandler();
//
// public abstract void registerOwnListeners();
//
// Set<XServer> getServers(XGroup group);
//
// Set<? extends XGroup> getGroups();
//
// XGroup getGroupByName(String name);
//
// }
//
// Path: XServer-API/src/main/java/de/mickare/xserver/Message.java
// public interface Message {
//
// /**
// * Get Sender Server Name
// *
// * @return sender name
// */
// public abstract XServer getSender();
//
// /**
// * SubChannel
// *
// * @return subchannel name
// */
// public abstract String getSubChannel();
//
// /**
// * Get the content of this message...
// *
// * @return byte array
// */
// public abstract byte[] getContent();
//
// /**
// * Get the compiled byte array of this message...
// *
// * @return byte array
// * @throws IOException
// */
// public abstract byte[] getData() throws IOException;
//
// }
//
// Path: XServer-API/src/main/java/de/mickare/xserver/XType.java
// public enum XType {
// Other(0, "Other"), Bukkit(1, "Bukkit"), BungeeCord(2, "BungeeCord");
//
// private final int number;
// private final String name;
//
// private XType(int number, String name) {
// this.number = number;
// this.name = name;
// }
//
// public static XType getByNumber(int number) {
// switch (number) {
// case 1:
// return Bukkit;
// case 2:
// return BungeeCord;
// default:
// return Other;
// }
// }
//
// public int getNumber() {
// return number;
// }
//
// public String getName() {
// return name;
// }
//
// }
//
// Path: XServer-API/src/main/java/de/mickare/xserver/exceptions/NotInitializedException.java
// @SuppressWarnings("serial")
// public class NotInitializedException extends RuntimeException {
//
// public NotInitializedException() {}
//
// public NotInitializedException(String reason) {
// super(reason);
// }
//
// public NotInitializedException(Throwable cause) {
// super(cause);
// }
//
// public NotInitializedException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// }
// Path: XServer-API/src/main/java/de/mickare/xserver/net/XServer.java
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Set;
import de.mickare.xserver.AbstractXServerManager;
import de.mickare.xserver.Message;
import de.mickare.xserver.XGroup;
import de.mickare.xserver.XType;
import de.mickare.xserver.exceptions.NotInitializedException;
package de.mickare.xserver.net;
public interface XServer {
/**
* Try to establish a connection to this server
*
* @throws UnknownHostException
* @throws IOException
* @throws InterruptedException
* @throws NotInitializedException
*/
public abstract void connect() throws UnknownHostException, IOException, InterruptedException, NotInitializedException;
/**
* Returns the connection status
*
* @return true if connected, otherwise false
*/
public abstract boolean isConnected();
/**
* Disconnect from this server
*/
public abstract void disconnect();
/**
* Get the Server Name
*
* @return name
*/
public abstract String getName();
/**
* Get the host/ip address
*
* @return host
*/
public abstract String getHost();
/**
* Get the port
*
* @return port
*/
public abstract int getPort();
/**
* Get the md5-encrypted password that is needed to login to this server
*
* @return
*/
public abstract String getPassword();
/**
* Send a data Message to this server
*
* @param message
* @return true, if queued for sending into connection (= did send); otherwise false (= message
* cached)
* @throws IOException
*/ | public abstract boolean sendMessage(Message message) throws IOException; |
mickare/xserver | XServer-API/src/main/java/de/mickare/xserver/net/XServer.java | // Path: XServer-API/src/main/java/de/mickare/xserver/AbstractXServerManager.java
// public interface AbstractXServerManager {
//
// public abstract void start() throws IOException;
//
// public abstract void start_async();
//
// public abstract void reconnectAll_soft();
//
// public abstract void reconnectAll_forced();
//
// public abstract void stop() throws IOException;
//
// /**
// * Reload configuration
// *
// * @throws IOException
// *
// * @throws InvalidConfigurationException
// */
// public abstract void reload() throws IOException;
//
// public abstract XServer getHomeServer();
//
// public abstract XServer getServer(String servername);
//
// public abstract XServerPlugin getPlugin();
//
// public abstract Logger getLogger();
//
// public abstract ServerThreadPoolExecutor getThreadPool();
//
// public abstract SocketFactory getSocketFactory();
//
// public abstract XServer getXServer(String name);
//
// /**
// * Get the list of all available servers
// *
// * @return servers
// */
// public abstract Set<XServer> getServers();
//
// /**
// * Get a string list of all servernames
// *
// * @return
// */
// public abstract String[] getServernames();
//
// /**
// * Get the XServer Object with the servername name
// *
// * @param name servername
// * @return XServer with that name
// */
// public abstract XServer getServerIgnoreCase(String name);
//
// /**
// * Get the XServer Object via host and port
// *
// * @param host
// * @param port
// * @return XServer
// */
// public abstract XServer getServer(String host, int port);
//
// public abstract String getHomeServerName();
//
// public abstract Message createMessage(String subChannel, byte[] content);
//
// public abstract Message readMessage(XServer sender, byte[] data) throws IOException;
//
// public abstract EventHandler<?> getEventHandler();
//
// public abstract void registerOwnListeners();
//
// Set<XServer> getServers(XGroup group);
//
// Set<? extends XGroup> getGroups();
//
// XGroup getGroupByName(String name);
//
// }
//
// Path: XServer-API/src/main/java/de/mickare/xserver/Message.java
// public interface Message {
//
// /**
// * Get Sender Server Name
// *
// * @return sender name
// */
// public abstract XServer getSender();
//
// /**
// * SubChannel
// *
// * @return subchannel name
// */
// public abstract String getSubChannel();
//
// /**
// * Get the content of this message...
// *
// * @return byte array
// */
// public abstract byte[] getContent();
//
// /**
// * Get the compiled byte array of this message...
// *
// * @return byte array
// * @throws IOException
// */
// public abstract byte[] getData() throws IOException;
//
// }
//
// Path: XServer-API/src/main/java/de/mickare/xserver/XType.java
// public enum XType {
// Other(0, "Other"), Bukkit(1, "Bukkit"), BungeeCord(2, "BungeeCord");
//
// private final int number;
// private final String name;
//
// private XType(int number, String name) {
// this.number = number;
// this.name = name;
// }
//
// public static XType getByNumber(int number) {
// switch (number) {
// case 1:
// return Bukkit;
// case 2:
// return BungeeCord;
// default:
// return Other;
// }
// }
//
// public int getNumber() {
// return number;
// }
//
// public String getName() {
// return name;
// }
//
// }
//
// Path: XServer-API/src/main/java/de/mickare/xserver/exceptions/NotInitializedException.java
// @SuppressWarnings("serial")
// public class NotInitializedException extends RuntimeException {
//
// public NotInitializedException() {}
//
// public NotInitializedException(String reason) {
// super(reason);
// }
//
// public NotInitializedException(Throwable cause) {
// super(cause);
// }
//
// public NotInitializedException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// }
| import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Set;
import de.mickare.xserver.AbstractXServerManager;
import de.mickare.xserver.Message;
import de.mickare.xserver.XGroup;
import de.mickare.xserver.XType;
import de.mickare.xserver.exceptions.NotInitializedException; | package de.mickare.xserver.net;
public interface XServer {
/**
* Try to establish a connection to this server
*
* @throws UnknownHostException
* @throws IOException
* @throws InterruptedException
* @throws NotInitializedException
*/
public abstract void connect() throws UnknownHostException, IOException, InterruptedException, NotInitializedException;
/**
* Returns the connection status
*
* @return true if connected, otherwise false
*/
public abstract boolean isConnected();
/**
* Disconnect from this server
*/
public abstract void disconnect();
/**
* Get the Server Name
*
* @return name
*/
public abstract String getName();
/**
* Get the host/ip address
*
* @return host
*/
public abstract String getHost();
/**
* Get the port
*
* @return port
*/
public abstract int getPort();
/**
* Get the md5-encrypted password that is needed to login to this server
*
* @return
*/
public abstract String getPassword();
/**
* Send a data Message to this server
*
* @param message
* @return true, if queued for sending into connection (= did send); otherwise false (= message
* cached)
* @throws IOException
*/
public abstract boolean sendMessage(Message message) throws IOException;
/**
* Ping this server with a new Ping
*
* @param ping that is used to verify this ping
* @throws InterruptedException
* @throws IOException
*/
public abstract void ping(Ping ping) throws InterruptedException, IOException;
/**
* Send cached packets = queue packets into connection
*/
public abstract void flushCache();
/**
* Get the type of this server
*
* @return Server Type
*/ | // Path: XServer-API/src/main/java/de/mickare/xserver/AbstractXServerManager.java
// public interface AbstractXServerManager {
//
// public abstract void start() throws IOException;
//
// public abstract void start_async();
//
// public abstract void reconnectAll_soft();
//
// public abstract void reconnectAll_forced();
//
// public abstract void stop() throws IOException;
//
// /**
// * Reload configuration
// *
// * @throws IOException
// *
// * @throws InvalidConfigurationException
// */
// public abstract void reload() throws IOException;
//
// public abstract XServer getHomeServer();
//
// public abstract XServer getServer(String servername);
//
// public abstract XServerPlugin getPlugin();
//
// public abstract Logger getLogger();
//
// public abstract ServerThreadPoolExecutor getThreadPool();
//
// public abstract SocketFactory getSocketFactory();
//
// public abstract XServer getXServer(String name);
//
// /**
// * Get the list of all available servers
// *
// * @return servers
// */
// public abstract Set<XServer> getServers();
//
// /**
// * Get a string list of all servernames
// *
// * @return
// */
// public abstract String[] getServernames();
//
// /**
// * Get the XServer Object with the servername name
// *
// * @param name servername
// * @return XServer with that name
// */
// public abstract XServer getServerIgnoreCase(String name);
//
// /**
// * Get the XServer Object via host and port
// *
// * @param host
// * @param port
// * @return XServer
// */
// public abstract XServer getServer(String host, int port);
//
// public abstract String getHomeServerName();
//
// public abstract Message createMessage(String subChannel, byte[] content);
//
// public abstract Message readMessage(XServer sender, byte[] data) throws IOException;
//
// public abstract EventHandler<?> getEventHandler();
//
// public abstract void registerOwnListeners();
//
// Set<XServer> getServers(XGroup group);
//
// Set<? extends XGroup> getGroups();
//
// XGroup getGroupByName(String name);
//
// }
//
// Path: XServer-API/src/main/java/de/mickare/xserver/Message.java
// public interface Message {
//
// /**
// * Get Sender Server Name
// *
// * @return sender name
// */
// public abstract XServer getSender();
//
// /**
// * SubChannel
// *
// * @return subchannel name
// */
// public abstract String getSubChannel();
//
// /**
// * Get the content of this message...
// *
// * @return byte array
// */
// public abstract byte[] getContent();
//
// /**
// * Get the compiled byte array of this message...
// *
// * @return byte array
// * @throws IOException
// */
// public abstract byte[] getData() throws IOException;
//
// }
//
// Path: XServer-API/src/main/java/de/mickare/xserver/XType.java
// public enum XType {
// Other(0, "Other"), Bukkit(1, "Bukkit"), BungeeCord(2, "BungeeCord");
//
// private final int number;
// private final String name;
//
// private XType(int number, String name) {
// this.number = number;
// this.name = name;
// }
//
// public static XType getByNumber(int number) {
// switch (number) {
// case 1:
// return Bukkit;
// case 2:
// return BungeeCord;
// default:
// return Other;
// }
// }
//
// public int getNumber() {
// return number;
// }
//
// public String getName() {
// return name;
// }
//
// }
//
// Path: XServer-API/src/main/java/de/mickare/xserver/exceptions/NotInitializedException.java
// @SuppressWarnings("serial")
// public class NotInitializedException extends RuntimeException {
//
// public NotInitializedException() {}
//
// public NotInitializedException(String reason) {
// super(reason);
// }
//
// public NotInitializedException(Throwable cause) {
// super(cause);
// }
//
// public NotInitializedException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// }
// Path: XServer-API/src/main/java/de/mickare/xserver/net/XServer.java
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Set;
import de.mickare.xserver.AbstractXServerManager;
import de.mickare.xserver.Message;
import de.mickare.xserver.XGroup;
import de.mickare.xserver.XType;
import de.mickare.xserver.exceptions.NotInitializedException;
package de.mickare.xserver.net;
public interface XServer {
/**
* Try to establish a connection to this server
*
* @throws UnknownHostException
* @throws IOException
* @throws InterruptedException
* @throws NotInitializedException
*/
public abstract void connect() throws UnknownHostException, IOException, InterruptedException, NotInitializedException;
/**
* Returns the connection status
*
* @return true if connected, otherwise false
*/
public abstract boolean isConnected();
/**
* Disconnect from this server
*/
public abstract void disconnect();
/**
* Get the Server Name
*
* @return name
*/
public abstract String getName();
/**
* Get the host/ip address
*
* @return host
*/
public abstract String getHost();
/**
* Get the port
*
* @return port
*/
public abstract int getPort();
/**
* Get the md5-encrypted password that is needed to login to this server
*
* @return
*/
public abstract String getPassword();
/**
* Send a data Message to this server
*
* @param message
* @return true, if queued for sending into connection (= did send); otherwise false (= message
* cached)
* @throws IOException
*/
public abstract boolean sendMessage(Message message) throws IOException;
/**
* Ping this server with a new Ping
*
* @param ping that is used to verify this ping
* @throws InterruptedException
* @throws IOException
*/
public abstract void ping(Ping ping) throws InterruptedException, IOException;
/**
* Send cached packets = queue packets into connection
*/
public abstract void flushCache();
/**
* Get the type of this server
*
* @return Server Type
*/ | public abstract XType getType(); |
mickare/xserver | XServer-API/src/main/java/de/mickare/xserver/EventHandler.java | // Path: XServer-API/src/main/java/de/mickare/xserver/events/XServerEvent.java
// public class XServerEvent {
//
// private final String text;
//
// public XServerEvent() {
// text = "";
// }
//
// public XServerEvent(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void postCall() {
//
// }
//
// public String getChannel() {
// return "";
// }
//
// }
| import java.util.Map;
import de.mickare.xserver.events.XServerEvent; | package de.mickare.xserver;
public interface EventHandler<T> {
/**
* Get all Listeners...
*
* @return new Map
*/
public abstract Map<XServerListener, XServerListenerPlugin<T>> getListeners();
/**
* Register a new listener...
*
* @param plugin
* @param lis
*/
public abstract void registerListener(T plugin, XServerListener lis);
/**
* Register a new listener and will throw an Exception if it fails
*
* @param plugin
* @param lis
* @throws IllegalArgumentException
*/
public abstract void registerListenerUnsafe(Object plugin, XServerListener lis) throws IllegalArgumentException;
/**
* Unregister a old listener...
*
* @param lis
*/
public abstract void unregisterListener(XServerListener lis);
/**
* Unregister all for a plugin listeners...
*/
public abstract void unregisterAll(T plugin);
public abstract void unregisterAll(XServerListenerPlugin<T> plugin);
/**
* Unregister all listeners...
*/
public abstract void unregisterAll();
/**
* Call an Event...
*
* @param event
*/ | // Path: XServer-API/src/main/java/de/mickare/xserver/events/XServerEvent.java
// public class XServerEvent {
//
// private final String text;
//
// public XServerEvent() {
// text = "";
// }
//
// public XServerEvent(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void postCall() {
//
// }
//
// public String getChannel() {
// return "";
// }
//
// }
// Path: XServer-API/src/main/java/de/mickare/xserver/EventHandler.java
import java.util.Map;
import de.mickare.xserver.events.XServerEvent;
package de.mickare.xserver;
public interface EventHandler<T> {
/**
* Get all Listeners...
*
* @return new Map
*/
public abstract Map<XServerListener, XServerListenerPlugin<T>> getListeners();
/**
* Register a new listener...
*
* @param plugin
* @param lis
*/
public abstract void registerListener(T plugin, XServerListener lis);
/**
* Register a new listener and will throw an Exception if it fails
*
* @param plugin
* @param lis
* @throws IllegalArgumentException
*/
public abstract void registerListenerUnsafe(Object plugin, XServerListener lis) throws IllegalArgumentException;
/**
* Unregister a old listener...
*
* @param lis
*/
public abstract void unregisterListener(XServerListener lis);
/**
* Unregister all for a plugin listeners...
*/
public abstract void unregisterAll(T plugin);
public abstract void unregisterAll(XServerListenerPlugin<T> plugin);
/**
* Unregister all listeners...
*/
public abstract void unregisterAll();
/**
* Call an Event...
*
* @param event
*/ | public abstract XServerEvent callEvent(XServerEvent event); |
mickare/xserver | XServer-Bukkit/src/main/java/de/mickare/xserver/commands/XServerCommands.java | // Path: XServer-Bukkit/src/main/java/de/mickare/xserver/BukkitXServerPlugin.java
// public class BukkitXServerPlugin extends JavaPlugin implements XServerPlugin {
//
// private static final long AUTORECONNECT = 10000;
// public static final XType HOMETYPE = XType.Bukkit;
//
// private Logger log;
//
// private String servername;
//
// private MySQL cfgconnection = null;
// private XServerManager xmanager;
//
// private boolean debug = false;
//
// @Override
// public void onDisable() {
// log = this.getLogger();
// log.info("---------------------------------");
// log.info("------------ XServer ------------");
// log.info("---------- disabling ----------");
//
// if (xmanager != null) {
// xmanager.stop();
// xmanager.getThreadPool().shutDown();
// }
//
// if (cfgconnection != null) {
// cfgconnection.disconnect();
// }
//
// log.info(getDescription().getName() + " disabled!");
// }
//
// @Override
// public void onEnable() {
// log = this.getLogger();
// log.info("---------------------------------");
// log.info("------------ XServer ------------");
// log.info("---------- enabling ----------");
// setDebugging(this.getConfig().getBoolean("debug", false));
//
// this.saveDefaultConfig();
//
// servername = this.getServer().getMotd();
// if (servername == null) {
// servername = this.getServer().getServerName();
// }
// if (!this.getConfig().getBoolean("useMotdForServername", true)) {
// servername = this.getConfig().getString("servername", servername);
// }
//
// String user = this.getConfig().getString("mysql.User");
// String pass = this.getConfig().getString("mysql.Pass");
// String data = this.getConfig().getString("mysql.Data");
// String host = this.getConfig().getString("mysql.Host");
// int port = this.getConfig().getInt("mysql.Port", 3306);
// String sql_table_xservers = this.getConfig().getString("mysql.TableXServers", "xservers");
// String sql_table_xgroups = this.getConfig().getString("mysql.TableXGroups", "xgroups");
// String sql_table_xserversxgroups = this.getConfig().getString("mysql.TableXServersGroups", "xservers_xgroups");
//
// log.info("Connecting to Database " + host + ":" + port + "/" + data + " with user: " + user);
//
// cfgconnection = new MySQL(log, user, pass, data, host, port, "config");
//
// cfgconnection.connect();
//
// try {
// log.info("Starting XServer async.");
// xmanager =
// new BukkitXServerManager(servername, this, cfgconnection, sql_table_xservers, sql_table_xgroups, sql_table_xserversxgroups);
// } catch (IOException | InvalidConfigurationException e) {
// log.severe("XServerManager not initialized correctly!\n" + e.getMessage() + "\n" + MyStringUtils.stackTraceToString(e));
// this.getServer().shutdown();
// // this.getServer().dispatchCommand(this.getServer().getConsoleSender(), "stop");
// }
//
// // Register Commands
// new XServerCommands(this);
//
// try {
// MetricsLite metrics = new MetricsLite(this);
// metrics.start();
// } catch (IOException e) {
// // Failed to submit the stats :-(
// }
//
// log.info(getDescription().getName() + " enabled!");
// }
//
// @Override
// public void shutdownServer() {
// this.getServer().shutdown();
// }
//
// @Override
// public XServerManager getManager() {
// return xmanager;
// }
//
// @Override
// public long getAutoReconnectTime() {
// return AUTORECONNECT;
// }
//
// @Override
// public XType getHomeType() {
// return HOMETYPE;
// }
//
// @Override
// public boolean isDebugging() {
// return this.debug;
// }
//
// @Override
// public void setDebugging(boolean debug) {
// this.debug = debug;
// }
//
// }
| import java.util.Arrays;
import java.util.HashSet;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import de.mickare.xserver.BukkitXServerPlugin;
import de.mickare.xserver.commands.XServerSubCommands.*; | package de.mickare.xserver.commands;
public class XServerCommands extends AbstractCommand {
private HashSet<SubCommand> commands = new HashSet<SubCommand>();
| // Path: XServer-Bukkit/src/main/java/de/mickare/xserver/BukkitXServerPlugin.java
// public class BukkitXServerPlugin extends JavaPlugin implements XServerPlugin {
//
// private static final long AUTORECONNECT = 10000;
// public static final XType HOMETYPE = XType.Bukkit;
//
// private Logger log;
//
// private String servername;
//
// private MySQL cfgconnection = null;
// private XServerManager xmanager;
//
// private boolean debug = false;
//
// @Override
// public void onDisable() {
// log = this.getLogger();
// log.info("---------------------------------");
// log.info("------------ XServer ------------");
// log.info("---------- disabling ----------");
//
// if (xmanager != null) {
// xmanager.stop();
// xmanager.getThreadPool().shutDown();
// }
//
// if (cfgconnection != null) {
// cfgconnection.disconnect();
// }
//
// log.info(getDescription().getName() + " disabled!");
// }
//
// @Override
// public void onEnable() {
// log = this.getLogger();
// log.info("---------------------------------");
// log.info("------------ XServer ------------");
// log.info("---------- enabling ----------");
// setDebugging(this.getConfig().getBoolean("debug", false));
//
// this.saveDefaultConfig();
//
// servername = this.getServer().getMotd();
// if (servername == null) {
// servername = this.getServer().getServerName();
// }
// if (!this.getConfig().getBoolean("useMotdForServername", true)) {
// servername = this.getConfig().getString("servername", servername);
// }
//
// String user = this.getConfig().getString("mysql.User");
// String pass = this.getConfig().getString("mysql.Pass");
// String data = this.getConfig().getString("mysql.Data");
// String host = this.getConfig().getString("mysql.Host");
// int port = this.getConfig().getInt("mysql.Port", 3306);
// String sql_table_xservers = this.getConfig().getString("mysql.TableXServers", "xservers");
// String sql_table_xgroups = this.getConfig().getString("mysql.TableXGroups", "xgroups");
// String sql_table_xserversxgroups = this.getConfig().getString("mysql.TableXServersGroups", "xservers_xgroups");
//
// log.info("Connecting to Database " + host + ":" + port + "/" + data + " with user: " + user);
//
// cfgconnection = new MySQL(log, user, pass, data, host, port, "config");
//
// cfgconnection.connect();
//
// try {
// log.info("Starting XServer async.");
// xmanager =
// new BukkitXServerManager(servername, this, cfgconnection, sql_table_xservers, sql_table_xgroups, sql_table_xserversxgroups);
// } catch (IOException | InvalidConfigurationException e) {
// log.severe("XServerManager not initialized correctly!\n" + e.getMessage() + "\n" + MyStringUtils.stackTraceToString(e));
// this.getServer().shutdown();
// // this.getServer().dispatchCommand(this.getServer().getConsoleSender(), "stop");
// }
//
// // Register Commands
// new XServerCommands(this);
//
// try {
// MetricsLite metrics = new MetricsLite(this);
// metrics.start();
// } catch (IOException e) {
// // Failed to submit the stats :-(
// }
//
// log.info(getDescription().getName() + " enabled!");
// }
//
// @Override
// public void shutdownServer() {
// this.getServer().shutdown();
// }
//
// @Override
// public XServerManager getManager() {
// return xmanager;
// }
//
// @Override
// public long getAutoReconnectTime() {
// return AUTORECONNECT;
// }
//
// @Override
// public XType getHomeType() {
// return HOMETYPE;
// }
//
// @Override
// public boolean isDebugging() {
// return this.debug;
// }
//
// @Override
// public void setDebugging(boolean debug) {
// this.debug = debug;
// }
//
// }
// Path: XServer-Bukkit/src/main/java/de/mickare/xserver/commands/XServerCommands.java
import java.util.Arrays;
import java.util.HashSet;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import de.mickare.xserver.BukkitXServerPlugin;
import de.mickare.xserver.commands.XServerSubCommands.*;
package de.mickare.xserver.commands;
public class XServerCommands extends AbstractCommand {
private HashSet<SubCommand> commands = new HashSet<SubCommand>();
| public XServerCommands(BukkitXServerPlugin plugin) { |
mickare/xserver | XServer-Core/src/main/java/de/mickare/xserver/EventHandlerObj.java | // Path: XServer-API/src/main/java/de/mickare/xserver/events/XServerEvent.java
// public class XServerEvent {
//
// private final String text;
//
// public XServerEvent() {
// text = "";
// }
//
// public XServerEvent(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void postCall() {
//
// }
//
// public String getChannel() {
// return "";
// }
//
// }
| import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import de.mickare.xserver.events.XServerEvent; | @Override
public synchronized void unregisterAll(XServerListenerPlugin<T> plugin) {
for (Entry<XServerListener, XServerListenerPlugin<T>> e : new HashSet<Entry<XServerListener, XServerListenerPlugin<T>>>(
listeners.entrySet())) {
if (e.getValue() == plugin) {
bus.unregister(e.getKey());
listeners.remove(e.getKey());
}
}
}
/*
* (non-Javadoc)
*
* @see de.mickare.xserver.EventHandler#unregisterAll()
*/
@Override
public synchronized void unregisterAll() {
for (XServerListener lis : listeners.keySet()) {
bus.unregister(lis);
}
listeners.clear();
}
/*
* (non-Javadoc)
*
* @see de.mickare.xserver.EventHandler#callEvent(de.mickare.xserver.events.XServerEvent)
*/
@Override | // Path: XServer-API/src/main/java/de/mickare/xserver/events/XServerEvent.java
// public class XServerEvent {
//
// private final String text;
//
// public XServerEvent() {
// text = "";
// }
//
// public XServerEvent(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void postCall() {
//
// }
//
// public String getChannel() {
// return "";
// }
//
// }
// Path: XServer-Core/src/main/java/de/mickare/xserver/EventHandlerObj.java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import de.mickare.xserver.events.XServerEvent;
@Override
public synchronized void unregisterAll(XServerListenerPlugin<T> plugin) {
for (Entry<XServerListener, XServerListenerPlugin<T>> e : new HashSet<Entry<XServerListener, XServerListenerPlugin<T>>>(
listeners.entrySet())) {
if (e.getValue() == plugin) {
bus.unregister(e.getKey());
listeners.remove(e.getKey());
}
}
}
/*
* (non-Javadoc)
*
* @see de.mickare.xserver.EventHandler#unregisterAll()
*/
@Override
public synchronized void unregisterAll() {
for (XServerListener lis : listeners.keySet()) {
bus.unregister(lis);
}
listeners.clear();
}
/*
* (non-Javadoc)
*
* @see de.mickare.xserver.EventHandler#callEvent(de.mickare.xserver.events.XServerEvent)
*/
@Override | public XServerEvent callEvent(final XServerEvent event) { |
mickare/xserver | XServer-Bungee/src/main/java/de/mickare/xserver/BungeeXServerManager.java | // Path: XServer-API/src/main/java/de/mickare/xserver/exceptions/NotInitializedException.java
// @SuppressWarnings("serial")
// public class NotInitializedException extends RuntimeException {
//
// public NotInitializedException() {}
//
// public NotInitializedException(String reason) {
// super(reason);
// }
//
// public NotInitializedException(Throwable cause) {
// super(cause);
// }
//
// public NotInitializedException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: XServer-Core/src/main/java/de/mickare/xserver/util/MySQL.java
// public class MySQL {
//
// private final Logger logger;
//
// private final String user, pass, db, host, name;
// private final int port;
// private Connection connection;
//
// public MySQL( Logger logger, String user, String pass, String db, String host, int port, String name ) {
// this.logger = logger;
// this.user = user;
// this.pass = pass;
// this.db = db;
// this.host = host;
// this.port = port;
// this.name = name;
// }
//
// public String getDatabase() {
// return db;
// }
//
// public void reconnect() {
// try {
// if ( connection != null ) {
// if ( connection.isClosed() ) {
// connect();
// }
// } else {
// connect();
// }
// } catch ( SQLException ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// }
// }
//
// public void connect() {
// try {
// Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
// connection = DriverManager.getConnection( "jdbc:mysql://" + host + ":" + port + "/" + db
// + "?autoReconnect=true", user, pass );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void disconnect() {
// if ( connection != null ) {
// try {
// connection.close();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
// }
//
// public void updateSilent( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// }
// }
//
// public void update( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void update( String stmtqry, String... values ) {
// try ( PreparedStatement stmt = connection.prepareStatement( stmtqry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// stmt.setString( i + 1, values[i] );
// }
// stmt.executeUpdate();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(stmtqry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry, String... values ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// pstmt.setString( i + 1, values[i] );
// }
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public Connection getConnection() {
// return connection;
// }
//
// public String getName() {
// return name;
// }
//
// }
| import java.io.IOException;
import de.mickare.xserver.exceptions.InvalidConfigurationException;
import de.mickare.xserver.exceptions.NotInitializedException;
import de.mickare.xserver.listener.StressTestListener;
import de.mickare.xserver.util.MySQL; | package de.mickare.xserver;
public class BungeeXServerManager extends XServerManager {
public static BungeeXServerManager getInstance() throws NotInitializedException {
return (BungeeXServerManager) XServerManager.getInstance();
}
private final BungeeEventHandler eventhandler;
private final BungeeXServerPlugin bungeePlugin;
private final StressTestListener stressListener;
| // Path: XServer-API/src/main/java/de/mickare/xserver/exceptions/NotInitializedException.java
// @SuppressWarnings("serial")
// public class NotInitializedException extends RuntimeException {
//
// public NotInitializedException() {}
//
// public NotInitializedException(String reason) {
// super(reason);
// }
//
// public NotInitializedException(Throwable cause) {
// super(cause);
// }
//
// public NotInitializedException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: XServer-Core/src/main/java/de/mickare/xserver/util/MySQL.java
// public class MySQL {
//
// private final Logger logger;
//
// private final String user, pass, db, host, name;
// private final int port;
// private Connection connection;
//
// public MySQL( Logger logger, String user, String pass, String db, String host, int port, String name ) {
// this.logger = logger;
// this.user = user;
// this.pass = pass;
// this.db = db;
// this.host = host;
// this.port = port;
// this.name = name;
// }
//
// public String getDatabase() {
// return db;
// }
//
// public void reconnect() {
// try {
// if ( connection != null ) {
// if ( connection.isClosed() ) {
// connect();
// }
// } else {
// connect();
// }
// } catch ( SQLException ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// }
// }
//
// public void connect() {
// try {
// Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
// connection = DriverManager.getConnection( "jdbc:mysql://" + host + ":" + port + "/" + db
// + "?autoReconnect=true", user, pass );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void disconnect() {
// if ( connection != null ) {
// try {
// connection.close();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
// }
//
// public void updateSilent( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// }
// }
//
// public void update( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void update( String stmtqry, String... values ) {
// try ( PreparedStatement stmt = connection.prepareStatement( stmtqry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// stmt.setString( i + 1, values[i] );
// }
// stmt.executeUpdate();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(stmtqry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry, String... values ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// pstmt.setString( i + 1, values[i] );
// }
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public Connection getConnection() {
// return connection;
// }
//
// public String getName() {
// return name;
// }
//
// }
// Path: XServer-Bungee/src/main/java/de/mickare/xserver/BungeeXServerManager.java
import java.io.IOException;
import de.mickare.xserver.exceptions.InvalidConfigurationException;
import de.mickare.xserver.exceptions.NotInitializedException;
import de.mickare.xserver.listener.StressTestListener;
import de.mickare.xserver.util.MySQL;
package de.mickare.xserver;
public class BungeeXServerManager extends XServerManager {
public static BungeeXServerManager getInstance() throws NotInitializedException {
return (BungeeXServerManager) XServerManager.getInstance();
}
private final BungeeEventHandler eventhandler;
private final BungeeXServerPlugin bungeePlugin;
private final StressTestListener stressListener;
| protected BungeeXServerManager(String servername, BungeeXServerPlugin bungeePlugin, MySQL connection, String sql_table_xservers, |
mickare/xserver | XServer-API/src/main/java/de/mickare/xserver/util/InterruptableRunnable.java | // Path: XServer-API/src/main/java/de/mickare/xserver/ServerThreadPoolExecutor.java
// public interface ServerThreadPoolExecutor {
//
// /**
// * Here we add our jobs to working queue
// *
// * @param task a Runnable task
// */
// public abstract Future<?> runTask(Runnable task);
//
// /**
// * Shutdown the Threadpool if it's finished
// */
// public abstract void shutDown();
//
// /**
// * Run tha main ServerSocket Task
// *
// * @param task
// * @return
// */
// Future<?> runServerTask(Runnable task);
//
// }
| import de.mickare.xserver.ServerThreadPoolExecutor; | package de.mickare.xserver.util;
public abstract class InterruptableRunnable implements Runnable {
private volatile boolean interrupted = false;
private final String name;
public InterruptableRunnable(String name) {
this.name = name;
}
| // Path: XServer-API/src/main/java/de/mickare/xserver/ServerThreadPoolExecutor.java
// public interface ServerThreadPoolExecutor {
//
// /**
// * Here we add our jobs to working queue
// *
// * @param task a Runnable task
// */
// public abstract Future<?> runTask(Runnable task);
//
// /**
// * Shutdown the Threadpool if it's finished
// */
// public abstract void shutDown();
//
// /**
// * Run tha main ServerSocket Task
// *
// * @param task
// * @return
// */
// Future<?> runServerTask(Runnable task);
//
// }
// Path: XServer-API/src/main/java/de/mickare/xserver/util/InterruptableRunnable.java
import de.mickare.xserver.ServerThreadPoolExecutor;
package de.mickare.xserver.util;
public abstract class InterruptableRunnable implements Runnable {
private volatile boolean interrupted = false;
private final String name;
public InterruptableRunnable(String name) {
this.name = name;
}
| public void start(ServerThreadPoolExecutor threadpool) { |
mickare/xserver | XServer-API/src/main/java/de/mickare/xserver/events/XServerMessageEvent.java | // Path: XServer-API/src/main/java/de/mickare/xserver/Message.java
// public interface Message {
//
// /**
// * Get Sender Server Name
// *
// * @return sender name
// */
// public abstract XServer getSender();
//
// /**
// * SubChannel
// *
// * @return subchannel name
// */
// public abstract String getSubChannel();
//
// /**
// * Get the content of this message...
// *
// * @return byte array
// */
// public abstract byte[] getContent();
//
// /**
// * Get the compiled byte array of this message...
// *
// * @return byte array
// * @throws IOException
// */
// public abstract byte[] getData() throws IOException;
//
// }
//
// Path: XServer-API/src/main/java/de/mickare/xserver/net/XServer.java
// public interface XServer {
//
// /**
// * Try to establish a connection to this server
// *
// * @throws UnknownHostException
// * @throws IOException
// * @throws InterruptedException
// * @throws NotInitializedException
// */
// public abstract void connect() throws UnknownHostException, IOException, InterruptedException, NotInitializedException;
//
// /**
// * Returns the connection status
// *
// * @return true if connected, otherwise false
// */
// public abstract boolean isConnected();
//
// /**
// * Disconnect from this server
// */
// public abstract void disconnect();
//
// /**
// * Get the Server Name
// *
// * @return name
// */
// public abstract String getName();
//
// /**
// * Get the host/ip address
// *
// * @return host
// */
// public abstract String getHost();
//
// /**
// * Get the port
// *
// * @return port
// */
// public abstract int getPort();
//
// /**
// * Get the md5-encrypted password that is needed to login to this server
// *
// * @return
// */
// public abstract String getPassword();
//
// /**
// * Send a data Message to this server
// *
// * @param message
// * @return true, if queued for sending into connection (= did send); otherwise false (= message
// * cached)
// * @throws IOException
// */
// public abstract boolean sendMessage(Message message) throws IOException;
//
// /**
// * Ping this server with a new Ping
// *
// * @param ping that is used to verify this ping
// * @throws InterruptedException
// * @throws IOException
// */
// public abstract void ping(Ping ping) throws InterruptedException, IOException;
//
// /**
// * Send cached packets = queue packets into connection
// */
// public abstract void flushCache();
//
// /**
// * Get the type of this server
// *
// * @return Server Type
// */
// public abstract XType getType();
//
// /**
// * Get the Current Server Manager Object
// *
// * @return
// */
// public abstract AbstractXServerManager getManager();
//
// /**
// * Get the record number of packages sended in one second
// *
// * @return number of packages
// */
// public abstract long getSendingRecordSecondPackageCount();
//
// /**
// * Get the number of packages sended in the last one second
// *
// * @return number of packages
// */
// public abstract long getSendinglastSecondPackageCount();
//
// /**
// * Get the record number of packages received in one second
// *
// * @return number of packages
// */
// public abstract long getReceivingRecordSecondPackageCount();
//
// /**
// * Get the number of packages received in the last one second
// *
// * @return number of packages
// */
// public abstract long getReceivinglastSecondPackageCount();
//
// public abstract Set<XGroup> getGroups();
//
// boolean hasGroup(XGroup group);
//
// boolean isDeprecated();
//
// XServer getCurrentXServer();
//
// }
| import de.mickare.xserver.Message;
import de.mickare.xserver.net.XServer; | package de.mickare.xserver.events;
public class XServerMessageEvent extends XServerEvent {
private final XServer server; | // Path: XServer-API/src/main/java/de/mickare/xserver/Message.java
// public interface Message {
//
// /**
// * Get Sender Server Name
// *
// * @return sender name
// */
// public abstract XServer getSender();
//
// /**
// * SubChannel
// *
// * @return subchannel name
// */
// public abstract String getSubChannel();
//
// /**
// * Get the content of this message...
// *
// * @return byte array
// */
// public abstract byte[] getContent();
//
// /**
// * Get the compiled byte array of this message...
// *
// * @return byte array
// * @throws IOException
// */
// public abstract byte[] getData() throws IOException;
//
// }
//
// Path: XServer-API/src/main/java/de/mickare/xserver/net/XServer.java
// public interface XServer {
//
// /**
// * Try to establish a connection to this server
// *
// * @throws UnknownHostException
// * @throws IOException
// * @throws InterruptedException
// * @throws NotInitializedException
// */
// public abstract void connect() throws UnknownHostException, IOException, InterruptedException, NotInitializedException;
//
// /**
// * Returns the connection status
// *
// * @return true if connected, otherwise false
// */
// public abstract boolean isConnected();
//
// /**
// * Disconnect from this server
// */
// public abstract void disconnect();
//
// /**
// * Get the Server Name
// *
// * @return name
// */
// public abstract String getName();
//
// /**
// * Get the host/ip address
// *
// * @return host
// */
// public abstract String getHost();
//
// /**
// * Get the port
// *
// * @return port
// */
// public abstract int getPort();
//
// /**
// * Get the md5-encrypted password that is needed to login to this server
// *
// * @return
// */
// public abstract String getPassword();
//
// /**
// * Send a data Message to this server
// *
// * @param message
// * @return true, if queued for sending into connection (= did send); otherwise false (= message
// * cached)
// * @throws IOException
// */
// public abstract boolean sendMessage(Message message) throws IOException;
//
// /**
// * Ping this server with a new Ping
// *
// * @param ping that is used to verify this ping
// * @throws InterruptedException
// * @throws IOException
// */
// public abstract void ping(Ping ping) throws InterruptedException, IOException;
//
// /**
// * Send cached packets = queue packets into connection
// */
// public abstract void flushCache();
//
// /**
// * Get the type of this server
// *
// * @return Server Type
// */
// public abstract XType getType();
//
// /**
// * Get the Current Server Manager Object
// *
// * @return
// */
// public abstract AbstractXServerManager getManager();
//
// /**
// * Get the record number of packages sended in one second
// *
// * @return number of packages
// */
// public abstract long getSendingRecordSecondPackageCount();
//
// /**
// * Get the number of packages sended in the last one second
// *
// * @return number of packages
// */
// public abstract long getSendinglastSecondPackageCount();
//
// /**
// * Get the record number of packages received in one second
// *
// * @return number of packages
// */
// public abstract long getReceivingRecordSecondPackageCount();
//
// /**
// * Get the number of packages received in the last one second
// *
// * @return number of packages
// */
// public abstract long getReceivinglastSecondPackageCount();
//
// public abstract Set<XGroup> getGroups();
//
// boolean hasGroup(XGroup group);
//
// boolean isDeprecated();
//
// XServer getCurrentXServer();
//
// }
// Path: XServer-API/src/main/java/de/mickare/xserver/events/XServerMessageEvent.java
import de.mickare.xserver.Message;
import de.mickare.xserver.net.XServer;
package de.mickare.xserver.events;
public class XServerMessageEvent extends XServerEvent {
private final XServer server; | private final Message message; |
mickare/xserver | XServer-API/src/main/java/de/mickare/xserver/net/Ping.java | // Path: XServer-API/src/main/java/de/mickare/xserver/user/ComSender.java
// public interface ComSender {
//
// public String getName();
//
// public boolean hasPermission(String perm);
//
// public void sendMessage(String message);
//
// }
| import java.util.Collection;
import de.mickare.xserver.user.ComSender; | package de.mickare.xserver.net;
public interface Ping {
public abstract boolean start();
public abstract void add(XServer server);
public abstract void addAll(Collection<XServer> servers);
public abstract void receive(XServer server);
public abstract boolean isPending();
public abstract String getFormatedString();
| // Path: XServer-API/src/main/java/de/mickare/xserver/user/ComSender.java
// public interface ComSender {
//
// public String getName();
//
// public boolean hasPermission(String perm);
//
// public void sendMessage(String message);
//
// }
// Path: XServer-API/src/main/java/de/mickare/xserver/net/Ping.java
import java.util.Collection;
import de.mickare.xserver.user.ComSender;
package de.mickare.xserver.net;
public interface Ping {
public abstract boolean start();
public abstract void add(XServer server);
public abstract void addAll(Collection<XServer> servers);
public abstract void receive(XServer server);
public abstract boolean isPending();
public abstract String getFormatedString();
| public abstract ComSender getSender(); |
mickare/xserver | XServer-API/src/main/java/de/mickare/xserver/AbstractXServerManager.java | // Path: XServer-API/src/main/java/de/mickare/xserver/net/XServer.java
// public interface XServer {
//
// /**
// * Try to establish a connection to this server
// *
// * @throws UnknownHostException
// * @throws IOException
// * @throws InterruptedException
// * @throws NotInitializedException
// */
// public abstract void connect() throws UnknownHostException, IOException, InterruptedException, NotInitializedException;
//
// /**
// * Returns the connection status
// *
// * @return true if connected, otherwise false
// */
// public abstract boolean isConnected();
//
// /**
// * Disconnect from this server
// */
// public abstract void disconnect();
//
// /**
// * Get the Server Name
// *
// * @return name
// */
// public abstract String getName();
//
// /**
// * Get the host/ip address
// *
// * @return host
// */
// public abstract String getHost();
//
// /**
// * Get the port
// *
// * @return port
// */
// public abstract int getPort();
//
// /**
// * Get the md5-encrypted password that is needed to login to this server
// *
// * @return
// */
// public abstract String getPassword();
//
// /**
// * Send a data Message to this server
// *
// * @param message
// * @return true, if queued for sending into connection (= did send); otherwise false (= message
// * cached)
// * @throws IOException
// */
// public abstract boolean sendMessage(Message message) throws IOException;
//
// /**
// * Ping this server with a new Ping
// *
// * @param ping that is used to verify this ping
// * @throws InterruptedException
// * @throws IOException
// */
// public abstract void ping(Ping ping) throws InterruptedException, IOException;
//
// /**
// * Send cached packets = queue packets into connection
// */
// public abstract void flushCache();
//
// /**
// * Get the type of this server
// *
// * @return Server Type
// */
// public abstract XType getType();
//
// /**
// * Get the Current Server Manager Object
// *
// * @return
// */
// public abstract AbstractXServerManager getManager();
//
// /**
// * Get the record number of packages sended in one second
// *
// * @return number of packages
// */
// public abstract long getSendingRecordSecondPackageCount();
//
// /**
// * Get the number of packages sended in the last one second
// *
// * @return number of packages
// */
// public abstract long getSendinglastSecondPackageCount();
//
// /**
// * Get the record number of packages received in one second
// *
// * @return number of packages
// */
// public abstract long getReceivingRecordSecondPackageCount();
//
// /**
// * Get the number of packages received in the last one second
// *
// * @return number of packages
// */
// public abstract long getReceivinglastSecondPackageCount();
//
// public abstract Set<XGroup> getGroups();
//
// boolean hasGroup(XGroup group);
//
// boolean isDeprecated();
//
// XServer getCurrentXServer();
//
// }
| import java.io.IOException;
import java.util.Set;
import java.util.logging.Logger;
import javax.net.SocketFactory;
import de.mickare.xserver.exceptions.InvalidConfigurationException;
import de.mickare.xserver.net.XServer; | package de.mickare.xserver;
public interface AbstractXServerManager {
public abstract void start() throws IOException;
public abstract void start_async();
public abstract void reconnectAll_soft();
public abstract void reconnectAll_forced();
public abstract void stop() throws IOException;
/**
* Reload configuration
*
* @throws IOException
*
* @throws InvalidConfigurationException
*/
public abstract void reload() throws IOException;
| // Path: XServer-API/src/main/java/de/mickare/xserver/net/XServer.java
// public interface XServer {
//
// /**
// * Try to establish a connection to this server
// *
// * @throws UnknownHostException
// * @throws IOException
// * @throws InterruptedException
// * @throws NotInitializedException
// */
// public abstract void connect() throws UnknownHostException, IOException, InterruptedException, NotInitializedException;
//
// /**
// * Returns the connection status
// *
// * @return true if connected, otherwise false
// */
// public abstract boolean isConnected();
//
// /**
// * Disconnect from this server
// */
// public abstract void disconnect();
//
// /**
// * Get the Server Name
// *
// * @return name
// */
// public abstract String getName();
//
// /**
// * Get the host/ip address
// *
// * @return host
// */
// public abstract String getHost();
//
// /**
// * Get the port
// *
// * @return port
// */
// public abstract int getPort();
//
// /**
// * Get the md5-encrypted password that is needed to login to this server
// *
// * @return
// */
// public abstract String getPassword();
//
// /**
// * Send a data Message to this server
// *
// * @param message
// * @return true, if queued for sending into connection (= did send); otherwise false (= message
// * cached)
// * @throws IOException
// */
// public abstract boolean sendMessage(Message message) throws IOException;
//
// /**
// * Ping this server with a new Ping
// *
// * @param ping that is used to verify this ping
// * @throws InterruptedException
// * @throws IOException
// */
// public abstract void ping(Ping ping) throws InterruptedException, IOException;
//
// /**
// * Send cached packets = queue packets into connection
// */
// public abstract void flushCache();
//
// /**
// * Get the type of this server
// *
// * @return Server Type
// */
// public abstract XType getType();
//
// /**
// * Get the Current Server Manager Object
// *
// * @return
// */
// public abstract AbstractXServerManager getManager();
//
// /**
// * Get the record number of packages sended in one second
// *
// * @return number of packages
// */
// public abstract long getSendingRecordSecondPackageCount();
//
// /**
// * Get the number of packages sended in the last one second
// *
// * @return number of packages
// */
// public abstract long getSendinglastSecondPackageCount();
//
// /**
// * Get the record number of packages received in one second
// *
// * @return number of packages
// */
// public abstract long getReceivingRecordSecondPackageCount();
//
// /**
// * Get the number of packages received in the last one second
// *
// * @return number of packages
// */
// public abstract long getReceivinglastSecondPackageCount();
//
// public abstract Set<XGroup> getGroups();
//
// boolean hasGroup(XGroup group);
//
// boolean isDeprecated();
//
// XServer getCurrentXServer();
//
// }
// Path: XServer-API/src/main/java/de/mickare/xserver/AbstractXServerManager.java
import java.io.IOException;
import java.util.Set;
import java.util.logging.Logger;
import javax.net.SocketFactory;
import de.mickare.xserver.exceptions.InvalidConfigurationException;
import de.mickare.xserver.net.XServer;
package de.mickare.xserver;
public interface AbstractXServerManager {
public abstract void start() throws IOException;
public abstract void start_async();
public abstract void reconnectAll_soft();
public abstract void reconnectAll_forced();
public abstract void stop() throws IOException;
/**
* Reload configuration
*
* @throws IOException
*
* @throws InvalidConfigurationException
*/
public abstract void reload() throws IOException;
| public abstract XServer getHomeServer(); |
mickare/xserver | XServer-Core/src/main/java/de/mickare/xserver/XServerManager.java | // Path: XServer-API/src/main/java/de/mickare/xserver/exceptions/NotInitializedException.java
// @SuppressWarnings("serial")
// public class NotInitializedException extends RuntimeException {
//
// public NotInitializedException() {}
//
// public NotInitializedException(String reason) {
// super(reason);
// }
//
// public NotInitializedException(Throwable cause) {
// super(cause);
// }
//
// public NotInitializedException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: XServer-Core/src/main/java/de/mickare/xserver/util/MySQL.java
// public class MySQL {
//
// private final Logger logger;
//
// private final String user, pass, db, host, name;
// private final int port;
// private Connection connection;
//
// public MySQL( Logger logger, String user, String pass, String db, String host, int port, String name ) {
// this.logger = logger;
// this.user = user;
// this.pass = pass;
// this.db = db;
// this.host = host;
// this.port = port;
// this.name = name;
// }
//
// public String getDatabase() {
// return db;
// }
//
// public void reconnect() {
// try {
// if ( connection != null ) {
// if ( connection.isClosed() ) {
// connect();
// }
// } else {
// connect();
// }
// } catch ( SQLException ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// }
// }
//
// public void connect() {
// try {
// Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
// connection = DriverManager.getConnection( "jdbc:mysql://" + host + ":" + port + "/" + db
// + "?autoReconnect=true", user, pass );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void disconnect() {
// if ( connection != null ) {
// try {
// connection.close();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
// }
//
// public void updateSilent( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// }
// }
//
// public void update( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void update( String stmtqry, String... values ) {
// try ( PreparedStatement stmt = connection.prepareStatement( stmtqry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// stmt.setString( i + 1, values[i] );
// }
// stmt.executeUpdate();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(stmtqry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry, String... values ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// pstmt.setString( i + 1, values[i] );
// }
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public Connection getConnection() {
// return connection;
// }
//
// public String getName() {
// return name;
// }
//
// }
| import java.io.IOException;
import de.mickare.xserver.exceptions.InvalidConfigurationException;
import de.mickare.xserver.exceptions.NotInitializedException;
import de.mickare.xserver.util.MySQL; | package de.mickare.xserver;
public abstract class XServerManager extends AbstractXServerManagerObj {
private static XServerManager instance = null;
| // Path: XServer-API/src/main/java/de/mickare/xserver/exceptions/NotInitializedException.java
// @SuppressWarnings("serial")
// public class NotInitializedException extends RuntimeException {
//
// public NotInitializedException() {}
//
// public NotInitializedException(String reason) {
// super(reason);
// }
//
// public NotInitializedException(Throwable cause) {
// super(cause);
// }
//
// public NotInitializedException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: XServer-Core/src/main/java/de/mickare/xserver/util/MySQL.java
// public class MySQL {
//
// private final Logger logger;
//
// private final String user, pass, db, host, name;
// private final int port;
// private Connection connection;
//
// public MySQL( Logger logger, String user, String pass, String db, String host, int port, String name ) {
// this.logger = logger;
// this.user = user;
// this.pass = pass;
// this.db = db;
// this.host = host;
// this.port = port;
// this.name = name;
// }
//
// public String getDatabase() {
// return db;
// }
//
// public void reconnect() {
// try {
// if ( connection != null ) {
// if ( connection.isClosed() ) {
// connect();
// }
// } else {
// connect();
// }
// } catch ( SQLException ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// }
// }
//
// public void connect() {
// try {
// Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
// connection = DriverManager.getConnection( "jdbc:mysql://" + host + ":" + port + "/" + db
// + "?autoReconnect=true", user, pass );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void disconnect() {
// if ( connection != null ) {
// try {
// connection.close();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
// }
//
// public void updateSilent( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// }
// }
//
// public void update( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void update( String stmtqry, String... values ) {
// try ( PreparedStatement stmt = connection.prepareStatement( stmtqry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// stmt.setString( i + 1, values[i] );
// }
// stmt.executeUpdate();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(stmtqry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry, String... values ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// pstmt.setString( i + 1, values[i] );
// }
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public Connection getConnection() {
// return connection;
// }
//
// public String getName() {
// return name;
// }
//
// }
// Path: XServer-Core/src/main/java/de/mickare/xserver/XServerManager.java
import java.io.IOException;
import de.mickare.xserver.exceptions.InvalidConfigurationException;
import de.mickare.xserver.exceptions.NotInitializedException;
import de.mickare.xserver.util.MySQL;
package de.mickare.xserver;
public abstract class XServerManager extends AbstractXServerManagerObj {
private static XServerManager instance = null;
| public static XServerManager getInstance() throws NotInitializedException { |
mickare/xserver | XServer-Core/src/main/java/de/mickare/xserver/XServerManager.java | // Path: XServer-API/src/main/java/de/mickare/xserver/exceptions/NotInitializedException.java
// @SuppressWarnings("serial")
// public class NotInitializedException extends RuntimeException {
//
// public NotInitializedException() {}
//
// public NotInitializedException(String reason) {
// super(reason);
// }
//
// public NotInitializedException(Throwable cause) {
// super(cause);
// }
//
// public NotInitializedException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: XServer-Core/src/main/java/de/mickare/xserver/util/MySQL.java
// public class MySQL {
//
// private final Logger logger;
//
// private final String user, pass, db, host, name;
// private final int port;
// private Connection connection;
//
// public MySQL( Logger logger, String user, String pass, String db, String host, int port, String name ) {
// this.logger = logger;
// this.user = user;
// this.pass = pass;
// this.db = db;
// this.host = host;
// this.port = port;
// this.name = name;
// }
//
// public String getDatabase() {
// return db;
// }
//
// public void reconnect() {
// try {
// if ( connection != null ) {
// if ( connection.isClosed() ) {
// connect();
// }
// } else {
// connect();
// }
// } catch ( SQLException ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// }
// }
//
// public void connect() {
// try {
// Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
// connection = DriverManager.getConnection( "jdbc:mysql://" + host + ":" + port + "/" + db
// + "?autoReconnect=true", user, pass );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void disconnect() {
// if ( connection != null ) {
// try {
// connection.close();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
// }
//
// public void updateSilent( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// }
// }
//
// public void update( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void update( String stmtqry, String... values ) {
// try ( PreparedStatement stmt = connection.prepareStatement( stmtqry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// stmt.setString( i + 1, values[i] );
// }
// stmt.executeUpdate();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(stmtqry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry, String... values ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// pstmt.setString( i + 1, values[i] );
// }
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public Connection getConnection() {
// return connection;
// }
//
// public String getName() {
// return name;
// }
//
// }
| import java.io.IOException;
import de.mickare.xserver.exceptions.InvalidConfigurationException;
import de.mickare.xserver.exceptions.NotInitializedException;
import de.mickare.xserver.util.MySQL; | package de.mickare.xserver;
public abstract class XServerManager extends AbstractXServerManagerObj {
private static XServerManager instance = null;
public static XServerManager getInstance() throws NotInitializedException {
if (instance == null) {
throw new NotInitializedException();
}
return instance;
}
| // Path: XServer-API/src/main/java/de/mickare/xserver/exceptions/NotInitializedException.java
// @SuppressWarnings("serial")
// public class NotInitializedException extends RuntimeException {
//
// public NotInitializedException() {}
//
// public NotInitializedException(String reason) {
// super(reason);
// }
//
// public NotInitializedException(Throwable cause) {
// super(cause);
// }
//
// public NotInitializedException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: XServer-Core/src/main/java/de/mickare/xserver/util/MySQL.java
// public class MySQL {
//
// private final Logger logger;
//
// private final String user, pass, db, host, name;
// private final int port;
// private Connection connection;
//
// public MySQL( Logger logger, String user, String pass, String db, String host, int port, String name ) {
// this.logger = logger;
// this.user = user;
// this.pass = pass;
// this.db = db;
// this.host = host;
// this.port = port;
// this.name = name;
// }
//
// public String getDatabase() {
// return db;
// }
//
// public void reconnect() {
// try {
// if ( connection != null ) {
// if ( connection.isClosed() ) {
// connect();
// }
// } else {
// connect();
// }
// } catch ( SQLException ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// }
// }
//
// public void connect() {
// try {
// Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
// connection = DriverManager.getConnection( "jdbc:mysql://" + host + ":" + port + "/" + db
// + "?autoReconnect=true", user, pass );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void disconnect() {
// if ( connection != null ) {
// try {
// connection.close();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
// }
//
// public void updateSilent( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// }
// }
//
// public void update( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void update( String stmtqry, String... values ) {
// try ( PreparedStatement stmt = connection.prepareStatement( stmtqry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// stmt.setString( i + 1, values[i] );
// }
// stmt.executeUpdate();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(stmtqry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry, String... values ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// pstmt.setString( i + 1, values[i] );
// }
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public Connection getConnection() {
// return connection;
// }
//
// public String getName() {
// return name;
// }
//
// }
// Path: XServer-Core/src/main/java/de/mickare/xserver/XServerManager.java
import java.io.IOException;
import de.mickare.xserver.exceptions.InvalidConfigurationException;
import de.mickare.xserver.exceptions.NotInitializedException;
import de.mickare.xserver.util.MySQL;
package de.mickare.xserver;
public abstract class XServerManager extends AbstractXServerManagerObj {
private static XServerManager instance = null;
public static XServerManager getInstance() throws NotInitializedException {
if (instance == null) {
throw new NotInitializedException();
}
return instance;
}
| protected XServerManager(String servername, XServerPlugin plugin, MySQL connection, String sql_table_xservers, String sql_table_xgroups, |
mickare/xserver | XServer-Core/src/main/java/de/mickare/xserver/EventBus.java | // Path: XServer-API/src/main/java/de/mickare/xserver/events/XServerEvent.java
// public class XServerEvent {
//
// private final String text;
//
// public XServerEvent() {
// text = "";
// }
//
// public XServerEvent(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void postCall() {
//
// }
//
// public String getChannel() {
// return "";
// }
//
// }
//
// Path: XServer-Core/src/main/java/de/mickare/xserver/util/concurrent/CloseableReadWriteLock.java
// public interface CloseableReadWriteLock extends ReadWriteLock {
//
// public CloseableLock readLock();
//
// public CloseableLock writeLock();
//
// }
| import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import de.mickare.xserver.annotations.XEventHandler;
import de.mickare.xserver.events.XServerEvent;
import de.mickare.xserver.util.concurrent.CloseableLock;
import de.mickare.xserver.util.concurrent.CloseableReadWriteLock;
import de.mickare.xserver.util.concurrent.CloseableReentrantReadWriteLock; | package de.mickare.xserver;
// Class from MD5 - BungeeCord
public class EventBus<T> {
private final Map<Class<?>, Map<Object, Method[]>> eventToHandler = new HashMap<>();
private final Map<Method, Boolean> synced = Collections.synchronizedMap(new HashMap<Method, Boolean>());
private final Map<Method, String> channeled = Collections.synchronizedMap(new HashMap<Method, String>());
private final Map<Method, XServerListenerPlugin<T>> plugins =
Collections.synchronizedMap(new HashMap<Method, XServerListenerPlugin<T>>()); | // Path: XServer-API/src/main/java/de/mickare/xserver/events/XServerEvent.java
// public class XServerEvent {
//
// private final String text;
//
// public XServerEvent() {
// text = "";
// }
//
// public XServerEvent(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void postCall() {
//
// }
//
// public String getChannel() {
// return "";
// }
//
// }
//
// Path: XServer-Core/src/main/java/de/mickare/xserver/util/concurrent/CloseableReadWriteLock.java
// public interface CloseableReadWriteLock extends ReadWriteLock {
//
// public CloseableLock readLock();
//
// public CloseableLock writeLock();
//
// }
// Path: XServer-Core/src/main/java/de/mickare/xserver/EventBus.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import de.mickare.xserver.annotations.XEventHandler;
import de.mickare.xserver.events.XServerEvent;
import de.mickare.xserver.util.concurrent.CloseableLock;
import de.mickare.xserver.util.concurrent.CloseableReadWriteLock;
import de.mickare.xserver.util.concurrent.CloseableReentrantReadWriteLock;
package de.mickare.xserver;
// Class from MD5 - BungeeCord
public class EventBus<T> {
private final Map<Class<?>, Map<Object, Method[]>> eventToHandler = new HashMap<>();
private final Map<Method, Boolean> synced = Collections.synchronizedMap(new HashMap<Method, Boolean>());
private final Map<Method, String> channeled = Collections.synchronizedMap(new HashMap<Method, String>());
private final Map<Method, XServerListenerPlugin<T>> plugins =
Collections.synchronizedMap(new HashMap<Method, XServerListenerPlugin<T>>()); | private final CloseableReadWriteLock lock = new CloseableReentrantReadWriteLock(); |
mickare/xserver | XServer-Core/src/main/java/de/mickare/xserver/EventBus.java | // Path: XServer-API/src/main/java/de/mickare/xserver/events/XServerEvent.java
// public class XServerEvent {
//
// private final String text;
//
// public XServerEvent() {
// text = "";
// }
//
// public XServerEvent(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void postCall() {
//
// }
//
// public String getChannel() {
// return "";
// }
//
// }
//
// Path: XServer-Core/src/main/java/de/mickare/xserver/util/concurrent/CloseableReadWriteLock.java
// public interface CloseableReadWriteLock extends ReadWriteLock {
//
// public CloseableLock readLock();
//
// public CloseableLock writeLock();
//
// }
| import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import de.mickare.xserver.annotations.XEventHandler;
import de.mickare.xserver.events.XServerEvent;
import de.mickare.xserver.util.concurrent.CloseableLock;
import de.mickare.xserver.util.concurrent.CloseableReadWriteLock;
import de.mickare.xserver.util.concurrent.CloseableReentrantReadWriteLock; | package de.mickare.xserver;
// Class from MD5 - BungeeCord
public class EventBus<T> {
private final Map<Class<?>, Map<Object, Method[]>> eventToHandler = new HashMap<>();
private final Map<Method, Boolean> synced = Collections.synchronizedMap(new HashMap<Method, Boolean>());
private final Map<Method, String> channeled = Collections.synchronizedMap(new HashMap<Method, String>());
private final Map<Method, XServerListenerPlugin<T>> plugins =
Collections.synchronizedMap(new HashMap<Method, XServerListenerPlugin<T>>());
private final CloseableReadWriteLock lock = new CloseableReentrantReadWriteLock();
private final Logger logger;
private final EventHandler<T> myhandler;
public EventBus(EventHandler<T> myhandler, Logger logger) {
this.logger = (logger == null) ? Logger.getGlobal() : logger;
this.myhandler = myhandler;
}
| // Path: XServer-API/src/main/java/de/mickare/xserver/events/XServerEvent.java
// public class XServerEvent {
//
// private final String text;
//
// public XServerEvent() {
// text = "";
// }
//
// public XServerEvent(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void postCall() {
//
// }
//
// public String getChannel() {
// return "";
// }
//
// }
//
// Path: XServer-Core/src/main/java/de/mickare/xserver/util/concurrent/CloseableReadWriteLock.java
// public interface CloseableReadWriteLock extends ReadWriteLock {
//
// public CloseableLock readLock();
//
// public CloseableLock writeLock();
//
// }
// Path: XServer-Core/src/main/java/de/mickare/xserver/EventBus.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import de.mickare.xserver.annotations.XEventHandler;
import de.mickare.xserver.events.XServerEvent;
import de.mickare.xserver.util.concurrent.CloseableLock;
import de.mickare.xserver.util.concurrent.CloseableReadWriteLock;
import de.mickare.xserver.util.concurrent.CloseableReentrantReadWriteLock;
package de.mickare.xserver;
// Class from MD5 - BungeeCord
public class EventBus<T> {
private final Map<Class<?>, Map<Object, Method[]>> eventToHandler = new HashMap<>();
private final Map<Method, Boolean> synced = Collections.synchronizedMap(new HashMap<Method, Boolean>());
private final Map<Method, String> channeled = Collections.synchronizedMap(new HashMap<Method, String>());
private final Map<Method, XServerListenerPlugin<T>> plugins =
Collections.synchronizedMap(new HashMap<Method, XServerListenerPlugin<T>>());
private final CloseableReadWriteLock lock = new CloseableReentrantReadWriteLock();
private final Logger logger;
private final EventHandler<T> myhandler;
public EventBus(EventHandler<T> myhandler, Logger logger) {
this.logger = (logger == null) ? Logger.getGlobal() : logger;
this.myhandler = myhandler;
}
| private Map<Object, Method[]> getHandlers(final XServerEvent event) { |
mickare/xserver | XServer-Bukkit/src/main/java/de/mickare/xserver/BukkitXServerManager.java | // Path: XServer-API/src/main/java/de/mickare/xserver/exceptions/NotInitializedException.java
// @SuppressWarnings("serial")
// public class NotInitializedException extends RuntimeException {
//
// public NotInitializedException() {}
//
// public NotInitializedException(String reason) {
// super(reason);
// }
//
// public NotInitializedException(Throwable cause) {
// super(cause);
// }
//
// public NotInitializedException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: XServer-Core/src/main/java/de/mickare/xserver/util/MySQL.java
// public class MySQL {
//
// private final Logger logger;
//
// private final String user, pass, db, host, name;
// private final int port;
// private Connection connection;
//
// public MySQL( Logger logger, String user, String pass, String db, String host, int port, String name ) {
// this.logger = logger;
// this.user = user;
// this.pass = pass;
// this.db = db;
// this.host = host;
// this.port = port;
// this.name = name;
// }
//
// public String getDatabase() {
// return db;
// }
//
// public void reconnect() {
// try {
// if ( connection != null ) {
// if ( connection.isClosed() ) {
// connect();
// }
// } else {
// connect();
// }
// } catch ( SQLException ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// }
// }
//
// public void connect() {
// try {
// Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
// connection = DriverManager.getConnection( "jdbc:mysql://" + host + ":" + port + "/" + db
// + "?autoReconnect=true", user, pass );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void disconnect() {
// if ( connection != null ) {
// try {
// connection.close();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
// }
//
// public void updateSilent( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// }
// }
//
// public void update( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void update( String stmtqry, String... values ) {
// try ( PreparedStatement stmt = connection.prepareStatement( stmtqry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// stmt.setString( i + 1, values[i] );
// }
// stmt.executeUpdate();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(stmtqry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry, String... values ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// pstmt.setString( i + 1, values[i] );
// }
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public Connection getConnection() {
// return connection;
// }
//
// public String getName() {
// return name;
// }
//
// }
| import java.io.IOException;
import de.mickare.xserver.exceptions.InvalidConfigurationException;
import de.mickare.xserver.exceptions.NotInitializedException;
import de.mickare.xserver.listener.StressTestListener;
import de.mickare.xserver.util.MySQL; | package de.mickare.xserver;
public class BukkitXServerManager extends XServerManager {
public static BukkitXServerManager getInstance() throws NotInitializedException {
return (BukkitXServerManager) XServerManager.getInstance();
}
private final BukkitEventHandler eventhandler;
private final BukkitXServerPlugin bukkitPlugin;
private final StressTestListener stressListener;
| // Path: XServer-API/src/main/java/de/mickare/xserver/exceptions/NotInitializedException.java
// @SuppressWarnings("serial")
// public class NotInitializedException extends RuntimeException {
//
// public NotInitializedException() {}
//
// public NotInitializedException(String reason) {
// super(reason);
// }
//
// public NotInitializedException(Throwable cause) {
// super(cause);
// }
//
// public NotInitializedException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// }
//
// Path: XServer-Core/src/main/java/de/mickare/xserver/util/MySQL.java
// public class MySQL {
//
// private final Logger logger;
//
// private final String user, pass, db, host, name;
// private final int port;
// private Connection connection;
//
// public MySQL( Logger logger, String user, String pass, String db, String host, int port, String name ) {
// this.logger = logger;
// this.user = user;
// this.pass = pass;
// this.db = db;
// this.host = host;
// this.port = port;
// this.name = name;
// }
//
// public String getDatabase() {
// return db;
// }
//
// public void reconnect() {
// try {
// if ( connection != null ) {
// if ( connection.isClosed() ) {
// connect();
// }
// } else {
// connect();
// }
// } catch ( SQLException ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// }
// }
//
// public void connect() {
// try {
// Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
// connection = DriverManager.getConnection( "jdbc:mysql://" + host + ":" + port + "/" + db
// + "?autoReconnect=true", user, pass );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void disconnect() {
// if ( connection != null ) {
// try {
// connection.close();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
// }
//
// public void updateSilent( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// }
// }
//
// public void update( String qry ) {
// try ( Statement stmt = connection.createStatement() ) {
// stmt.executeUpdate( qry );
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void update( String stmtqry, String... values ) {
// try ( PreparedStatement stmt = connection.prepareStatement( stmtqry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// stmt.setString( i + 1, values[i] );
// }
// stmt.executeUpdate();
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(stmtqry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public void query( Consumer<ResultSet> consumer, String qry, String... values ) {
// try ( PreparedStatement pstmt = connection.prepareStatement( qry ) ) {
// for ( int i = 0; i < values.length; i++ ) {
// pstmt.setString( i + 1, values[i] );
// }
// try ( ResultSet rs = pstmt.executeQuery( qry ) ) {
// consumer.accept( rs );
// }
// } catch ( Exception ex ) {
// logger.log( Level.SEVERE, ex.getMessage() );
// // Bukkit.getLogger().severe(qry);
// // Bukkit.getLogger().severe(java.util.Arrays.toString(ex.getStackTrace()));
// }
// }
//
// public Connection getConnection() {
// return connection;
// }
//
// public String getName() {
// return name;
// }
//
// }
// Path: XServer-Bukkit/src/main/java/de/mickare/xserver/BukkitXServerManager.java
import java.io.IOException;
import de.mickare.xserver.exceptions.InvalidConfigurationException;
import de.mickare.xserver.exceptions.NotInitializedException;
import de.mickare.xserver.listener.StressTestListener;
import de.mickare.xserver.util.MySQL;
package de.mickare.xserver;
public class BukkitXServerManager extends XServerManager {
public static BukkitXServerManager getInstance() throws NotInitializedException {
return (BukkitXServerManager) XServerManager.getInstance();
}
private final BukkitEventHandler eventhandler;
private final BukkitXServerPlugin bukkitPlugin;
private final StressTestListener stressListener;
| protected BukkitXServerManager(String servername, BukkitXServerPlugin bukkitPlugin, MySQL connection, String sql_table_xservers, |
chiehmin/MinMinGuard | app/src/main/java/tw/fatminmin/xposed/minminguard/ui/adapter/ModeFragmentAdapter.java | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/ui/fragments/MainFragment.java
// public class MainFragment extends Fragment
// {
//
// public boolean isAlive = false;
// private MainActivity mainActivity;
// private FragmentMode mMode;
// private Button mBtnMode;
// private AppsAdapter adapter;
// private SharedPreferences mModPref;
// private final View.OnClickListener btnModeClick = new View.OnClickListener()
// {
// @Override
// public void onClick(View v)
// {
// mModPref.edit().putString(Common.KEY_MODE, Common.getModeString(mMode)).apply();
// mBtnMode.setVisibility(View.GONE);
// adapter.notifyDataSetChanged();
// }
// };
//
// public static MainFragment newInstance(FragmentMode mode)
// {
// MainFragment fragment = new MainFragment();
// Bundle args = new Bundle();
// args.putInt("mode", mode.ordinal());
// fragment.setArguments(args);
// return fragment;
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState)
// {
// super.onCreate(savedInstanceState);
// setHasOptionsMenu(true);
// }
//
// public void refreshUI()
// {
// if (mModPref.getString(Common.KEY_MODE, Common.VALUE_MODE_BLACKLIST).equals(Common.getModeString(mMode)))
// {
// mBtnMode.setVisibility(View.GONE);
// }
// else
// {
// mBtnMode.setVisibility(View.VISIBLE);
// }
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item)
// {
// return super.onOptionsItemSelected(item);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
// {
//
// mainActivity = (MainActivity) getActivity();
// mModPref = mainActivity.modPref;
// mMode = FragmentMode.values()[getArguments().getInt("mode")];
//
// View view = inflater.inflate(R.layout.fragment_main, container, false);
//
// TextView mTxtXposedEnabled = view.findViewById(R.id.txt_xposed_enable);
// mBtnMode = view.findViewById(R.id.btn_mode);
//
// RecyclerView mRecyclerView = view.findViewById(R.id.recycler_view);
//
// if (!Util.xposedEnabled())
// {
// mTxtXposedEnabled.setVisibility(View.VISIBLE);
// }
//
// /* setup apply button */
// mBtnMode.setOnClickListener(btnModeClick);
// if (mModPref.getString(Common.KEY_MODE, Common.VALUE_MODE_BLACKLIST).equals(Common.getModeString(mMode)))
// {
// mBtnMode.setVisibility(View.GONE);
// }
//
// mRecyclerView.setLayoutManager(new LinearLayoutManager(mainActivity));
// adapter = new AppsAdapter(getActivity(), mainActivity.masterAppList, mMode);
// mRecyclerView.setAdapter(adapter);
//
// isAlive = true;
// return view;
// }
//
// public FragmentMode getMode()
// {
// return mMode;
// }
//
// public void updateAndNotify(ArrayList<AppDetails> list)
// {
// adapter.setAppList(list);
// adapter.notifyDataSetChanged();
// }
//
// public enum FragmentMode
// {
// AUTO, BLACKLIST, WHITELIST
// }
// }
| import android.content.Context;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import tw.fatminmin.xposed.minminguard.R;
import tw.fatminmin.xposed.minminguard.ui.fragments.MainFragment; | package tw.fatminmin.xposed.minminguard.ui.adapter;
/**
* Created by fatminmin on 4/21/16.
*/
public final class ModeFragmentAdapter extends FragmentPagerAdapter
{
private static final int PAGE_COUNT = 3;
private Context mContext;
private String[] mTabTitles = new String[]{"AUTO", "Blacklist", "Whitelist"};
| // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/ui/fragments/MainFragment.java
// public class MainFragment extends Fragment
// {
//
// public boolean isAlive = false;
// private MainActivity mainActivity;
// private FragmentMode mMode;
// private Button mBtnMode;
// private AppsAdapter adapter;
// private SharedPreferences mModPref;
// private final View.OnClickListener btnModeClick = new View.OnClickListener()
// {
// @Override
// public void onClick(View v)
// {
// mModPref.edit().putString(Common.KEY_MODE, Common.getModeString(mMode)).apply();
// mBtnMode.setVisibility(View.GONE);
// adapter.notifyDataSetChanged();
// }
// };
//
// public static MainFragment newInstance(FragmentMode mode)
// {
// MainFragment fragment = new MainFragment();
// Bundle args = new Bundle();
// args.putInt("mode", mode.ordinal());
// fragment.setArguments(args);
// return fragment;
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState)
// {
// super.onCreate(savedInstanceState);
// setHasOptionsMenu(true);
// }
//
// public void refreshUI()
// {
// if (mModPref.getString(Common.KEY_MODE, Common.VALUE_MODE_BLACKLIST).equals(Common.getModeString(mMode)))
// {
// mBtnMode.setVisibility(View.GONE);
// }
// else
// {
// mBtnMode.setVisibility(View.VISIBLE);
// }
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item)
// {
// return super.onOptionsItemSelected(item);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
// {
//
// mainActivity = (MainActivity) getActivity();
// mModPref = mainActivity.modPref;
// mMode = FragmentMode.values()[getArguments().getInt("mode")];
//
// View view = inflater.inflate(R.layout.fragment_main, container, false);
//
// TextView mTxtXposedEnabled = view.findViewById(R.id.txt_xposed_enable);
// mBtnMode = view.findViewById(R.id.btn_mode);
//
// RecyclerView mRecyclerView = view.findViewById(R.id.recycler_view);
//
// if (!Util.xposedEnabled())
// {
// mTxtXposedEnabled.setVisibility(View.VISIBLE);
// }
//
// /* setup apply button */
// mBtnMode.setOnClickListener(btnModeClick);
// if (mModPref.getString(Common.KEY_MODE, Common.VALUE_MODE_BLACKLIST).equals(Common.getModeString(mMode)))
// {
// mBtnMode.setVisibility(View.GONE);
// }
//
// mRecyclerView.setLayoutManager(new LinearLayoutManager(mainActivity));
// adapter = new AppsAdapter(getActivity(), mainActivity.masterAppList, mMode);
// mRecyclerView.setAdapter(adapter);
//
// isAlive = true;
// return view;
// }
//
// public FragmentMode getMode()
// {
// return mMode;
// }
//
// public void updateAndNotify(ArrayList<AppDetails> list)
// {
// adapter.setAppList(list);
// adapter.notifyDataSetChanged();
// }
//
// public enum FragmentMode
// {
// AUTO, BLACKLIST, WHITELIST
// }
// }
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/ui/adapter/ModeFragmentAdapter.java
import android.content.Context;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import tw.fatminmin.xposed.minminguard.R;
import tw.fatminmin.xposed.minminguard.ui.fragments.MainFragment;
package tw.fatminmin.xposed.minminguard.ui.adapter;
/**
* Created by fatminmin on 4/21/16.
*/
public final class ModeFragmentAdapter extends FragmentPagerAdapter
{
private static final int PAGE_COUNT = 3;
private Context mContext;
private String[] mTabTitles = new String[]{"AUTO", "Blacklist", "Whitelist"};
| private MainFragment[] mFragments = new MainFragment[]{ |
chiehmin/MinMinGuard | app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/custom_mod/PeriodCalendar.java | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/ViewBlocking.java
// public class ViewBlocking
// {
// public static void removeAdView(String packageName, View view)
// {
// Util.notifyRemoveAdView(view.getContext(), packageName, 1);
// removeAdView(packageName, view, true, 51);
// }
//
// private static void removeAdView(final String packageName, final View view, final boolean first, final float heightLimit)
// {
// float adHeight = convertPixelsToDp(view.getHeight());
//
// if (first || (adHeight > 0 && adHeight <= heightLimit))
// {
// ViewGroup.LayoutParams params = view.getLayoutParams();
//
// if (params == null)
// params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
// else
// params.height = 0;
//
// view.setLayoutParams(params);
// }
//
// // preventing view not ready situation
// view.post(new Runnable()
// {
// @Override
// public void run()
// {
// float adHeight = convertPixelsToDp(view.getHeight());
//
// if (first || (adHeight > 0 && adHeight <= heightLimit))
// {
// ViewGroup.LayoutParams params = view.getLayoutParams();
//
// if (params == null)
// params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
// else
// params.height = 0;
//
// view.setLayoutParams(params);
// }
// }
// });
//
// if (view.getParent() != null && view.getParent() instanceof ViewGroup)
// {
// ViewGroup parent = (ViewGroup) view.getParent();
//
// removeAdView(packageName, parent, false, heightLimit);
// }
// }
//
// private static DisplayMetrics metrics = new DisplayMetrics();;
//
// private static float convertPixelsToDp(float px)
// {
// if(Main.resources != null)
// metrics = Main.resources.getDisplayMetrics();
//
// return px / (metrics.densityDpi / 160f);
// }
// }
| import android.view.View;
import de.robv.android.xposed.callbacks.XC_InitPackageResources;
import de.robv.android.xposed.callbacks.XC_LayoutInflated;
import tw.fatminmin.xposed.minminguard.blocker.ViewBlocking; | package tw.fatminmin.xposed.minminguard.blocker.custom_mod;
/**
* Created by fatminmin on 2015/10/30.
*/
final class PeriodCalendar
{
private static String pkgName = "com.popularapp.periodcalendar";
private PeriodCalendar() throws InstantiationException
{
throw new InstantiationException("This class is not for instantiation");
}
//TODO Lets check if we are using an Xposed version that supports resource hooking
public static void handleInitPackageResources(XC_InitPackageResources.InitPackageResourcesParam resparam)
{
if (!resparam.packageName.equals(pkgName))
{
return;
}
resparam.res.hookLayout(pkgName, "layout", "native_ad", new XC_LayoutInflated()
{
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam)
{
View ad = liparam.view.findViewById(liparam.res.getIdentifier("native_layout", "id", pkgName));
| // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/ViewBlocking.java
// public class ViewBlocking
// {
// public static void removeAdView(String packageName, View view)
// {
// Util.notifyRemoveAdView(view.getContext(), packageName, 1);
// removeAdView(packageName, view, true, 51);
// }
//
// private static void removeAdView(final String packageName, final View view, final boolean first, final float heightLimit)
// {
// float adHeight = convertPixelsToDp(view.getHeight());
//
// if (first || (adHeight > 0 && adHeight <= heightLimit))
// {
// ViewGroup.LayoutParams params = view.getLayoutParams();
//
// if (params == null)
// params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
// else
// params.height = 0;
//
// view.setLayoutParams(params);
// }
//
// // preventing view not ready situation
// view.post(new Runnable()
// {
// @Override
// public void run()
// {
// float adHeight = convertPixelsToDp(view.getHeight());
//
// if (first || (adHeight > 0 && adHeight <= heightLimit))
// {
// ViewGroup.LayoutParams params = view.getLayoutParams();
//
// if (params == null)
// params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
// else
// params.height = 0;
//
// view.setLayoutParams(params);
// }
// }
// });
//
// if (view.getParent() != null && view.getParent() instanceof ViewGroup)
// {
// ViewGroup parent = (ViewGroup) view.getParent();
//
// removeAdView(packageName, parent, false, heightLimit);
// }
// }
//
// private static DisplayMetrics metrics = new DisplayMetrics();;
//
// private static float convertPixelsToDp(float px)
// {
// if(Main.resources != null)
// metrics = Main.resources.getDisplayMetrics();
//
// return px / (metrics.densityDpi / 160f);
// }
// }
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/custom_mod/PeriodCalendar.java
import android.view.View;
import de.robv.android.xposed.callbacks.XC_InitPackageResources;
import de.robv.android.xposed.callbacks.XC_LayoutInflated;
import tw.fatminmin.xposed.minminguard.blocker.ViewBlocking;
package tw.fatminmin.xposed.minminguard.blocker.custom_mod;
/**
* Created by fatminmin on 2015/10/30.
*/
final class PeriodCalendar
{
private static String pkgName = "com.popularapp.periodcalendar";
private PeriodCalendar() throws InstantiationException
{
throw new InstantiationException("This class is not for instantiation");
}
//TODO Lets check if we are using an Xposed version that supports resource hooking
public static void handleInitPackageResources(XC_InitPackageResources.InitPackageResourcesParam resparam)
{
if (!resparam.packageName.equals(pkgName))
{
return;
}
resparam.res.hookLayout(pkgName, "layout", "native_ad", new XC_LayoutInflated()
{
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam)
{
View ad = liparam.view.findViewById(liparam.res.getIdentifier("native_layout", "id", pkgName));
| ViewBlocking.removeAdView(pkgName, ad); |
chiehmin/MinMinGuard | app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/custom_mod/_2chMate.java | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Util.java
// public final class Util
// {
// // change it to false for release build
// public static boolean DEBUG = BuildConfig.DEBUG;
//
// public static ExecutorService notifyWorker;
//
// public static final String TAG = "MinMinGuard";
// private static final String PACKAGE = "tw.fatminmin.xposed.minminguard";
//
// private Util() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static Boolean xposedEnabled()
// {
// return false;
// }
//
// public static String getAppVersion(Context context)
// {
// String version = null;
// PackageManager pm = context.getPackageManager();
//
// try
// {
// version = pm.getPackageInfo(PACKAGE, 0).versionName;
// }
// catch (PackageManager.NameNotFoundException e)
// {
// }
//
// return version;
// }
//
// public static void log(String packageName, String msg)
// {
// if (DEBUG)
// {
// //Log.d(TAG, packageName + ": " + msg);
// XposedBridge.log(packageName + ": " + msg);
// }
// }
//
// public static Application getCurrentApplication()
// {
// try
// {
// return AndroidAppHelper.currentApplication();
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// return null;
// }
//
// public static void saveLog(final File dest, final Context context, final Handler handler)
// {
// handler.post(new Runnable()
// {
//
// @Override
// public void run()
// {
// try
// {
//
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// });
// }
//
// public static void notifyAdNetwork(final Context context, final String pkgName, final String adNetwork)
// {
// new Thread(new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = context.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_NETWORK, adNetwork);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// }).start();
// }
//
// public static void notifyRemoveAdView(final Context context, final String pkgName, final int blockNum)
// {
// final Context mContext;
//
// if (context == null)
// mContext = getCurrentApplication();
// else
// mContext = context;
//
// Runnable task = new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = mContext.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_BLOCK_NUM, blockNum);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// };
//
// notifyWorker.submit(task);
// }
//
// public static void hookAllMethods(String className, ClassLoader classLoader, String method, XC_MethodHook callBack)
// {
// Class<?> clazz = XposedHelpers.findClass(className, classLoader);
//
// XposedBridge.hookAllMethods(clazz, method, callBack);
// }
// }
| import android.view.View;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.XposedHelpers.ClassNotFoundError;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import tw.fatminmin.xposed.minminguard.blocker.Util; | package tw.fatminmin.xposed.minminguard.blocker.custom_mod;
public final class _2chMate
{
private _2chMate() throws InstantiationException
{
throw new InstantiationException("This class is not for instantiation");
}
public static boolean handleLoadPackage(final String packageName, LoadPackageParam lpparam)
{
if (!packageName.equals("jp.co.airfront.android.a2chMate"))
{
return false;
}
try
{
final Class<?> viewGroupClass = XposedHelpers.findClass("android.view.ViewGroup", lpparam.classLoader);
XposedBridge.hookAllMethods(viewGroupClass, "addView", new XC_MethodHook()
{
@Override
protected void beforeHookedMethod(MethodHookParam param)
{
final View view = (View) param.args[0];
if (view.getClass().getName().equals("jp.syoboi.a2chMate.view.MyAdView"))
{ | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Util.java
// public final class Util
// {
// // change it to false for release build
// public static boolean DEBUG = BuildConfig.DEBUG;
//
// public static ExecutorService notifyWorker;
//
// public static final String TAG = "MinMinGuard";
// private static final String PACKAGE = "tw.fatminmin.xposed.minminguard";
//
// private Util() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static Boolean xposedEnabled()
// {
// return false;
// }
//
// public static String getAppVersion(Context context)
// {
// String version = null;
// PackageManager pm = context.getPackageManager();
//
// try
// {
// version = pm.getPackageInfo(PACKAGE, 0).versionName;
// }
// catch (PackageManager.NameNotFoundException e)
// {
// }
//
// return version;
// }
//
// public static void log(String packageName, String msg)
// {
// if (DEBUG)
// {
// //Log.d(TAG, packageName + ": " + msg);
// XposedBridge.log(packageName + ": " + msg);
// }
// }
//
// public static Application getCurrentApplication()
// {
// try
// {
// return AndroidAppHelper.currentApplication();
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// return null;
// }
//
// public static void saveLog(final File dest, final Context context, final Handler handler)
// {
// handler.post(new Runnable()
// {
//
// @Override
// public void run()
// {
// try
// {
//
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// });
// }
//
// public static void notifyAdNetwork(final Context context, final String pkgName, final String adNetwork)
// {
// new Thread(new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = context.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_NETWORK, adNetwork);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// }).start();
// }
//
// public static void notifyRemoveAdView(final Context context, final String pkgName, final int blockNum)
// {
// final Context mContext;
//
// if (context == null)
// mContext = getCurrentApplication();
// else
// mContext = context;
//
// Runnable task = new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = mContext.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_BLOCK_NUM, blockNum);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// };
//
// notifyWorker.submit(task);
// }
//
// public static void hookAllMethods(String className, ClassLoader classLoader, String method, XC_MethodHook callBack)
// {
// Class<?> clazz = XposedHelpers.findClass(className, classLoader);
//
// XposedBridge.hookAllMethods(clazz, method, callBack);
// }
// }
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/custom_mod/_2chMate.java
import android.view.View;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.XposedHelpers.ClassNotFoundError;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import tw.fatminmin.xposed.minminguard.blocker.Util;
package tw.fatminmin.xposed.minminguard.blocker.custom_mod;
public final class _2chMate
{
private _2chMate() throws InstantiationException
{
throw new InstantiationException("This class is not for instantiation");
}
public static boolean handleLoadPackage(final String packageName, LoadPackageParam lpparam)
{
if (!packageName.equals("jp.co.airfront.android.a2chMate"))
{
return false;
}
try
{
final Class<?> viewGroupClass = XposedHelpers.findClass("android.view.ViewGroup", lpparam.classLoader);
XposedBridge.hookAllMethods(viewGroupClass, "addView", new XC_MethodHook()
{
@Override
protected void beforeHookedMethod(MethodHookParam param)
{
final View view = (View) param.args[0];
if (view.getClass().getName().equals("jp.syoboi.a2chMate.view.MyAdView"))
{ | Util.log(packageName, "Detect 2chmate MyAdView in " + packageName); |
chiehmin/MinMinGuard | app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/adnetwork/Onelouder.java | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Blocker.java
// public abstract class Blocker
// {
// /**
// * @param packageName
// * @param lpparam
// * @return True if currrent handling app using this adnetwork. False otherwise.
// */
// abstract public boolean handleLoadPackage(final String packageName, XC_LoadPackage.LoadPackageParam lpparam);
//
// abstract public String getBanner();
//
// abstract public String getBannerPrefix();
//
// public String getName()
// {
// return getClass().getSimpleName();
// }
// }
//
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Util.java
// public final class Util
// {
// // change it to false for release build
// public static boolean DEBUG = BuildConfig.DEBUG;
//
// public static ExecutorService notifyWorker;
//
// public static final String TAG = "MinMinGuard";
// private static final String PACKAGE = "tw.fatminmin.xposed.minminguard";
//
// private Util() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static Boolean xposedEnabled()
// {
// return false;
// }
//
// public static String getAppVersion(Context context)
// {
// String version = null;
// PackageManager pm = context.getPackageManager();
//
// try
// {
// version = pm.getPackageInfo(PACKAGE, 0).versionName;
// }
// catch (PackageManager.NameNotFoundException e)
// {
// }
//
// return version;
// }
//
// public static void log(String packageName, String msg)
// {
// if (DEBUG)
// {
// //Log.d(TAG, packageName + ": " + msg);
// XposedBridge.log(packageName + ": " + msg);
// }
// }
//
// public static Application getCurrentApplication()
// {
// try
// {
// return AndroidAppHelper.currentApplication();
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// return null;
// }
//
// public static void saveLog(final File dest, final Context context, final Handler handler)
// {
// handler.post(new Runnable()
// {
//
// @Override
// public void run()
// {
// try
// {
//
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// });
// }
//
// public static void notifyAdNetwork(final Context context, final String pkgName, final String adNetwork)
// {
// new Thread(new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = context.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_NETWORK, adNetwork);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// }).start();
// }
//
// public static void notifyRemoveAdView(final Context context, final String pkgName, final int blockNum)
// {
// final Context mContext;
//
// if (context == null)
// mContext = getCurrentApplication();
// else
// mContext = context;
//
// Runnable task = new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = mContext.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_BLOCK_NUM, blockNum);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// };
//
// notifyWorker.submit(task);
// }
//
// public static void hookAllMethods(String className, ClassLoader classLoader, String method, XC_MethodHook callBack)
// {
// Class<?> clazz = XposedHelpers.findClass(className, classLoader);
//
// XposedBridge.hookAllMethods(clazz, method, callBack);
// }
// }
| import android.view.View;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.XposedHelpers.ClassNotFoundError;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import tw.fatminmin.xposed.minminguard.blocker.Blocker;
import tw.fatminmin.xposed.minminguard.blocker.Util;
import java.lang.reflect.Method; | package tw.fatminmin.xposed.minminguard.blocker.adnetwork;
public class Onelouder extends Blocker
{
private static final String BANNER = "com.onelouder.adlib.AdView";
private static final String BANNER_PREFIX = "com.onelouder.adlib";
//TODO Use APIBlocking
public boolean handleLoadPackage(final String packageName, LoadPackageParam lpparam)
{
try
{
Class<?> adView = XposedHelpers.findClass("com.onelouder.adlib.AdView", lpparam.classLoader);
XposedBridge.hookAllMethods(adView, "setVisibility", new XC_MethodHook()
{
@Override
protected void beforeHookedMethod(MethodHookParam param)
{ | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Blocker.java
// public abstract class Blocker
// {
// /**
// * @param packageName
// * @param lpparam
// * @return True if currrent handling app using this adnetwork. False otherwise.
// */
// abstract public boolean handleLoadPackage(final String packageName, XC_LoadPackage.LoadPackageParam lpparam);
//
// abstract public String getBanner();
//
// abstract public String getBannerPrefix();
//
// public String getName()
// {
// return getClass().getSimpleName();
// }
// }
//
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Util.java
// public final class Util
// {
// // change it to false for release build
// public static boolean DEBUG = BuildConfig.DEBUG;
//
// public static ExecutorService notifyWorker;
//
// public static final String TAG = "MinMinGuard";
// private static final String PACKAGE = "tw.fatminmin.xposed.minminguard";
//
// private Util() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static Boolean xposedEnabled()
// {
// return false;
// }
//
// public static String getAppVersion(Context context)
// {
// String version = null;
// PackageManager pm = context.getPackageManager();
//
// try
// {
// version = pm.getPackageInfo(PACKAGE, 0).versionName;
// }
// catch (PackageManager.NameNotFoundException e)
// {
// }
//
// return version;
// }
//
// public static void log(String packageName, String msg)
// {
// if (DEBUG)
// {
// //Log.d(TAG, packageName + ": " + msg);
// XposedBridge.log(packageName + ": " + msg);
// }
// }
//
// public static Application getCurrentApplication()
// {
// try
// {
// return AndroidAppHelper.currentApplication();
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// return null;
// }
//
// public static void saveLog(final File dest, final Context context, final Handler handler)
// {
// handler.post(new Runnable()
// {
//
// @Override
// public void run()
// {
// try
// {
//
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// });
// }
//
// public static void notifyAdNetwork(final Context context, final String pkgName, final String adNetwork)
// {
// new Thread(new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = context.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_NETWORK, adNetwork);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// }).start();
// }
//
// public static void notifyRemoveAdView(final Context context, final String pkgName, final int blockNum)
// {
// final Context mContext;
//
// if (context == null)
// mContext = getCurrentApplication();
// else
// mContext = context;
//
// Runnable task = new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = mContext.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_BLOCK_NUM, blockNum);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// };
//
// notifyWorker.submit(task);
// }
//
// public static void hookAllMethods(String className, ClassLoader classLoader, String method, XC_MethodHook callBack)
// {
// Class<?> clazz = XposedHelpers.findClass(className, classLoader);
//
// XposedBridge.hookAllMethods(clazz, method, callBack);
// }
// }
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/adnetwork/Onelouder.java
import android.view.View;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.XposedHelpers.ClassNotFoundError;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import tw.fatminmin.xposed.minminguard.blocker.Blocker;
import tw.fatminmin.xposed.minminguard.blocker.Util;
import java.lang.reflect.Method;
package tw.fatminmin.xposed.minminguard.blocker.adnetwork;
public class Onelouder extends Blocker
{
private static final String BANNER = "com.onelouder.adlib.AdView";
private static final String BANNER_PREFIX = "com.onelouder.adlib";
//TODO Use APIBlocking
public boolean handleLoadPackage(final String packageName, LoadPackageParam lpparam)
{
try
{
Class<?> adView = XposedHelpers.findClass("com.onelouder.adlib.AdView", lpparam.classLoader);
XposedBridge.hookAllMethods(adView, "setVisibility", new XC_MethodHook()
{
@Override
protected void beforeHookedMethod(MethodHookParam param)
{ | Util.log(packageName, "Detect onelouder AdView setVisibility in " + packageName); |
chiehmin/MinMinGuard | app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/adnetwork/mAdserve.java | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Blocker.java
// public abstract class Blocker
// {
// /**
// * @param packageName
// * @param lpparam
// * @return True if currrent handling app using this adnetwork. False otherwise.
// */
// abstract public boolean handleLoadPackage(final String packageName, XC_LoadPackage.LoadPackageParam lpparam);
//
// abstract public String getBanner();
//
// abstract public String getBannerPrefix();
//
// public String getName()
// {
// return getClass().getSimpleName();
// }
// }
//
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Util.java
// public final class Util
// {
// // change it to false for release build
// public static boolean DEBUG = BuildConfig.DEBUG;
//
// public static ExecutorService notifyWorker;
//
// public static final String TAG = "MinMinGuard";
// private static final String PACKAGE = "tw.fatminmin.xposed.minminguard";
//
// private Util() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static Boolean xposedEnabled()
// {
// return false;
// }
//
// public static String getAppVersion(Context context)
// {
// String version = null;
// PackageManager pm = context.getPackageManager();
//
// try
// {
// version = pm.getPackageInfo(PACKAGE, 0).versionName;
// }
// catch (PackageManager.NameNotFoundException e)
// {
// }
//
// return version;
// }
//
// public static void log(String packageName, String msg)
// {
// if (DEBUG)
// {
// //Log.d(TAG, packageName + ": " + msg);
// XposedBridge.log(packageName + ": " + msg);
// }
// }
//
// public static Application getCurrentApplication()
// {
// try
// {
// return AndroidAppHelper.currentApplication();
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// return null;
// }
//
// public static void saveLog(final File dest, final Context context, final Handler handler)
// {
// handler.post(new Runnable()
// {
//
// @Override
// public void run()
// {
// try
// {
//
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// });
// }
//
// public static void notifyAdNetwork(final Context context, final String pkgName, final String adNetwork)
// {
// new Thread(new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = context.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_NETWORK, adNetwork);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// }).start();
// }
//
// public static void notifyRemoveAdView(final Context context, final String pkgName, final int blockNum)
// {
// final Context mContext;
//
// if (context == null)
// mContext = getCurrentApplication();
// else
// mContext = context;
//
// Runnable task = new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = mContext.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_BLOCK_NUM, blockNum);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// };
//
// notifyWorker.submit(task);
// }
//
// public static void hookAllMethods(String className, ClassLoader classLoader, String method, XC_MethodHook callBack)
// {
// Class<?> clazz = XposedHelpers.findClass(className, classLoader);
//
// XposedBridge.hookAllMethods(clazz, method, callBack);
// }
// }
| import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.XposedHelpers.ClassNotFoundError;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import tw.fatminmin.xposed.minminguard.blocker.Blocker;
import tw.fatminmin.xposed.minminguard.blocker.Util; | package tw.fatminmin.xposed.minminguard.blocker.adnetwork;
public class mAdserve extends Blocker
{
private static final String BANNER = "com.adsdk.sdk.banner.InAppWebView";
private static final String BANNER_PREFIX = "com.adsdk.sdk.banner";
public boolean handleLoadPackage(final String packageName, LoadPackageParam lpparam)
{
try
{
//TODO Add blockConstructor to ApiBlocking, so we dont have to do this hack..
Class<?> adView = XposedHelpers.findClass("com.adsdk.sdk.banner.InAppWebView", lpparam.classLoader);
XposedBridge.hookAllConstructors(adView, new XC_MethodHook()
{
@Override
protected void beforeHookedMethod(MethodHookParam param)
{ | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Blocker.java
// public abstract class Blocker
// {
// /**
// * @param packageName
// * @param lpparam
// * @return True if currrent handling app using this adnetwork. False otherwise.
// */
// abstract public boolean handleLoadPackage(final String packageName, XC_LoadPackage.LoadPackageParam lpparam);
//
// abstract public String getBanner();
//
// abstract public String getBannerPrefix();
//
// public String getName()
// {
// return getClass().getSimpleName();
// }
// }
//
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Util.java
// public final class Util
// {
// // change it to false for release build
// public static boolean DEBUG = BuildConfig.DEBUG;
//
// public static ExecutorService notifyWorker;
//
// public static final String TAG = "MinMinGuard";
// private static final String PACKAGE = "tw.fatminmin.xposed.minminguard";
//
// private Util() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static Boolean xposedEnabled()
// {
// return false;
// }
//
// public static String getAppVersion(Context context)
// {
// String version = null;
// PackageManager pm = context.getPackageManager();
//
// try
// {
// version = pm.getPackageInfo(PACKAGE, 0).versionName;
// }
// catch (PackageManager.NameNotFoundException e)
// {
// }
//
// return version;
// }
//
// public static void log(String packageName, String msg)
// {
// if (DEBUG)
// {
// //Log.d(TAG, packageName + ": " + msg);
// XposedBridge.log(packageName + ": " + msg);
// }
// }
//
// public static Application getCurrentApplication()
// {
// try
// {
// return AndroidAppHelper.currentApplication();
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// return null;
// }
//
// public static void saveLog(final File dest, final Context context, final Handler handler)
// {
// handler.post(new Runnable()
// {
//
// @Override
// public void run()
// {
// try
// {
//
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// });
// }
//
// public static void notifyAdNetwork(final Context context, final String pkgName, final String adNetwork)
// {
// new Thread(new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = context.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_NETWORK, adNetwork);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// }).start();
// }
//
// public static void notifyRemoveAdView(final Context context, final String pkgName, final int blockNum)
// {
// final Context mContext;
//
// if (context == null)
// mContext = getCurrentApplication();
// else
// mContext = context;
//
// Runnable task = new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = mContext.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_BLOCK_NUM, blockNum);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// };
//
// notifyWorker.submit(task);
// }
//
// public static void hookAllMethods(String className, ClassLoader classLoader, String method, XC_MethodHook callBack)
// {
// Class<?> clazz = XposedHelpers.findClass(className, classLoader);
//
// XposedBridge.hookAllMethods(clazz, method, callBack);
// }
// }
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/adnetwork/mAdserve.java
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.XposedHelpers.ClassNotFoundError;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import tw.fatminmin.xposed.minminguard.blocker.Blocker;
import tw.fatminmin.xposed.minminguard.blocker.Util;
package tw.fatminmin.xposed.minminguard.blocker.adnetwork;
public class mAdserve extends Blocker
{
private static final String BANNER = "com.adsdk.sdk.banner.InAppWebView";
private static final String BANNER_PREFIX = "com.adsdk.sdk.banner";
public boolean handleLoadPackage(final String packageName, LoadPackageParam lpparam)
{
try
{
//TODO Add blockConstructor to ApiBlocking, so we dont have to do this hack..
Class<?> adView = XposedHelpers.findClass("com.adsdk.sdk.banner.InAppWebView", lpparam.classLoader);
XposedBridge.hookAllConstructors(adView, new XC_MethodHook()
{
@Override
protected void beforeHookedMethod(MethodHookParam param)
{ | Util.log(packageName, "Detect mAdserve InAppWebView constructor in " + packageName); |
chiehmin/MinMinGuard | app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/custom_mod/Viafree.java | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Util.java
// public final class Util
// {
// // change it to false for release build
// public static boolean DEBUG = BuildConfig.DEBUG;
//
// public static ExecutorService notifyWorker;
//
// public static final String TAG = "MinMinGuard";
// private static final String PACKAGE = "tw.fatminmin.xposed.minminguard";
//
// private Util() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static Boolean xposedEnabled()
// {
// return false;
// }
//
// public static String getAppVersion(Context context)
// {
// String version = null;
// PackageManager pm = context.getPackageManager();
//
// try
// {
// version = pm.getPackageInfo(PACKAGE, 0).versionName;
// }
// catch (PackageManager.NameNotFoundException e)
// {
// }
//
// return version;
// }
//
// public static void log(String packageName, String msg)
// {
// if (DEBUG)
// {
// //Log.d(TAG, packageName + ": " + msg);
// XposedBridge.log(packageName + ": " + msg);
// }
// }
//
// public static Application getCurrentApplication()
// {
// try
// {
// return AndroidAppHelper.currentApplication();
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// return null;
// }
//
// public static void saveLog(final File dest, final Context context, final Handler handler)
// {
// handler.post(new Runnable()
// {
//
// @Override
// public void run()
// {
// try
// {
//
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// });
// }
//
// public static void notifyAdNetwork(final Context context, final String pkgName, final String adNetwork)
// {
// new Thread(new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = context.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_NETWORK, adNetwork);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// }).start();
// }
//
// public static void notifyRemoveAdView(final Context context, final String pkgName, final int blockNum)
// {
// final Context mContext;
//
// if (context == null)
// mContext = getCurrentApplication();
// else
// mContext = context;
//
// Runnable task = new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = mContext.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_BLOCK_NUM, blockNum);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// };
//
// notifyWorker.submit(task);
// }
//
// public static void hookAllMethods(String className, ClassLoader classLoader, String method, XC_MethodHook callBack)
// {
// Class<?> clazz = XposedHelpers.findClass(className, classLoader);
//
// XposedBridge.hookAllMethods(clazz, method, callBack);
// }
// }
| import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
import tw.fatminmin.xposed.minminguard.blocker.Util;
import java.util.ArrayList; | package tw.fatminmin.xposed.minminguard.blocker.custom_mod;
public final class Viafree
{
private static final String pkg = "viafree.android";
private static final String className = "com.viafree.android.videoplayer.ad.models.Freewheel";
private static final String method = "f";
private Viafree() throws InstantiationException
{
throw new InstantiationException("This class is not for instantiation");
}
public static boolean handleLoadPackage(final String packageName, XC_LoadPackage.LoadPackageParam lpparam)
{
if (!lpparam.packageName.contains(pkg))
{
return false;
}
XposedHelpers.findAndHookMethod(className, lpparam.classLoader, method, new XC_MethodHook()
{
@Override
protected void beforeHookedMethod(MethodHookParam param)
{
param.setResult(new ArrayList<Object>()); | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Util.java
// public final class Util
// {
// // change it to false for release build
// public static boolean DEBUG = BuildConfig.DEBUG;
//
// public static ExecutorService notifyWorker;
//
// public static final String TAG = "MinMinGuard";
// private static final String PACKAGE = "tw.fatminmin.xposed.minminguard";
//
// private Util() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static Boolean xposedEnabled()
// {
// return false;
// }
//
// public static String getAppVersion(Context context)
// {
// String version = null;
// PackageManager pm = context.getPackageManager();
//
// try
// {
// version = pm.getPackageInfo(PACKAGE, 0).versionName;
// }
// catch (PackageManager.NameNotFoundException e)
// {
// }
//
// return version;
// }
//
// public static void log(String packageName, String msg)
// {
// if (DEBUG)
// {
// //Log.d(TAG, packageName + ": " + msg);
// XposedBridge.log(packageName + ": " + msg);
// }
// }
//
// public static Application getCurrentApplication()
// {
// try
// {
// return AndroidAppHelper.currentApplication();
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// return null;
// }
//
// public static void saveLog(final File dest, final Context context, final Handler handler)
// {
// handler.post(new Runnable()
// {
//
// @Override
// public void run()
// {
// try
// {
//
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// });
// }
//
// public static void notifyAdNetwork(final Context context, final String pkgName, final String adNetwork)
// {
// new Thread(new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = context.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_NETWORK, adNetwork);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// }).start();
// }
//
// public static void notifyRemoveAdView(final Context context, final String pkgName, final int blockNum)
// {
// final Context mContext;
//
// if (context == null)
// mContext = getCurrentApplication();
// else
// mContext = context;
//
// Runnable task = new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = mContext.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_BLOCK_NUM, blockNum);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// };
//
// notifyWorker.submit(task);
// }
//
// public static void hookAllMethods(String className, ClassLoader classLoader, String method, XC_MethodHook callBack)
// {
// Class<?> clazz = XposedHelpers.findClass(className, classLoader);
//
// XposedBridge.hookAllMethods(clazz, method, callBack);
// }
// }
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/custom_mod/Viafree.java
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
import tw.fatminmin.xposed.minminguard.blocker.Util;
import java.util.ArrayList;
package tw.fatminmin.xposed.minminguard.blocker.custom_mod;
public final class Viafree
{
private static final String pkg = "viafree.android";
private static final String className = "com.viafree.android.videoplayer.ad.models.Freewheel";
private static final String method = "f";
private Viafree() throws InstantiationException
{
throw new InstantiationException("This class is not for instantiation");
}
public static boolean handleLoadPackage(final String packageName, XC_LoadPackage.LoadPackageParam lpparam)
{
if (!lpparam.packageName.contains(pkg))
{
return false;
}
XposedHelpers.findAndHookMethod(className, lpparam.classLoader, method, new XC_MethodHook()
{
@Override
protected void beforeHookedMethod(MethodHookParam param)
{
param.setResult(new ArrayList<Object>()); | Util.notifyRemoveAdView(null, packageName, 1); |
chiehmin/MinMinGuard | app/src/main/java/tw/fatminmin/xposed/minminguard/Common.java | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/ui/fragments/MainFragment.java
// public class MainFragment extends Fragment
// {
//
// public boolean isAlive = false;
// private MainActivity mainActivity;
// private FragmentMode mMode;
// private Button mBtnMode;
// private AppsAdapter adapter;
// private SharedPreferences mModPref;
// private final View.OnClickListener btnModeClick = new View.OnClickListener()
// {
// @Override
// public void onClick(View v)
// {
// mModPref.edit().putString(Common.KEY_MODE, Common.getModeString(mMode)).apply();
// mBtnMode.setVisibility(View.GONE);
// adapter.notifyDataSetChanged();
// }
// };
//
// public static MainFragment newInstance(FragmentMode mode)
// {
// MainFragment fragment = new MainFragment();
// Bundle args = new Bundle();
// args.putInt("mode", mode.ordinal());
// fragment.setArguments(args);
// return fragment;
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState)
// {
// super.onCreate(savedInstanceState);
// setHasOptionsMenu(true);
// }
//
// public void refreshUI()
// {
// if (mModPref.getString(Common.KEY_MODE, Common.VALUE_MODE_BLACKLIST).equals(Common.getModeString(mMode)))
// {
// mBtnMode.setVisibility(View.GONE);
// }
// else
// {
// mBtnMode.setVisibility(View.VISIBLE);
// }
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item)
// {
// return super.onOptionsItemSelected(item);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
// {
//
// mainActivity = (MainActivity) getActivity();
// mModPref = mainActivity.modPref;
// mMode = FragmentMode.values()[getArguments().getInt("mode")];
//
// View view = inflater.inflate(R.layout.fragment_main, container, false);
//
// TextView mTxtXposedEnabled = view.findViewById(R.id.txt_xposed_enable);
// mBtnMode = view.findViewById(R.id.btn_mode);
//
// RecyclerView mRecyclerView = view.findViewById(R.id.recycler_view);
//
// if (!Util.xposedEnabled())
// {
// mTxtXposedEnabled.setVisibility(View.VISIBLE);
// }
//
// /* setup apply button */
// mBtnMode.setOnClickListener(btnModeClick);
// if (mModPref.getString(Common.KEY_MODE, Common.VALUE_MODE_BLACKLIST).equals(Common.getModeString(mMode)))
// {
// mBtnMode.setVisibility(View.GONE);
// }
//
// mRecyclerView.setLayoutManager(new LinearLayoutManager(mainActivity));
// adapter = new AppsAdapter(getActivity(), mainActivity.masterAppList, mMode);
// mRecyclerView.setAdapter(adapter);
//
// isAlive = true;
// return view;
// }
//
// public FragmentMode getMode()
// {
// return mMode;
// }
//
// public void updateAndNotify(ArrayList<AppDetails> list)
// {
// adapter.setAppList(list);
// adapter.notifyDataSetChanged();
// }
//
// public enum FragmentMode
// {
// AUTO, BLACKLIST, WHITELIST
// }
// }
| import tw.fatminmin.xposed.minminguard.ui.fragments.MainFragment; | package tw.fatminmin.xposed.minminguard;
/**
* Created by fatminmin on 2015/10/1.
*/
public class Common
{
public final static String PACKAGE_NAME = BuildConfig.APPLICATION_ID;
public final static String MOD_PREFS = "ModSettings";
public final static String UI_PREFS = "UI_PREF";
// UI Pref
public final static String KEY_FIRST_TIME = "first_time_2_0_alpha_7";
public final static String KEY_SHOW_SYSTEM_APPS = "show_system_apps";
public final static String KEY_SHOW_LAUNCHER_ICON = "show_launcher_icon";
// Xposed Mod Pref
public final static String KEY_MODE = "mode";
public final static String VALUE_MODE_AUTO = "auto";
public final static String VALUE_MODE_BLACKLIST = "blacklist";
public final static String VALUE_MODE_WHITELIST = "whitelist";
// Fragment Name
public final static String FRG_MAIN = "main_fragment";
// MinMinProvider
public final static String KEY_PKG_NAME = "PKG_NAME";
public final static String KEY_NETWORK = "AD_NETWORKS";
public final static String KEY_BLOCK_NUM = "BLOCK_NUM";
private Common() throws InstantiationException
{
throw new InstantiationException("This class is not for instantiation");
}
| // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/ui/fragments/MainFragment.java
// public class MainFragment extends Fragment
// {
//
// public boolean isAlive = false;
// private MainActivity mainActivity;
// private FragmentMode mMode;
// private Button mBtnMode;
// private AppsAdapter adapter;
// private SharedPreferences mModPref;
// private final View.OnClickListener btnModeClick = new View.OnClickListener()
// {
// @Override
// public void onClick(View v)
// {
// mModPref.edit().putString(Common.KEY_MODE, Common.getModeString(mMode)).apply();
// mBtnMode.setVisibility(View.GONE);
// adapter.notifyDataSetChanged();
// }
// };
//
// public static MainFragment newInstance(FragmentMode mode)
// {
// MainFragment fragment = new MainFragment();
// Bundle args = new Bundle();
// args.putInt("mode", mode.ordinal());
// fragment.setArguments(args);
// return fragment;
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState)
// {
// super.onCreate(savedInstanceState);
// setHasOptionsMenu(true);
// }
//
// public void refreshUI()
// {
// if (mModPref.getString(Common.KEY_MODE, Common.VALUE_MODE_BLACKLIST).equals(Common.getModeString(mMode)))
// {
// mBtnMode.setVisibility(View.GONE);
// }
// else
// {
// mBtnMode.setVisibility(View.VISIBLE);
// }
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item)
// {
// return super.onOptionsItemSelected(item);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
// {
//
// mainActivity = (MainActivity) getActivity();
// mModPref = mainActivity.modPref;
// mMode = FragmentMode.values()[getArguments().getInt("mode")];
//
// View view = inflater.inflate(R.layout.fragment_main, container, false);
//
// TextView mTxtXposedEnabled = view.findViewById(R.id.txt_xposed_enable);
// mBtnMode = view.findViewById(R.id.btn_mode);
//
// RecyclerView mRecyclerView = view.findViewById(R.id.recycler_view);
//
// if (!Util.xposedEnabled())
// {
// mTxtXposedEnabled.setVisibility(View.VISIBLE);
// }
//
// /* setup apply button */
// mBtnMode.setOnClickListener(btnModeClick);
// if (mModPref.getString(Common.KEY_MODE, Common.VALUE_MODE_BLACKLIST).equals(Common.getModeString(mMode)))
// {
// mBtnMode.setVisibility(View.GONE);
// }
//
// mRecyclerView.setLayoutManager(new LinearLayoutManager(mainActivity));
// adapter = new AppsAdapter(getActivity(), mainActivity.masterAppList, mMode);
// mRecyclerView.setAdapter(adapter);
//
// isAlive = true;
// return view;
// }
//
// public FragmentMode getMode()
// {
// return mMode;
// }
//
// public void updateAndNotify(ArrayList<AppDetails> list)
// {
// adapter.setAppList(list);
// adapter.notifyDataSetChanged();
// }
//
// public enum FragmentMode
// {
// AUTO, BLACKLIST, WHITELIST
// }
// }
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/Common.java
import tw.fatminmin.xposed.minminguard.ui.fragments.MainFragment;
package tw.fatminmin.xposed.minminguard;
/**
* Created by fatminmin on 2015/10/1.
*/
public class Common
{
public final static String PACKAGE_NAME = BuildConfig.APPLICATION_ID;
public final static String MOD_PREFS = "ModSettings";
public final static String UI_PREFS = "UI_PREF";
// UI Pref
public final static String KEY_FIRST_TIME = "first_time_2_0_alpha_7";
public final static String KEY_SHOW_SYSTEM_APPS = "show_system_apps";
public final static String KEY_SHOW_LAUNCHER_ICON = "show_launcher_icon";
// Xposed Mod Pref
public final static String KEY_MODE = "mode";
public final static String VALUE_MODE_AUTO = "auto";
public final static String VALUE_MODE_BLACKLIST = "blacklist";
public final static String VALUE_MODE_WHITELIST = "whitelist";
// Fragment Name
public final static String FRG_MAIN = "main_fragment";
// MinMinProvider
public final static String KEY_PKG_NAME = "PKG_NAME";
public final static String KEY_NETWORK = "AD_NETWORKS";
public final static String KEY_BLOCK_NUM = "BLOCK_NUM";
private Common() throws InstantiationException
{
throw new InstantiationException("This class is not for instantiation");
}
| public static String getModeString(MainFragment.FragmentMode mode) |
chiehmin/MinMinGuard | app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Util.java | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/Common.java
// public class Common
// {
// public final static String PACKAGE_NAME = BuildConfig.APPLICATION_ID;
//
// public final static String MOD_PREFS = "ModSettings";
// public final static String UI_PREFS = "UI_PREF";
//
// // UI Pref
// public final static String KEY_FIRST_TIME = "first_time_2_0_alpha_7";
// public final static String KEY_SHOW_SYSTEM_APPS = "show_system_apps";
// public final static String KEY_SHOW_LAUNCHER_ICON = "show_launcher_icon";
//
// // Xposed Mod Pref
// public final static String KEY_MODE = "mode";
// public final static String VALUE_MODE_AUTO = "auto";
// public final static String VALUE_MODE_BLACKLIST = "blacklist";
// public final static String VALUE_MODE_WHITELIST = "whitelist";
//
// // Fragment Name
// public final static String FRG_MAIN = "main_fragment";
//
// // MinMinProvider
// public final static String KEY_PKG_NAME = "PKG_NAME";
// public final static String KEY_NETWORK = "AD_NETWORKS";
// public final static String KEY_BLOCK_NUM = "BLOCK_NUM";
//
// private Common() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static String getModeString(MainFragment.FragmentMode mode)
// {
// switch (mode)
// {
// case AUTO:
// return Common.VALUE_MODE_AUTO;
// case BLACKLIST:
// return Common.VALUE_MODE_BLACKLIST;
// case WHITELIST:
// return Common.VALUE_MODE_WHITELIST;
// default:
// break;
// }
// return Common.VALUE_MODE_BLACKLIST;
// }
//
// public static String getWhiteListKey(String pkgName)
// {
// return pkgName + "_whitelist";
// }
// }
| import android.app.AndroidAppHelper;
import android.app.Application;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import java.io.File;
import java.util.concurrent.ExecutorService;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import tw.fatminmin.xposed.minminguard.BuildConfig;
import tw.fatminmin.xposed.minminguard.Common; | {
@Override
public void run()
{
try
{
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public static void notifyAdNetwork(final Context context, final String pkgName, final String adNetwork)
{
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
ContentValues values = new ContentValues();
| // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/Common.java
// public class Common
// {
// public final static String PACKAGE_NAME = BuildConfig.APPLICATION_ID;
//
// public final static String MOD_PREFS = "ModSettings";
// public final static String UI_PREFS = "UI_PREF";
//
// // UI Pref
// public final static String KEY_FIRST_TIME = "first_time_2_0_alpha_7";
// public final static String KEY_SHOW_SYSTEM_APPS = "show_system_apps";
// public final static String KEY_SHOW_LAUNCHER_ICON = "show_launcher_icon";
//
// // Xposed Mod Pref
// public final static String KEY_MODE = "mode";
// public final static String VALUE_MODE_AUTO = "auto";
// public final static String VALUE_MODE_BLACKLIST = "blacklist";
// public final static String VALUE_MODE_WHITELIST = "whitelist";
//
// // Fragment Name
// public final static String FRG_MAIN = "main_fragment";
//
// // MinMinProvider
// public final static String KEY_PKG_NAME = "PKG_NAME";
// public final static String KEY_NETWORK = "AD_NETWORKS";
// public final static String KEY_BLOCK_NUM = "BLOCK_NUM";
//
// private Common() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static String getModeString(MainFragment.FragmentMode mode)
// {
// switch (mode)
// {
// case AUTO:
// return Common.VALUE_MODE_AUTO;
// case BLACKLIST:
// return Common.VALUE_MODE_BLACKLIST;
// case WHITELIST:
// return Common.VALUE_MODE_WHITELIST;
// default:
// break;
// }
// return Common.VALUE_MODE_BLACKLIST;
// }
//
// public static String getWhiteListKey(String pkgName)
// {
// return pkgName + "_whitelist";
// }
// }
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Util.java
import android.app.AndroidAppHelper;
import android.app.Application;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import java.io.File;
import java.util.concurrent.ExecutorService;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import tw.fatminmin.xposed.minminguard.BuildConfig;
import tw.fatminmin.xposed.minminguard.Common;
{
@Override
public void run()
{
try
{
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public static void notifyAdNetwork(final Context context, final String pkgName, final String adNetwork)
{
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
ContentValues values = new ContentValues();
| values.put(Common.KEY_PKG_NAME, pkgName); |
chiehmin/MinMinGuard | app/src/main/java/tw/fatminmin/xposed/minminguard/ui/dialog/AppDetailDialogFragment.java | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/Common.java
// public class Common
// {
// public final static String PACKAGE_NAME = BuildConfig.APPLICATION_ID;
//
// public final static String MOD_PREFS = "ModSettings";
// public final static String UI_PREFS = "UI_PREF";
//
// // UI Pref
// public final static String KEY_FIRST_TIME = "first_time_2_0_alpha_7";
// public final static String KEY_SHOW_SYSTEM_APPS = "show_system_apps";
// public final static String KEY_SHOW_LAUNCHER_ICON = "show_launcher_icon";
//
// // Xposed Mod Pref
// public final static String KEY_MODE = "mode";
// public final static String VALUE_MODE_AUTO = "auto";
// public final static String VALUE_MODE_BLACKLIST = "blacklist";
// public final static String VALUE_MODE_WHITELIST = "whitelist";
//
// // Fragment Name
// public final static String FRG_MAIN = "main_fragment";
//
// // MinMinProvider
// public final static String KEY_PKG_NAME = "PKG_NAME";
// public final static String KEY_NETWORK = "AD_NETWORKS";
// public final static String KEY_BLOCK_NUM = "BLOCK_NUM";
//
// private Common() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static String getModeString(MainFragment.FragmentMode mode)
// {
// switch (mode)
// {
// case AUTO:
// return Common.VALUE_MODE_AUTO;
// case BLACKLIST:
// return Common.VALUE_MODE_BLACKLIST;
// case WHITELIST:
// return Common.VALUE_MODE_WHITELIST;
// default:
// break;
// }
// return Common.VALUE_MODE_BLACKLIST;
// }
//
// public static String getWhiteListKey(String pkgName)
// {
// return pkgName + "_whitelist";
// }
// }
//
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/orm/AppData.java
// public class AppData
// {
//
// private String pkgName;
// private String adNetworks;
// private Integer blockNum;
//
// public AppData()
// {
// }
//
// public AppData(String pkgName)
// {
// this.pkgName = pkgName;
// }
//
// public AppData(String pkgName, String adNetworks, Integer blockNum)
// {
// this.pkgName = pkgName;
// this.adNetworks = adNetworks;
// this.blockNum = blockNum;
// }
//
// public String getPkgName()
// {
// return pkgName;
// }
//
// public void setPkgName(String pkgName)
// {
// this.pkgName = pkgName;
// }
//
// public String getAdNetworks()
// {
// return adNetworks;
// }
//
// public void setAdNetworks(String adNetworks)
// {
// this.adNetworks = adNetworks;
// }
//
// public Integer getBlockNum()
// {
// return blockNum;
// }
//
// public void setBlockNum(Integer blockNum)
// {
// this.blockNum = blockNum;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import tw.fatminmin.xposed.minminguard.Common;
import tw.fatminmin.xposed.minminguard.R;
import tw.fatminmin.xposed.minminguard.orm.AppData; | package tw.fatminmin.xposed.minminguard.ui.dialog;
/**
* Created by fatminmin on 2015/10/25.
*/
public class AppDetailDialogFragment extends DialogFragment
{
private ImageView imgAppIcon;
private TextView txtAppName;
private TextView txtPkgName;
private TextView txtAdNetworks;
private TextView txtAdsBlocked;
private Switch swtUrlFilter;
private String appName;
private String pkgName;
private String adNetworks;
private Integer blockNum;
private SharedPreferences mPref;
| // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/Common.java
// public class Common
// {
// public final static String PACKAGE_NAME = BuildConfig.APPLICATION_ID;
//
// public final static String MOD_PREFS = "ModSettings";
// public final static String UI_PREFS = "UI_PREF";
//
// // UI Pref
// public final static String KEY_FIRST_TIME = "first_time_2_0_alpha_7";
// public final static String KEY_SHOW_SYSTEM_APPS = "show_system_apps";
// public final static String KEY_SHOW_LAUNCHER_ICON = "show_launcher_icon";
//
// // Xposed Mod Pref
// public final static String KEY_MODE = "mode";
// public final static String VALUE_MODE_AUTO = "auto";
// public final static String VALUE_MODE_BLACKLIST = "blacklist";
// public final static String VALUE_MODE_WHITELIST = "whitelist";
//
// // Fragment Name
// public final static String FRG_MAIN = "main_fragment";
//
// // MinMinProvider
// public final static String KEY_PKG_NAME = "PKG_NAME";
// public final static String KEY_NETWORK = "AD_NETWORKS";
// public final static String KEY_BLOCK_NUM = "BLOCK_NUM";
//
// private Common() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static String getModeString(MainFragment.FragmentMode mode)
// {
// switch (mode)
// {
// case AUTO:
// return Common.VALUE_MODE_AUTO;
// case BLACKLIST:
// return Common.VALUE_MODE_BLACKLIST;
// case WHITELIST:
// return Common.VALUE_MODE_WHITELIST;
// default:
// break;
// }
// return Common.VALUE_MODE_BLACKLIST;
// }
//
// public static String getWhiteListKey(String pkgName)
// {
// return pkgName + "_whitelist";
// }
// }
//
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/orm/AppData.java
// public class AppData
// {
//
// private String pkgName;
// private String adNetworks;
// private Integer blockNum;
//
// public AppData()
// {
// }
//
// public AppData(String pkgName)
// {
// this.pkgName = pkgName;
// }
//
// public AppData(String pkgName, String adNetworks, Integer blockNum)
// {
// this.pkgName = pkgName;
// this.adNetworks = adNetworks;
// this.blockNum = blockNum;
// }
//
// public String getPkgName()
// {
// return pkgName;
// }
//
// public void setPkgName(String pkgName)
// {
// this.pkgName = pkgName;
// }
//
// public String getAdNetworks()
// {
// return adNetworks;
// }
//
// public void setAdNetworks(String adNetworks)
// {
// this.adNetworks = adNetworks;
// }
//
// public Integer getBlockNum()
// {
// return blockNum;
// }
//
// public void setBlockNum(Integer blockNum)
// {
// this.blockNum = blockNum;
// }
// }
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/ui/dialog/AppDetailDialogFragment.java
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import tw.fatminmin.xposed.minminguard.Common;
import tw.fatminmin.xposed.minminguard.R;
import tw.fatminmin.xposed.minminguard.orm.AppData;
package tw.fatminmin.xposed.minminguard.ui.dialog;
/**
* Created by fatminmin on 2015/10/25.
*/
public class AppDetailDialogFragment extends DialogFragment
{
private ImageView imgAppIcon;
private TextView txtAppName;
private TextView txtPkgName;
private TextView txtAdNetworks;
private TextView txtAdsBlocked;
private Switch swtUrlFilter;
private String appName;
private String pkgName;
private String adNetworks;
private Integer blockNum;
private SharedPreferences mPref;
| public static AppDetailDialogFragment newInstance(String appName, String pkgName, AppData appData) |
chiehmin/MinMinGuard | app/src/main/java/tw/fatminmin/xposed/minminguard/ui/dialog/AppDetailDialogFragment.java | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/Common.java
// public class Common
// {
// public final static String PACKAGE_NAME = BuildConfig.APPLICATION_ID;
//
// public final static String MOD_PREFS = "ModSettings";
// public final static String UI_PREFS = "UI_PREF";
//
// // UI Pref
// public final static String KEY_FIRST_TIME = "first_time_2_0_alpha_7";
// public final static String KEY_SHOW_SYSTEM_APPS = "show_system_apps";
// public final static String KEY_SHOW_LAUNCHER_ICON = "show_launcher_icon";
//
// // Xposed Mod Pref
// public final static String KEY_MODE = "mode";
// public final static String VALUE_MODE_AUTO = "auto";
// public final static String VALUE_MODE_BLACKLIST = "blacklist";
// public final static String VALUE_MODE_WHITELIST = "whitelist";
//
// // Fragment Name
// public final static String FRG_MAIN = "main_fragment";
//
// // MinMinProvider
// public final static String KEY_PKG_NAME = "PKG_NAME";
// public final static String KEY_NETWORK = "AD_NETWORKS";
// public final static String KEY_BLOCK_NUM = "BLOCK_NUM";
//
// private Common() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static String getModeString(MainFragment.FragmentMode mode)
// {
// switch (mode)
// {
// case AUTO:
// return Common.VALUE_MODE_AUTO;
// case BLACKLIST:
// return Common.VALUE_MODE_BLACKLIST;
// case WHITELIST:
// return Common.VALUE_MODE_WHITELIST;
// default:
// break;
// }
// return Common.VALUE_MODE_BLACKLIST;
// }
//
// public static String getWhiteListKey(String pkgName)
// {
// return pkgName + "_whitelist";
// }
// }
//
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/orm/AppData.java
// public class AppData
// {
//
// private String pkgName;
// private String adNetworks;
// private Integer blockNum;
//
// public AppData()
// {
// }
//
// public AppData(String pkgName)
// {
// this.pkgName = pkgName;
// }
//
// public AppData(String pkgName, String adNetworks, Integer blockNum)
// {
// this.pkgName = pkgName;
// this.adNetworks = adNetworks;
// this.blockNum = blockNum;
// }
//
// public String getPkgName()
// {
// return pkgName;
// }
//
// public void setPkgName(String pkgName)
// {
// this.pkgName = pkgName;
// }
//
// public String getAdNetworks()
// {
// return adNetworks;
// }
//
// public void setAdNetworks(String adNetworks)
// {
// this.adNetworks = adNetworks;
// }
//
// public Integer getBlockNum()
// {
// return blockNum;
// }
//
// public void setBlockNum(Integer blockNum)
// {
// this.blockNum = blockNum;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import tw.fatminmin.xposed.minminguard.Common;
import tw.fatminmin.xposed.minminguard.R;
import tw.fatminmin.xposed.minminguard.orm.AppData; | {
Bundle args = new Bundle();
args.putString("appName", appName);
args.putString("pkgName", pkgName);
if (appData != null)
{
args.putString("adNetworks", appData.getAdNetworks());
args.putInt("blockNum", appData.getBlockNum());
}
AppDetailDialogFragment fragment = new AppDetailDialogFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle args = getArguments();
appName = args.getString("appName");
pkgName = args.getString("pkgName");
adNetworks = args.getString("adNetworks");
blockNum = args.getInt("blockNum");
Context ctx = ContextCompat.createDeviceProtectedStorageContext(getActivity());
if (ctx == null) ctx = getActivity();
| // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/Common.java
// public class Common
// {
// public final static String PACKAGE_NAME = BuildConfig.APPLICATION_ID;
//
// public final static String MOD_PREFS = "ModSettings";
// public final static String UI_PREFS = "UI_PREF";
//
// // UI Pref
// public final static String KEY_FIRST_TIME = "first_time_2_0_alpha_7";
// public final static String KEY_SHOW_SYSTEM_APPS = "show_system_apps";
// public final static String KEY_SHOW_LAUNCHER_ICON = "show_launcher_icon";
//
// // Xposed Mod Pref
// public final static String KEY_MODE = "mode";
// public final static String VALUE_MODE_AUTO = "auto";
// public final static String VALUE_MODE_BLACKLIST = "blacklist";
// public final static String VALUE_MODE_WHITELIST = "whitelist";
//
// // Fragment Name
// public final static String FRG_MAIN = "main_fragment";
//
// // MinMinProvider
// public final static String KEY_PKG_NAME = "PKG_NAME";
// public final static String KEY_NETWORK = "AD_NETWORKS";
// public final static String KEY_BLOCK_NUM = "BLOCK_NUM";
//
// private Common() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static String getModeString(MainFragment.FragmentMode mode)
// {
// switch (mode)
// {
// case AUTO:
// return Common.VALUE_MODE_AUTO;
// case BLACKLIST:
// return Common.VALUE_MODE_BLACKLIST;
// case WHITELIST:
// return Common.VALUE_MODE_WHITELIST;
// default:
// break;
// }
// return Common.VALUE_MODE_BLACKLIST;
// }
//
// public static String getWhiteListKey(String pkgName)
// {
// return pkgName + "_whitelist";
// }
// }
//
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/orm/AppData.java
// public class AppData
// {
//
// private String pkgName;
// private String adNetworks;
// private Integer blockNum;
//
// public AppData()
// {
// }
//
// public AppData(String pkgName)
// {
// this.pkgName = pkgName;
// }
//
// public AppData(String pkgName, String adNetworks, Integer blockNum)
// {
// this.pkgName = pkgName;
// this.adNetworks = adNetworks;
// this.blockNum = blockNum;
// }
//
// public String getPkgName()
// {
// return pkgName;
// }
//
// public void setPkgName(String pkgName)
// {
// this.pkgName = pkgName;
// }
//
// public String getAdNetworks()
// {
// return adNetworks;
// }
//
// public void setAdNetworks(String adNetworks)
// {
// this.adNetworks = adNetworks;
// }
//
// public Integer getBlockNum()
// {
// return blockNum;
// }
//
// public void setBlockNum(Integer blockNum)
// {
// this.blockNum = blockNum;
// }
// }
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/ui/dialog/AppDetailDialogFragment.java
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import tw.fatminmin.xposed.minminguard.Common;
import tw.fatminmin.xposed.minminguard.R;
import tw.fatminmin.xposed.minminguard.orm.AppData;
{
Bundle args = new Bundle();
args.putString("appName", appName);
args.putString("pkgName", pkgName);
if (appData != null)
{
args.putString("adNetworks", appData.getAdNetworks());
args.putInt("blockNum", appData.getBlockNum());
}
AppDetailDialogFragment fragment = new AppDetailDialogFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle args = getArguments();
appName = args.getString("appName");
pkgName = args.getString("pkgName");
adNetworks = args.getString("adNetworks");
blockNum = args.getInt("blockNum");
Context ctx = ContextCompat.createDeviceProtectedStorageContext(getActivity());
if (ctx == null) ctx = getActivity();
| mPref = ctx.getSharedPreferences(Common.MOD_PREFS, Context.MODE_PRIVATE); |
chiehmin/MinMinGuard | app/src/main/java/tw/fatminmin/xposed/minminguard/ui/models/AppDetails.java | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/ui/image/GlideModule.java
// @com.bumptech.glide.annotation.GlideModule
// public class GlideModule extends AppGlideModule {
//
// @Override
// public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
// registry.prepend(ApplicationInfo.class, Drawable.class, new DrawableModelLoaderFactory(context));
// }
//
// public static void loadApplicationIcon(Context context, ApplicationInfo applicationInfo, ImageView view) {
// GlideApp.with(context)
// .load(applicationInfo)
// .into(view);
// }
// }
| import android.content.pm.ApplicationInfo;
import android.widget.ImageView;
import tw.fatminmin.xposed.minminguard.ui.image.GlideModule; | package tw.fatminmin.xposed.minminguard.ui.models;
public class AppDetails
{
private String name;
private String packageName;
private ApplicationInfo applicationInfo;
private boolean isEnabled;
public AppDetails(String name, String packageName, ApplicationInfo applicationInfo, boolean isEnabled)
{
this.name = name;
this.applicationInfo = applicationInfo;
this.packageName = packageName;
this.isEnabled = isEnabled;
}
public String getName()
{
return name;
}
public String getPackageName()
{
return packageName;
}
public void loadIcon(ImageView imageView) { | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/ui/image/GlideModule.java
// @com.bumptech.glide.annotation.GlideModule
// public class GlideModule extends AppGlideModule {
//
// @Override
// public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
// registry.prepend(ApplicationInfo.class, Drawable.class, new DrawableModelLoaderFactory(context));
// }
//
// public static void loadApplicationIcon(Context context, ApplicationInfo applicationInfo, ImageView view) {
// GlideApp.with(context)
// .load(applicationInfo)
// .into(view);
// }
// }
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/ui/models/AppDetails.java
import android.content.pm.ApplicationInfo;
import android.widget.ImageView;
import tw.fatminmin.xposed.minminguard.ui.image.GlideModule;
package tw.fatminmin.xposed.minminguard.ui.models;
public class AppDetails
{
private String name;
private String packageName;
private ApplicationInfo applicationInfo;
private boolean isEnabled;
public AppDetails(String name, String packageName, ApplicationInfo applicationInfo, boolean isEnabled)
{
this.name = name;
this.applicationInfo = applicationInfo;
this.packageName = packageName;
this.isEnabled = isEnabled;
}
public String getName()
{
return name;
}
public String getPackageName()
{
return packageName;
}
public void loadIcon(ImageView imageView) { | GlideModule.loadApplicationIcon(imageView.getContext(), applicationInfo, imageView); |
chiehmin/MinMinGuard | app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/custom_mod/Train.java | // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Util.java
// public final class Util
// {
// // change it to false for release build
// public static boolean DEBUG = BuildConfig.DEBUG;
//
// public static ExecutorService notifyWorker;
//
// public static final String TAG = "MinMinGuard";
// private static final String PACKAGE = "tw.fatminmin.xposed.minminguard";
//
// private Util() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static Boolean xposedEnabled()
// {
// return false;
// }
//
// public static String getAppVersion(Context context)
// {
// String version = null;
// PackageManager pm = context.getPackageManager();
//
// try
// {
// version = pm.getPackageInfo(PACKAGE, 0).versionName;
// }
// catch (PackageManager.NameNotFoundException e)
// {
// }
//
// return version;
// }
//
// public static void log(String packageName, String msg)
// {
// if (DEBUG)
// {
// //Log.d(TAG, packageName + ": " + msg);
// XposedBridge.log(packageName + ": " + msg);
// }
// }
//
// public static Application getCurrentApplication()
// {
// try
// {
// return AndroidAppHelper.currentApplication();
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// return null;
// }
//
// public static void saveLog(final File dest, final Context context, final Handler handler)
// {
// handler.post(new Runnable()
// {
//
// @Override
// public void run()
// {
// try
// {
//
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// });
// }
//
// public static void notifyAdNetwork(final Context context, final String pkgName, final String adNetwork)
// {
// new Thread(new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = context.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_NETWORK, adNetwork);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// }).start();
// }
//
// public static void notifyRemoveAdView(final Context context, final String pkgName, final int blockNum)
// {
// final Context mContext;
//
// if (context == null)
// mContext = getCurrentApplication();
// else
// mContext = context;
//
// Runnable task = new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = mContext.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_BLOCK_NUM, blockNum);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// };
//
// notifyWorker.submit(task);
// }
//
// public static void hookAllMethods(String className, ClassLoader classLoader, String method, XC_MethodHook callBack)
// {
// Class<?> clazz = XposedHelpers.findClass(className, classLoader);
//
// XposedBridge.hookAllMethods(clazz, method, callBack);
// }
// }
| import android.view.View;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
import de.robv.android.xposed.callbacks.XC_LayoutInflated;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import tw.fatminmin.xposed.minminguard.blocker.Util; | package tw.fatminmin.xposed.minminguard.blocker.custom_mod;
//TODO Fix formatting
final class Train
{
private static String pkg = "idv.nightgospel.TWRailScheduleLookUp";
private Train() throws InstantiationException
{
throw new InstantiationException("This class is not for instantiation");
}
public static void handleLoadPackage(LoadPackageParam lpparam)
{
if (!lpparam.packageName.equals(pkg))
{
return;
}
XposedHelpers.findAndHookMethod("com.waystorm.ads.WSAdBanner", lpparam.classLoader, "setWSAdListener", "com.waystorm.ads.WSAdListener", new XC_MethodHook()
{
@Override
protected void beforeHookedMethod(MethodHookParam param)
{
| // Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/Util.java
// public final class Util
// {
// // change it to false for release build
// public static boolean DEBUG = BuildConfig.DEBUG;
//
// public static ExecutorService notifyWorker;
//
// public static final String TAG = "MinMinGuard";
// private static final String PACKAGE = "tw.fatminmin.xposed.minminguard";
//
// private Util() throws InstantiationException
// {
// throw new InstantiationException("This class is not for instantiation");
// }
//
// public static Boolean xposedEnabled()
// {
// return false;
// }
//
// public static String getAppVersion(Context context)
// {
// String version = null;
// PackageManager pm = context.getPackageManager();
//
// try
// {
// version = pm.getPackageInfo(PACKAGE, 0).versionName;
// }
// catch (PackageManager.NameNotFoundException e)
// {
// }
//
// return version;
// }
//
// public static void log(String packageName, String msg)
// {
// if (DEBUG)
// {
// //Log.d(TAG, packageName + ": " + msg);
// XposedBridge.log(packageName + ": " + msg);
// }
// }
//
// public static Application getCurrentApplication()
// {
// try
// {
// return AndroidAppHelper.currentApplication();
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// return null;
// }
//
// public static void saveLog(final File dest, final Context context, final Handler handler)
// {
// handler.post(new Runnable()
// {
//
// @Override
// public void run()
// {
// try
// {
//
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// });
// }
//
// public static void notifyAdNetwork(final Context context, final String pkgName, final String adNetwork)
// {
// new Thread(new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = context.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_NETWORK, adNetwork);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// }).start();
// }
//
// public static void notifyRemoveAdView(final Context context, final String pkgName, final int blockNum)
// {
// final Context mContext;
//
// if (context == null)
// mContext = getCurrentApplication();
// else
// mContext = context;
//
// Runnable task = new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// ContentResolver resolver = mContext.getContentResolver();
// Uri uri = Uri.parse("content://tw.fatminmin.xposed.minminguard/");
// ContentValues values = new ContentValues();
//
// values.put(Common.KEY_PKG_NAME, pkgName);
// values.put(Common.KEY_BLOCK_NUM, blockNum);
// resolver.update(uri, values, null, null);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// }
// };
//
// notifyWorker.submit(task);
// }
//
// public static void hookAllMethods(String className, ClassLoader classLoader, String method, XC_MethodHook callBack)
// {
// Class<?> clazz = XposedHelpers.findClass(className, classLoader);
//
// XposedBridge.hookAllMethods(clazz, method, callBack);
// }
// }
// Path: app/src/main/java/tw/fatminmin/xposed/minminguard/blocker/custom_mod/Train.java
import android.view.View;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
import de.robv.android.xposed.callbacks.XC_LayoutInflated;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import tw.fatminmin.xposed.minminguard.blocker.Util;
package tw.fatminmin.xposed.minminguard.blocker.custom_mod;
//TODO Fix formatting
final class Train
{
private static String pkg = "idv.nightgospel.TWRailScheduleLookUp";
private Train() throws InstantiationException
{
throw new InstantiationException("This class is not for instantiation");
}
public static void handleLoadPackage(LoadPackageParam lpparam)
{
if (!lpparam.packageName.equals(pkg))
{
return;
}
XposedHelpers.findAndHookMethod("com.waystorm.ads.WSAdBanner", lpparam.classLoader, "setWSAdListener", "com.waystorm.ads.WSAdListener", new XC_MethodHook()
{
@Override
protected void beforeHookedMethod(MethodHookParam param)
{
| Util.log(pkg, "Prevent WSAdBanner setWSAdListener " + pkg); |
sladkoff/minecraft-prometheus-exporter | src/main/java/de/sldk/mc/config/PrometheusExporterConfig.java | // Path: src/main/java/de/sldk/mc/MetricRegistry.java
// public class MetricRegistry {
//
// private static final MetricRegistry INSTANCE = new MetricRegistry();
//
// private final List<Metric> metrics = new ArrayList<>();
//
// private MetricRegistry() {
//
// }
//
// public static MetricRegistry getInstance() {
// return INSTANCE;
// }
//
// public void register(Metric metric) {
// this.metrics.add(metric);
// }
//
// void collectMetrics() {
// this.metrics.forEach(Metric::collect);
// }
//
// }
//
// Path: src/main/java/de/sldk/mc/PrometheusExporter.java
// public class PrometheusExporter extends JavaPlugin {
//
// private final PrometheusExporterConfig config = new PrometheusExporterConfig(this);
// private MetricsServer server;
//
// @Override
// public void onEnable() {
//
// config.loadDefaultsAndSave();
//
// config.enableConfiguredMetrics();
//
// startMetricsServer();
// }
//
// private void startMetricsServer() {
// String host = config.get(PrometheusExporterConfig.HOST);
// Integer port = config.get(PrometheusExporterConfig.PORT);
//
// server = new MetricsServer(host, port, this);
//
// try {
// server.start();
// getLogger().info("Started Prometheus metrics endpoint at: " + host + ":" + port);
// } catch (Exception e) {
// getLogger().severe("Could not start embedded Jetty server");
// }
// }
//
// @Override
// public void onDisable() {
// try {
// server.stop();
// } catch (Exception e) {
// getLogger().log(Level.WARNING, "Failed to stop metrics server gracefully: " + e.getMessage());
// getLogger().log(Level.FINE, "Failed to stop metrics server gracefully", e);
// }
// }
//
// }
| import de.sldk.mc.MetricRegistry;
import de.sldk.mc.PrometheusExporter;
import de.sldk.mc.metrics.*;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.Plugin;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function; | package de.sldk.mc.config;
public class PrometheusExporterConfig {
public static final PluginConfig<String> HOST = new PluginConfig<>("host", "localhost");
public static final PluginConfig<Integer> PORT = new PluginConfig<>("port", 9225);
public static final List<MetricConfig> METRICS = Arrays.asList(
metricConfig("entities_total", true, Entities::new),
metricConfig("villagers_total", true, Villagers::new),
metricConfig("loaded_chunks_total", true, LoadedChunks::new),
metricConfig("jvm_memory", true, Memory::new),
metricConfig("players_online_total", true, PlayersOnlineTotal::new),
metricConfig("players_total", true, PlayersTotal::new),
metricConfig("tps", true, Tps::new),
metricConfig("jvm_threads", true, ThreadsWrapper::new),
metricConfig("jvm_gc", true, GarbageCollectorWrapper::new),
metricConfig("tick_duration_median", true, TickDurationMedianCollector::new),
metricConfig("tick_duration_average", true, TickDurationAverageCollector::new),
metricConfig("tick_duration_min", false, TickDurationMinCollector::new),
metricConfig("tick_duration_max", true, TickDurationMaxCollector::new),
metricConfig("player_online", false, PlayerOnline::new),
metricConfig("player_statistic", false, PlayerStatistics::new));
| // Path: src/main/java/de/sldk/mc/MetricRegistry.java
// public class MetricRegistry {
//
// private static final MetricRegistry INSTANCE = new MetricRegistry();
//
// private final List<Metric> metrics = new ArrayList<>();
//
// private MetricRegistry() {
//
// }
//
// public static MetricRegistry getInstance() {
// return INSTANCE;
// }
//
// public void register(Metric metric) {
// this.metrics.add(metric);
// }
//
// void collectMetrics() {
// this.metrics.forEach(Metric::collect);
// }
//
// }
//
// Path: src/main/java/de/sldk/mc/PrometheusExporter.java
// public class PrometheusExporter extends JavaPlugin {
//
// private final PrometheusExporterConfig config = new PrometheusExporterConfig(this);
// private MetricsServer server;
//
// @Override
// public void onEnable() {
//
// config.loadDefaultsAndSave();
//
// config.enableConfiguredMetrics();
//
// startMetricsServer();
// }
//
// private void startMetricsServer() {
// String host = config.get(PrometheusExporterConfig.HOST);
// Integer port = config.get(PrometheusExporterConfig.PORT);
//
// server = new MetricsServer(host, port, this);
//
// try {
// server.start();
// getLogger().info("Started Prometheus metrics endpoint at: " + host + ":" + port);
// } catch (Exception e) {
// getLogger().severe("Could not start embedded Jetty server");
// }
// }
//
// @Override
// public void onDisable() {
// try {
// server.stop();
// } catch (Exception e) {
// getLogger().log(Level.WARNING, "Failed to stop metrics server gracefully: " + e.getMessage());
// getLogger().log(Level.FINE, "Failed to stop metrics server gracefully", e);
// }
// }
//
// }
// Path: src/main/java/de/sldk/mc/config/PrometheusExporterConfig.java
import de.sldk.mc.MetricRegistry;
import de.sldk.mc.PrometheusExporter;
import de.sldk.mc.metrics.*;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.Plugin;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
package de.sldk.mc.config;
public class PrometheusExporterConfig {
public static final PluginConfig<String> HOST = new PluginConfig<>("host", "localhost");
public static final PluginConfig<Integer> PORT = new PluginConfig<>("port", 9225);
public static final List<MetricConfig> METRICS = Arrays.asList(
metricConfig("entities_total", true, Entities::new),
metricConfig("villagers_total", true, Villagers::new),
metricConfig("loaded_chunks_total", true, LoadedChunks::new),
metricConfig("jvm_memory", true, Memory::new),
metricConfig("players_online_total", true, PlayersOnlineTotal::new),
metricConfig("players_total", true, PlayersTotal::new),
metricConfig("tps", true, Tps::new),
metricConfig("jvm_threads", true, ThreadsWrapper::new),
metricConfig("jvm_gc", true, GarbageCollectorWrapper::new),
metricConfig("tick_duration_median", true, TickDurationMedianCollector::new),
metricConfig("tick_duration_average", true, TickDurationAverageCollector::new),
metricConfig("tick_duration_min", false, TickDurationMinCollector::new),
metricConfig("tick_duration_max", true, TickDurationMaxCollector::new),
metricConfig("player_online", false, PlayerOnline::new),
metricConfig("player_statistic", false, PlayerStatistics::new));
| private final PrometheusExporter prometheusExporter; |
sladkoff/minecraft-prometheus-exporter | src/main/java/de/sldk/mc/config/PrometheusExporterConfig.java | // Path: src/main/java/de/sldk/mc/MetricRegistry.java
// public class MetricRegistry {
//
// private static final MetricRegistry INSTANCE = new MetricRegistry();
//
// private final List<Metric> metrics = new ArrayList<>();
//
// private MetricRegistry() {
//
// }
//
// public static MetricRegistry getInstance() {
// return INSTANCE;
// }
//
// public void register(Metric metric) {
// this.metrics.add(metric);
// }
//
// void collectMetrics() {
// this.metrics.forEach(Metric::collect);
// }
//
// }
//
// Path: src/main/java/de/sldk/mc/PrometheusExporter.java
// public class PrometheusExporter extends JavaPlugin {
//
// private final PrometheusExporterConfig config = new PrometheusExporterConfig(this);
// private MetricsServer server;
//
// @Override
// public void onEnable() {
//
// config.loadDefaultsAndSave();
//
// config.enableConfiguredMetrics();
//
// startMetricsServer();
// }
//
// private void startMetricsServer() {
// String host = config.get(PrometheusExporterConfig.HOST);
// Integer port = config.get(PrometheusExporterConfig.PORT);
//
// server = new MetricsServer(host, port, this);
//
// try {
// server.start();
// getLogger().info("Started Prometheus metrics endpoint at: " + host + ":" + port);
// } catch (Exception e) {
// getLogger().severe("Could not start embedded Jetty server");
// }
// }
//
// @Override
// public void onDisable() {
// try {
// server.stop();
// } catch (Exception e) {
// getLogger().log(Level.WARNING, "Failed to stop metrics server gracefully: " + e.getMessage());
// getLogger().log(Level.FINE, "Failed to stop metrics server gracefully", e);
// }
// }
//
// }
| import de.sldk.mc.MetricRegistry;
import de.sldk.mc.PrometheusExporter;
import de.sldk.mc.metrics.*;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.Plugin;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function; | }
private static MetricConfig metricConfig(String key, boolean defaultValue, Function<Plugin, Metric> metricInitializer) {
return new MetricConfig(key, defaultValue, metricInitializer);
}
public void loadDefaultsAndSave() {
FileConfiguration configFile = prometheusExporter.getConfig();
PrometheusExporterConfig.HOST.setDefault(configFile);
PrometheusExporterConfig.PORT.setDefault(configFile);
PrometheusExporterConfig.METRICS.forEach(metric -> metric.setDefault(configFile));
configFile.options().copyDefaults(true);
prometheusExporter.saveConfig();
}
public void enableConfiguredMetrics() {
PrometheusExporterConfig.METRICS
.forEach(metricConfig -> {
Metric metric = metricConfig.getMetric(prometheusExporter);
Boolean enabled = get(metricConfig);
if (Boolean.TRUE.equals(enabled)) {
metric.enable();
}
prometheusExporter.getLogger().fine("Metric " + metric.getClass().getSimpleName() + " enabled: " + enabled);
| // Path: src/main/java/de/sldk/mc/MetricRegistry.java
// public class MetricRegistry {
//
// private static final MetricRegistry INSTANCE = new MetricRegistry();
//
// private final List<Metric> metrics = new ArrayList<>();
//
// private MetricRegistry() {
//
// }
//
// public static MetricRegistry getInstance() {
// return INSTANCE;
// }
//
// public void register(Metric metric) {
// this.metrics.add(metric);
// }
//
// void collectMetrics() {
// this.metrics.forEach(Metric::collect);
// }
//
// }
//
// Path: src/main/java/de/sldk/mc/PrometheusExporter.java
// public class PrometheusExporter extends JavaPlugin {
//
// private final PrometheusExporterConfig config = new PrometheusExporterConfig(this);
// private MetricsServer server;
//
// @Override
// public void onEnable() {
//
// config.loadDefaultsAndSave();
//
// config.enableConfiguredMetrics();
//
// startMetricsServer();
// }
//
// private void startMetricsServer() {
// String host = config.get(PrometheusExporterConfig.HOST);
// Integer port = config.get(PrometheusExporterConfig.PORT);
//
// server = new MetricsServer(host, port, this);
//
// try {
// server.start();
// getLogger().info("Started Prometheus metrics endpoint at: " + host + ":" + port);
// } catch (Exception e) {
// getLogger().severe("Could not start embedded Jetty server");
// }
// }
//
// @Override
// public void onDisable() {
// try {
// server.stop();
// } catch (Exception e) {
// getLogger().log(Level.WARNING, "Failed to stop metrics server gracefully: " + e.getMessage());
// getLogger().log(Level.FINE, "Failed to stop metrics server gracefully", e);
// }
// }
//
// }
// Path: src/main/java/de/sldk/mc/config/PrometheusExporterConfig.java
import de.sldk.mc.MetricRegistry;
import de.sldk.mc.PrometheusExporter;
import de.sldk.mc.metrics.*;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.Plugin;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
}
private static MetricConfig metricConfig(String key, boolean defaultValue, Function<Plugin, Metric> metricInitializer) {
return new MetricConfig(key, defaultValue, metricInitializer);
}
public void loadDefaultsAndSave() {
FileConfiguration configFile = prometheusExporter.getConfig();
PrometheusExporterConfig.HOST.setDefault(configFile);
PrometheusExporterConfig.PORT.setDefault(configFile);
PrometheusExporterConfig.METRICS.forEach(metric -> metric.setDefault(configFile));
configFile.options().copyDefaults(true);
prometheusExporter.saveConfig();
}
public void enableConfiguredMetrics() {
PrometheusExporterConfig.METRICS
.forEach(metricConfig -> {
Metric metric = metricConfig.getMetric(prometheusExporter);
Boolean enabled = get(metricConfig);
if (Boolean.TRUE.equals(enabled)) {
metric.enable();
}
prometheusExporter.getLogger().fine("Metric " + metric.getClass().getSimpleName() + " enabled: " + enabled);
| MetricRegistry.getInstance().register(metric); |
sladkoff/minecraft-prometheus-exporter | src/test/java/de/sldk/mc/metrics/PlayerStatisticLoaderFromFileTest.java | // Path: src/main/java/de/sldk/mc/metrics/player/PlayerStatisticLoaderFromFile.java
// public class PlayerStatisticLoaderFromFile implements PlayerStatisticLoader {
// public final String SERVER_PROPERTIES = "server.properties";
// public final String DEFAULT_WORLD = "world";
//
// private final Plugin plugin;
// private final Logger logger;
// private final Supplier<Map<UUID, Map<Enum<?>, Integer>>> statsFileLoader =
// Suppliers.memoize(this::readPlayerStatsFiles);
//
// private static final Map<String, Enum<?>> mapStatNameToStat = Arrays
// .stream(PlayerStatisticLoaderFromBukkit.STATISTICS)
// .collect(Collectors.toMap(e -> e.getKey().toString(), e -> e));
//
// public PlayerStatisticLoaderFromFile(Plugin plugin) {
// this.plugin = plugin;
// this.logger = plugin.getLogger();
// }
//
// @Override
// public Map<Enum<?>, Integer> getPlayerStatistics(OfflinePlayer offlinePlayer) {
//
// final UUID uuid = offlinePlayer.getUniqueId();
//
// final Map<UUID, Map<Enum<?>, Integer>> fileData = statsFileLoader.get();
//
// return fileData.getOrDefault(uuid, new HashMap<>());
// }
//
// /**
// * Reads all valid files in the <code>stats</code> folder and maps them to a
// * player.
// */
// private Map<UUID, Map<Enum<?>, Integer>> readPlayerStatsFiles() {
// try {
// File minecraftDataFolder = plugin.getServer().getWorldContainer().getCanonicalFile();
//
// Path statsFolder =
// Paths.get(minecraftDataFolder.getAbsolutePath(), getDefaultWorld(SERVER_PROPERTIES), "stats");
// if (!Files.exists(statsFolder)) {
// return new HashMap<>();
// }
//
// logger.fine("Reading player stats from folder " + statsFolder);
//
// try (Stream<Path> statFiles = Files.walk(statsFolder)) {
// return statFiles.filter(Files::isRegularFile)
// .filter(this::isFileNameUuid)
// .peek(path -> logger.fine("Found player stats file: " + path.getFileName().toString()))
// .collect(Collectors.toMap(this::fileNameToUuid, path -> {
// try {
// return getPlayersStats(path);
// } catch (Exception e) {
// String msg = String.format("Could not read player stats from JSON at '%s'", path);
// logger.log(Level.FINE, msg, e);
// return new HashMap<>();
// }
// }));
// }
// } catch (Exception e) {
// logger.log(Level.FINE, "Failed to read player stats from file. ", e);
// return new HashMap<>();
// }
// }
//
// public String getDefaultWorld(String fileName) {
// try (BufferedReader read = new BufferedReader(new FileReader(fileName))) {
// String line;
// String prefix = "level-name=";
// while ((line = read.readLine()) != null) {
// if (line.startsWith(prefix)) {
// return line.replace(prefix, "");
// }
// }
// } catch (IOException e) {
// logger.log(Level.FINE, "Failed to read level name from server properties file. ", e);
// }
//
// return DEFAULT_WORLD;
// }
//
// /**
// * Given a player's stats json file, map each stat to a value.
// */
// private Map<Enum<?>, Integer> getPlayersStats(Path path) throws IOException {
// DocumentContext ctx = JsonPath.parse(path.toFile());
// Map<String, Object> fileStats = ctx.read(JsonPath.compile("$.stats.minecraft:custom"));
// return fileStats.keySet().stream().filter(mapStatNameToStat::containsKey)
// .filter(e -> fileStats.get(e) instanceof Integer)
// .collect(Collectors.toMap(mapStatNameToStat::get, e -> (Integer) fileStats.get(e)));
// }
//
// private boolean isFileNameUuid(Path path) {
// try {
// fileNameToUuid(path);
// } catch (Exception e) {
// String msg = String.format("Could not extract valid player UUID from player stats file '%s'", path);
// logger.log(Level.FINE, msg, e);
// return false;
// }
// return true;
// }
//
// private UUID fileNameToUuid(Path path) {
// String uuidPart = path.getFileName().toString().split("\\.")[0];
// return UUID.fromString(uuidPart);
// }
// }
| import de.sldk.mc.metrics.player.PlayerStatisticLoaderFromFile;
import org.bukkit.plugin.Plugin;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.logging.Logger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | package de.sldk.mc.metrics;
public class PlayerStatisticLoaderFromFileTest {
private static Plugin plugin; | // Path: src/main/java/de/sldk/mc/metrics/player/PlayerStatisticLoaderFromFile.java
// public class PlayerStatisticLoaderFromFile implements PlayerStatisticLoader {
// public final String SERVER_PROPERTIES = "server.properties";
// public final String DEFAULT_WORLD = "world";
//
// private final Plugin plugin;
// private final Logger logger;
// private final Supplier<Map<UUID, Map<Enum<?>, Integer>>> statsFileLoader =
// Suppliers.memoize(this::readPlayerStatsFiles);
//
// private static final Map<String, Enum<?>> mapStatNameToStat = Arrays
// .stream(PlayerStatisticLoaderFromBukkit.STATISTICS)
// .collect(Collectors.toMap(e -> e.getKey().toString(), e -> e));
//
// public PlayerStatisticLoaderFromFile(Plugin plugin) {
// this.plugin = plugin;
// this.logger = plugin.getLogger();
// }
//
// @Override
// public Map<Enum<?>, Integer> getPlayerStatistics(OfflinePlayer offlinePlayer) {
//
// final UUID uuid = offlinePlayer.getUniqueId();
//
// final Map<UUID, Map<Enum<?>, Integer>> fileData = statsFileLoader.get();
//
// return fileData.getOrDefault(uuid, new HashMap<>());
// }
//
// /**
// * Reads all valid files in the <code>stats</code> folder and maps them to a
// * player.
// */
// private Map<UUID, Map<Enum<?>, Integer>> readPlayerStatsFiles() {
// try {
// File minecraftDataFolder = plugin.getServer().getWorldContainer().getCanonicalFile();
//
// Path statsFolder =
// Paths.get(minecraftDataFolder.getAbsolutePath(), getDefaultWorld(SERVER_PROPERTIES), "stats");
// if (!Files.exists(statsFolder)) {
// return new HashMap<>();
// }
//
// logger.fine("Reading player stats from folder " + statsFolder);
//
// try (Stream<Path> statFiles = Files.walk(statsFolder)) {
// return statFiles.filter(Files::isRegularFile)
// .filter(this::isFileNameUuid)
// .peek(path -> logger.fine("Found player stats file: " + path.getFileName().toString()))
// .collect(Collectors.toMap(this::fileNameToUuid, path -> {
// try {
// return getPlayersStats(path);
// } catch (Exception e) {
// String msg = String.format("Could not read player stats from JSON at '%s'", path);
// logger.log(Level.FINE, msg, e);
// return new HashMap<>();
// }
// }));
// }
// } catch (Exception e) {
// logger.log(Level.FINE, "Failed to read player stats from file. ", e);
// return new HashMap<>();
// }
// }
//
// public String getDefaultWorld(String fileName) {
// try (BufferedReader read = new BufferedReader(new FileReader(fileName))) {
// String line;
// String prefix = "level-name=";
// while ((line = read.readLine()) != null) {
// if (line.startsWith(prefix)) {
// return line.replace(prefix, "");
// }
// }
// } catch (IOException e) {
// logger.log(Level.FINE, "Failed to read level name from server properties file. ", e);
// }
//
// return DEFAULT_WORLD;
// }
//
// /**
// * Given a player's stats json file, map each stat to a value.
// */
// private Map<Enum<?>, Integer> getPlayersStats(Path path) throws IOException {
// DocumentContext ctx = JsonPath.parse(path.toFile());
// Map<String, Object> fileStats = ctx.read(JsonPath.compile("$.stats.minecraft:custom"));
// return fileStats.keySet().stream().filter(mapStatNameToStat::containsKey)
// .filter(e -> fileStats.get(e) instanceof Integer)
// .collect(Collectors.toMap(mapStatNameToStat::get, e -> (Integer) fileStats.get(e)));
// }
//
// private boolean isFileNameUuid(Path path) {
// try {
// fileNameToUuid(path);
// } catch (Exception e) {
// String msg = String.format("Could not extract valid player UUID from player stats file '%s'", path);
// logger.log(Level.FINE, msg, e);
// return false;
// }
// return true;
// }
//
// private UUID fileNameToUuid(Path path) {
// String uuidPart = path.getFileName().toString().split("\\.")[0];
// return UUID.fromString(uuidPart);
// }
// }
// Path: src/test/java/de/sldk/mc/metrics/PlayerStatisticLoaderFromFileTest.java
import de.sldk.mc.metrics.player.PlayerStatisticLoaderFromFile;
import org.bukkit.plugin.Plugin;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.logging.Logger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
package de.sldk.mc.metrics;
public class PlayerStatisticLoaderFromFileTest {
private static Plugin plugin; | private static PlayerStatisticLoaderFromFile playerStatisticLoader; |
sladkoff/minecraft-prometheus-exporter | src/test/java/de/sldk/mc/exporter/PrometheusExporterTest.java | // Path: src/main/java/de/sldk/mc/MetricsServer.java
// public class MetricsServer {
//
// private final String host;
// private final int port;
// private final PrometheusExporter prometheusExporter;
//
// private Server server;
//
// public MetricsServer(String host, int port, PrometheusExporter prometheusExporter) {
// this.host = host;
// this.port = port;
// this.prometheusExporter = prometheusExporter;
// }
//
// public void start() throws Exception {
// GzipHandler gzipHandler = new GzipHandler();
// gzipHandler.setHandler(new MetricsController(prometheusExporter));
//
// InetSocketAddress address = new InetSocketAddress(host, port);
// server = new Server(address);
// server.setHandler(gzipHandler);
//
// server.start();
// }
//
// public void stop() throws Exception {
// if (server == null) {
// return;
// }
//
// server.stop();
// }
// }
//
// Path: src/main/java/de/sldk/mc/PrometheusExporter.java
// public class PrometheusExporter extends JavaPlugin {
//
// private final PrometheusExporterConfig config = new PrometheusExporterConfig(this);
// private MetricsServer server;
//
// @Override
// public void onEnable() {
//
// config.loadDefaultsAndSave();
//
// config.enableConfiguredMetrics();
//
// startMetricsServer();
// }
//
// private void startMetricsServer() {
// String host = config.get(PrometheusExporterConfig.HOST);
// Integer port = config.get(PrometheusExporterConfig.PORT);
//
// server = new MetricsServer(host, port, this);
//
// try {
// server.start();
// getLogger().info("Started Prometheus metrics endpoint at: " + host + ":" + port);
// } catch (Exception e) {
// getLogger().severe("Could not start embedded Jetty server");
// }
// }
//
// @Override
// public void onDisable() {
// try {
// server.stop();
// } catch (Exception e) {
// getLogger().log(Level.WARNING, "Failed to stop metrics server gracefully: " + e.getMessage());
// getLogger().log(Level.FINE, "Failed to stop metrics server gracefully", e);
// }
// }
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import de.sldk.mc.MetricsServer;
import de.sldk.mc.PrometheusExporter;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.exporter.common.TextFormat;
import io.restassured.RestAssured;
import org.bukkit.Server;
import org.bukkit.scheduler.BukkitScheduler;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.util.URIUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.CompletableFuture; | package de.sldk.mc.exporter;
@ExtendWith(MockitoExtension.class)
public class PrometheusExporterTest {
@Mock | // Path: src/main/java/de/sldk/mc/MetricsServer.java
// public class MetricsServer {
//
// private final String host;
// private final int port;
// private final PrometheusExporter prometheusExporter;
//
// private Server server;
//
// public MetricsServer(String host, int port, PrometheusExporter prometheusExporter) {
// this.host = host;
// this.port = port;
// this.prometheusExporter = prometheusExporter;
// }
//
// public void start() throws Exception {
// GzipHandler gzipHandler = new GzipHandler();
// gzipHandler.setHandler(new MetricsController(prometheusExporter));
//
// InetSocketAddress address = new InetSocketAddress(host, port);
// server = new Server(address);
// server.setHandler(gzipHandler);
//
// server.start();
// }
//
// public void stop() throws Exception {
// if (server == null) {
// return;
// }
//
// server.stop();
// }
// }
//
// Path: src/main/java/de/sldk/mc/PrometheusExporter.java
// public class PrometheusExporter extends JavaPlugin {
//
// private final PrometheusExporterConfig config = new PrometheusExporterConfig(this);
// private MetricsServer server;
//
// @Override
// public void onEnable() {
//
// config.loadDefaultsAndSave();
//
// config.enableConfiguredMetrics();
//
// startMetricsServer();
// }
//
// private void startMetricsServer() {
// String host = config.get(PrometheusExporterConfig.HOST);
// Integer port = config.get(PrometheusExporterConfig.PORT);
//
// server = new MetricsServer(host, port, this);
//
// try {
// server.start();
// getLogger().info("Started Prometheus metrics endpoint at: " + host + ":" + port);
// } catch (Exception e) {
// getLogger().severe("Could not start embedded Jetty server");
// }
// }
//
// @Override
// public void onDisable() {
// try {
// server.stop();
// } catch (Exception e) {
// getLogger().log(Level.WARNING, "Failed to stop metrics server gracefully: " + e.getMessage());
// getLogger().log(Level.FINE, "Failed to stop metrics server gracefully", e);
// }
// }
//
// }
// Path: src/test/java/de/sldk/mc/exporter/PrometheusExporterTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import de.sldk.mc.MetricsServer;
import de.sldk.mc.PrometheusExporter;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.exporter.common.TextFormat;
import io.restassured.RestAssured;
import org.bukkit.Server;
import org.bukkit.scheduler.BukkitScheduler;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.util.URIUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.CompletableFuture;
package de.sldk.mc.exporter;
@ExtendWith(MockitoExtension.class)
public class PrometheusExporterTest {
@Mock | private PrometheusExporter exporterMock; |
sladkoff/minecraft-prometheus-exporter | src/test/java/de/sldk/mc/exporter/PrometheusExporterTest.java | // Path: src/main/java/de/sldk/mc/MetricsServer.java
// public class MetricsServer {
//
// private final String host;
// private final int port;
// private final PrometheusExporter prometheusExporter;
//
// private Server server;
//
// public MetricsServer(String host, int port, PrometheusExporter prometheusExporter) {
// this.host = host;
// this.port = port;
// this.prometheusExporter = prometheusExporter;
// }
//
// public void start() throws Exception {
// GzipHandler gzipHandler = new GzipHandler();
// gzipHandler.setHandler(new MetricsController(prometheusExporter));
//
// InetSocketAddress address = new InetSocketAddress(host, port);
// server = new Server(address);
// server.setHandler(gzipHandler);
//
// server.start();
// }
//
// public void stop() throws Exception {
// if (server == null) {
// return;
// }
//
// server.stop();
// }
// }
//
// Path: src/main/java/de/sldk/mc/PrometheusExporter.java
// public class PrometheusExporter extends JavaPlugin {
//
// private final PrometheusExporterConfig config = new PrometheusExporterConfig(this);
// private MetricsServer server;
//
// @Override
// public void onEnable() {
//
// config.loadDefaultsAndSave();
//
// config.enableConfiguredMetrics();
//
// startMetricsServer();
// }
//
// private void startMetricsServer() {
// String host = config.get(PrometheusExporterConfig.HOST);
// Integer port = config.get(PrometheusExporterConfig.PORT);
//
// server = new MetricsServer(host, port, this);
//
// try {
// server.start();
// getLogger().info("Started Prometheus metrics endpoint at: " + host + ":" + port);
// } catch (Exception e) {
// getLogger().severe("Could not start embedded Jetty server");
// }
// }
//
// @Override
// public void onDisable() {
// try {
// server.stop();
// } catch (Exception e) {
// getLogger().log(Level.WARNING, "Failed to stop metrics server gracefully: " + e.getMessage());
// getLogger().log(Level.FINE, "Failed to stop metrics server gracefully", e);
// }
// }
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import de.sldk.mc.MetricsServer;
import de.sldk.mc.PrometheusExporter;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.exporter.common.TextFormat;
import io.restassured.RestAssured;
import org.bukkit.Server;
import org.bukkit.scheduler.BukkitScheduler;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.util.URIUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.CompletableFuture; | package de.sldk.mc.exporter;
@ExtendWith(MockitoExtension.class)
public class PrometheusExporterTest {
@Mock
private PrometheusExporter exporterMock;
@Mock
private Server mockServer;
@Mock
private BukkitScheduler mockScheduler;
private int metricsServerPort; | // Path: src/main/java/de/sldk/mc/MetricsServer.java
// public class MetricsServer {
//
// private final String host;
// private final int port;
// private final PrometheusExporter prometheusExporter;
//
// private Server server;
//
// public MetricsServer(String host, int port, PrometheusExporter prometheusExporter) {
// this.host = host;
// this.port = port;
// this.prometheusExporter = prometheusExporter;
// }
//
// public void start() throws Exception {
// GzipHandler gzipHandler = new GzipHandler();
// gzipHandler.setHandler(new MetricsController(prometheusExporter));
//
// InetSocketAddress address = new InetSocketAddress(host, port);
// server = new Server(address);
// server.setHandler(gzipHandler);
//
// server.start();
// }
//
// public void stop() throws Exception {
// if (server == null) {
// return;
// }
//
// server.stop();
// }
// }
//
// Path: src/main/java/de/sldk/mc/PrometheusExporter.java
// public class PrometheusExporter extends JavaPlugin {
//
// private final PrometheusExporterConfig config = new PrometheusExporterConfig(this);
// private MetricsServer server;
//
// @Override
// public void onEnable() {
//
// config.loadDefaultsAndSave();
//
// config.enableConfiguredMetrics();
//
// startMetricsServer();
// }
//
// private void startMetricsServer() {
// String host = config.get(PrometheusExporterConfig.HOST);
// Integer port = config.get(PrometheusExporterConfig.PORT);
//
// server = new MetricsServer(host, port, this);
//
// try {
// server.start();
// getLogger().info("Started Prometheus metrics endpoint at: " + host + ":" + port);
// } catch (Exception e) {
// getLogger().severe("Could not start embedded Jetty server");
// }
// }
//
// @Override
// public void onDisable() {
// try {
// server.stop();
// } catch (Exception e) {
// getLogger().log(Level.WARNING, "Failed to stop metrics server gracefully: " + e.getMessage());
// getLogger().log(Level.FINE, "Failed to stop metrics server gracefully", e);
// }
// }
//
// }
// Path: src/test/java/de/sldk/mc/exporter/PrometheusExporterTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import de.sldk.mc.MetricsServer;
import de.sldk.mc.PrometheusExporter;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.exporter.common.TextFormat;
import io.restassured.RestAssured;
import org.bukkit.Server;
import org.bukkit.scheduler.BukkitScheduler;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.util.URIUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.CompletableFuture;
package de.sldk.mc.exporter;
@ExtendWith(MockitoExtension.class)
public class PrometheusExporterTest {
@Mock
private PrometheusExporter exporterMock;
@Mock
private Server mockServer;
@Mock
private BukkitScheduler mockScheduler;
private int metricsServerPort; | private MetricsServer metricsServer; |
sladkoff/minecraft-prometheus-exporter | src/main/java/de/sldk/mc/metrics/Tps.java | // Path: src/main/java/de/sldk/mc/tps/TpsCollector.java
// public class TpsCollector implements Runnable {
//
// /**
// * Max amount of ticks that should happen per second
// */
// static final int TICKS_PER_SECOND = 20;
// /**
// * Every 40 ticks (2s ideally) the server will be polled
// */
// public static final int POLL_INTERVAL = 40;
// /**
// * The amount of TPS values to keep for calculating the average
// */
// static final int TPS_QUEUE_SIZE = 10;
//
// final private Supplier<Long> systemTimeSupplier;
// private LinkedList<Float> tpsQueue = new LinkedList<>();
// private long lastPoll;
//
// public TpsCollector() {
// this(System::currentTimeMillis);
// }
//
// public TpsCollector(Supplier<Long> systemTimeSupplier) {
// this.systemTimeSupplier = systemTimeSupplier;
// this.lastPoll = systemTimeSupplier.get();
// }
//
// @Override
// public void run() {
// final long now = systemTimeSupplier.get();
// final long timeSpent = now - this.lastPoll;
//
// if (timeSpent <= 0) {
// // This would be caused by an invalid poll interval, skip it
// return;
// }
//
// final float tps = (POLL_INTERVAL / (float) timeSpent) * 1000;
// log(tps > TICKS_PER_SECOND ? TICKS_PER_SECOND : tps);
//
// this.lastPoll = now;
// }
//
// private void log(float tps) {
// tpsQueue.add(tps);
// if (tpsQueue.size() > TPS_QUEUE_SIZE) {
// tpsQueue.poll();
// }
// }
//
// public float getAverageTPS() {
// if (tpsQueue.isEmpty()) {
// return 20;
// }
//
// float sum = 0F;
// for (Float f : tpsQueue) {
// sum += f;
// }
// return sum / tpsQueue.size();
// }
// }
| import de.sldk.mc.tps.TpsCollector;
import io.prometheus.client.Gauge;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin; | package de.sldk.mc.metrics;
public class Tps extends Metric {
private static final Gauge TPS = Gauge.build()
.name(prefix("tps"))
.help("Server TPS (ticks per second)")
.create();
private int taskId;
| // Path: src/main/java/de/sldk/mc/tps/TpsCollector.java
// public class TpsCollector implements Runnable {
//
// /**
// * Max amount of ticks that should happen per second
// */
// static final int TICKS_PER_SECOND = 20;
// /**
// * Every 40 ticks (2s ideally) the server will be polled
// */
// public static final int POLL_INTERVAL = 40;
// /**
// * The amount of TPS values to keep for calculating the average
// */
// static final int TPS_QUEUE_SIZE = 10;
//
// final private Supplier<Long> systemTimeSupplier;
// private LinkedList<Float> tpsQueue = new LinkedList<>();
// private long lastPoll;
//
// public TpsCollector() {
// this(System::currentTimeMillis);
// }
//
// public TpsCollector(Supplier<Long> systemTimeSupplier) {
// this.systemTimeSupplier = systemTimeSupplier;
// this.lastPoll = systemTimeSupplier.get();
// }
//
// @Override
// public void run() {
// final long now = systemTimeSupplier.get();
// final long timeSpent = now - this.lastPoll;
//
// if (timeSpent <= 0) {
// // This would be caused by an invalid poll interval, skip it
// return;
// }
//
// final float tps = (POLL_INTERVAL / (float) timeSpent) * 1000;
// log(tps > TICKS_PER_SECOND ? TICKS_PER_SECOND : tps);
//
// this.lastPoll = now;
// }
//
// private void log(float tps) {
// tpsQueue.add(tps);
// if (tpsQueue.size() > TPS_QUEUE_SIZE) {
// tpsQueue.poll();
// }
// }
//
// public float getAverageTPS() {
// if (tpsQueue.isEmpty()) {
// return 20;
// }
//
// float sum = 0F;
// for (Float f : tpsQueue) {
// sum += f;
// }
// return sum / tpsQueue.size();
// }
// }
// Path: src/main/java/de/sldk/mc/metrics/Tps.java
import de.sldk.mc.tps.TpsCollector;
import io.prometheus.client.Gauge;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
package de.sldk.mc.metrics;
public class Tps extends Metric {
private static final Gauge TPS = Gauge.build()
.name(prefix("tps"))
.help("Server TPS (ticks per second)")
.create();
private int taskId;
| private TpsCollector tpsCollector = new TpsCollector(); |
sladkoff/minecraft-prometheus-exporter | src/main/java/de/sldk/mc/MetricRegistry.java | // Path: src/main/java/de/sldk/mc/metrics/Metric.java
// public abstract class Metric {
//
// private final static String COMMON_PREFIX = "mc_";
//
// private final Plugin plugin;
// private final Collector collector;
//
// private boolean enabled = false;
//
// protected Metric(Plugin plugin, Collector collector) {
// this.plugin = plugin;
// this.collector = collector;
// }
//
// protected Plugin getPlugin() {
// return plugin;
// }
//
// public void collect() {
//
// if (!enabled) {
// return;
// }
//
// try {
// doCollect();
// } catch (Exception e) {
// logException(e);
// }
// }
//
// protected abstract void doCollect();
//
// private void logException(Exception e) {
// final Logger log = plugin.getLogger();
// final String className = getClass().getSimpleName();
//
// log.warning(String.format("Failed to collect metric '%s' (see FINER log for stacktrace): %s",
// className, e.toString()));
// log.throwing(className, "collect", e);
// }
//
// protected static String prefix(String name) {
// return COMMON_PREFIX + name;
// }
//
// public void enable() {
// CollectorRegistry.defaultRegistry.register(collector);
// enabled = true;
// }
//
// public void disable() {
// CollectorRegistry.defaultRegistry.unregister(collector);
// enabled = false;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
// }
| import de.sldk.mc.metrics.Metric;
import java.util.ArrayList;
import java.util.List; | package de.sldk.mc;
public class MetricRegistry {
private static final MetricRegistry INSTANCE = new MetricRegistry();
| // Path: src/main/java/de/sldk/mc/metrics/Metric.java
// public abstract class Metric {
//
// private final static String COMMON_PREFIX = "mc_";
//
// private final Plugin plugin;
// private final Collector collector;
//
// private boolean enabled = false;
//
// protected Metric(Plugin plugin, Collector collector) {
// this.plugin = plugin;
// this.collector = collector;
// }
//
// protected Plugin getPlugin() {
// return plugin;
// }
//
// public void collect() {
//
// if (!enabled) {
// return;
// }
//
// try {
// doCollect();
// } catch (Exception e) {
// logException(e);
// }
// }
//
// protected abstract void doCollect();
//
// private void logException(Exception e) {
// final Logger log = plugin.getLogger();
// final String className = getClass().getSimpleName();
//
// log.warning(String.format("Failed to collect metric '%s' (see FINER log for stacktrace): %s",
// className, e.toString()));
// log.throwing(className, "collect", e);
// }
//
// protected static String prefix(String name) {
// return COMMON_PREFIX + name;
// }
//
// public void enable() {
// CollectorRegistry.defaultRegistry.register(collector);
// enabled = true;
// }
//
// public void disable() {
// CollectorRegistry.defaultRegistry.unregister(collector);
// enabled = false;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
// }
// Path: src/main/java/de/sldk/mc/MetricRegistry.java
import de.sldk.mc.metrics.Metric;
import java.util.ArrayList;
import java.util.List;
package de.sldk.mc;
public class MetricRegistry {
private static final MetricRegistry INSTANCE = new MetricRegistry();
| private final List<Metric> metrics = new ArrayList<>(); |
sladkoff/minecraft-prometheus-exporter | src/main/java/de/sldk/mc/config/MetricConfig.java | // Path: src/main/java/de/sldk/mc/metrics/Metric.java
// public abstract class Metric {
//
// private final static String COMMON_PREFIX = "mc_";
//
// private final Plugin plugin;
// private final Collector collector;
//
// private boolean enabled = false;
//
// protected Metric(Plugin plugin, Collector collector) {
// this.plugin = plugin;
// this.collector = collector;
// }
//
// protected Plugin getPlugin() {
// return plugin;
// }
//
// public void collect() {
//
// if (!enabled) {
// return;
// }
//
// try {
// doCollect();
// } catch (Exception e) {
// logException(e);
// }
// }
//
// protected abstract void doCollect();
//
// private void logException(Exception e) {
// final Logger log = plugin.getLogger();
// final String className = getClass().getSimpleName();
//
// log.warning(String.format("Failed to collect metric '%s' (see FINER log for stacktrace): %s",
// className, e.toString()));
// log.throwing(className, "collect", e);
// }
//
// protected static String prefix(String name) {
// return COMMON_PREFIX + name;
// }
//
// public void enable() {
// CollectorRegistry.defaultRegistry.register(collector);
// enabled = true;
// }
//
// public void disable() {
// CollectorRegistry.defaultRegistry.unregister(collector);
// enabled = false;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
// }
| import de.sldk.mc.metrics.Metric;
import org.bukkit.plugin.Plugin;
import java.util.function.Function; | package de.sldk.mc.config;
public class MetricConfig extends PluginConfig<Boolean> {
private static final String CONFIG_PATH_PREFIX = "enable_metrics";
| // Path: src/main/java/de/sldk/mc/metrics/Metric.java
// public abstract class Metric {
//
// private final static String COMMON_PREFIX = "mc_";
//
// private final Plugin plugin;
// private final Collector collector;
//
// private boolean enabled = false;
//
// protected Metric(Plugin plugin, Collector collector) {
// this.plugin = plugin;
// this.collector = collector;
// }
//
// protected Plugin getPlugin() {
// return plugin;
// }
//
// public void collect() {
//
// if (!enabled) {
// return;
// }
//
// try {
// doCollect();
// } catch (Exception e) {
// logException(e);
// }
// }
//
// protected abstract void doCollect();
//
// private void logException(Exception e) {
// final Logger log = plugin.getLogger();
// final String className = getClass().getSimpleName();
//
// log.warning(String.format("Failed to collect metric '%s' (see FINER log for stacktrace): %s",
// className, e.toString()));
// log.throwing(className, "collect", e);
// }
//
// protected static String prefix(String name) {
// return COMMON_PREFIX + name;
// }
//
// public void enable() {
// CollectorRegistry.defaultRegistry.register(collector);
// enabled = true;
// }
//
// public void disable() {
// CollectorRegistry.defaultRegistry.unregister(collector);
// enabled = false;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
// }
// Path: src/main/java/de/sldk/mc/config/MetricConfig.java
import de.sldk.mc.metrics.Metric;
import org.bukkit.plugin.Plugin;
import java.util.function.Function;
package de.sldk.mc.config;
public class MetricConfig extends PluginConfig<Boolean> {
private static final String CONFIG_PATH_PREFIX = "enable_metrics";
| private Function<Plugin, Metric> metricInitializer; |
binghuo365/csustRepo | trunk/src/com/yunstudio/struts/action/admin/asks/AsksAction.java | // Path: trunk/src/com/yunstudio/entity/RepMessage.java
// @SuppressWarnings("serial")
// public class RepMessage implements Serializable {
//
//
// private Integer id;
//
//
// private String title;
//
//
// private Date addtime;
//
//
// private String content;
//
//
// private Integer ispassed;
//
// private String notpassreason;
//
// private Integer isreplied;
//
//
// private Date passtime;
//
//
// private Date reptime;
//
//
// private String repcontent;
//
//
// private Integer sort;
//
//
// private RepUser repUser;
//
//
// private RepAdmin repAdmin;
//
// private String replyer;
//
// private String asker;
//
//
// public Integer getId() {
// return id;
// }
//
//
// public void setId(Integer id) {
// this.id = id;
// }
//
//
// public String getTitle() {
// return title;
// }
//
//
// public void setTitle(String title) {
// this.title = title;
// }
//
//
// public Date getAddtime() {
// return addtime;
// }
//
//
// public void setAddtime(Date addtime) {
// this.addtime = addtime;
// }
//
//
// public String getContent() {
// return content;
// }
//
//
// public void setContent(String content) {
// this.content = content;
// }
//
//
// public Integer getIspassed() {
// return ispassed;
// }
//
//
// public void setIspassed(Integer ispassed) {
// this.ispassed = ispassed;
// }
//
//
// public Integer getIsreplied() {
// return isreplied;
// }
//
//
// public void setIsreplied(Integer isreplied) {
// this.isreplied = isreplied;
// }
//
// public Date getPasstime() {
// return passtime;
// }
//
//
// public void setPasstime(Date passtime) {
// this.passtime = passtime;
// }
//
//
// public Date getReptime() {
// return reptime;
// }
//
//
// public void setReptime(Date reptime) {
// this.reptime = reptime;
// }
//
//
// public String getRepcontent() {
// return repcontent;
// }
//
//
// public void setRepcontent(String repcontent) {
// this.repcontent = repcontent;
// }
//
//
// public Integer getSort() {
// return sort;
// }
//
//
// public void setSort(Integer sort) {
// this.sort = sort;
// }
//
//
// public RepUser getRepUser() {
// return repUser;
// }
//
//
// public void setRepUser(RepUser repUser) {
// this.repUser = repUser;
// }
//
//
// public RepAdmin getRepAdmin() {
// return repAdmin;
// }
//
//
// public void setRepAdmin(RepAdmin repAdmin) {
// this.repAdmin = repAdmin;
// }
//
//
// public String getReplyer() {
// return replyer;
// }
//
//
// public void setReplyer(String replyer) {
// this.replyer = replyer;
// }
//
//
// public String getNotpassreason() {
// return notpassreason;
// }
//
//
// public void setNotpassreason(String notpassreason) {
// this.notpassreason = notpassreason;
// }
//
//
// public String getAsker() {
// return asker;
// }
//
//
// public void setAsker(String asker) {
// this.asker = asker;
// }
//
//
//
//
// }
//
// Path: trunk/src/com/yunstudio/service/MessageService.java
// public interface MessageService extends BaseService<RepMessage>{
//
// }
| import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.yunstudio.entity.Page;
import com.yunstudio.entity.RepAdmin;
import com.yunstudio.entity.RepMessage;
import com.yunstudio.service.AdminService;
import com.yunstudio.service.MessageService;
import com.yunstudio.service.UserService;
import com.yunstudio.struts.action.BaseAction; | package com.yunstudio.struts.action.admin.asks;
@SuppressWarnings("serial")
public class AsksAction extends BaseAction{
private UserService userService;
private AdminService adminService; | // Path: trunk/src/com/yunstudio/entity/RepMessage.java
// @SuppressWarnings("serial")
// public class RepMessage implements Serializable {
//
//
// private Integer id;
//
//
// private String title;
//
//
// private Date addtime;
//
//
// private String content;
//
//
// private Integer ispassed;
//
// private String notpassreason;
//
// private Integer isreplied;
//
//
// private Date passtime;
//
//
// private Date reptime;
//
//
// private String repcontent;
//
//
// private Integer sort;
//
//
// private RepUser repUser;
//
//
// private RepAdmin repAdmin;
//
// private String replyer;
//
// private String asker;
//
//
// public Integer getId() {
// return id;
// }
//
//
// public void setId(Integer id) {
// this.id = id;
// }
//
//
// public String getTitle() {
// return title;
// }
//
//
// public void setTitle(String title) {
// this.title = title;
// }
//
//
// public Date getAddtime() {
// return addtime;
// }
//
//
// public void setAddtime(Date addtime) {
// this.addtime = addtime;
// }
//
//
// public String getContent() {
// return content;
// }
//
//
// public void setContent(String content) {
// this.content = content;
// }
//
//
// public Integer getIspassed() {
// return ispassed;
// }
//
//
// public void setIspassed(Integer ispassed) {
// this.ispassed = ispassed;
// }
//
//
// public Integer getIsreplied() {
// return isreplied;
// }
//
//
// public void setIsreplied(Integer isreplied) {
// this.isreplied = isreplied;
// }
//
// public Date getPasstime() {
// return passtime;
// }
//
//
// public void setPasstime(Date passtime) {
// this.passtime = passtime;
// }
//
//
// public Date getReptime() {
// return reptime;
// }
//
//
// public void setReptime(Date reptime) {
// this.reptime = reptime;
// }
//
//
// public String getRepcontent() {
// return repcontent;
// }
//
//
// public void setRepcontent(String repcontent) {
// this.repcontent = repcontent;
// }
//
//
// public Integer getSort() {
// return sort;
// }
//
//
// public void setSort(Integer sort) {
// this.sort = sort;
// }
//
//
// public RepUser getRepUser() {
// return repUser;
// }
//
//
// public void setRepUser(RepUser repUser) {
// this.repUser = repUser;
// }
//
//
// public RepAdmin getRepAdmin() {
// return repAdmin;
// }
//
//
// public void setRepAdmin(RepAdmin repAdmin) {
// this.repAdmin = repAdmin;
// }
//
//
// public String getReplyer() {
// return replyer;
// }
//
//
// public void setReplyer(String replyer) {
// this.replyer = replyer;
// }
//
//
// public String getNotpassreason() {
// return notpassreason;
// }
//
//
// public void setNotpassreason(String notpassreason) {
// this.notpassreason = notpassreason;
// }
//
//
// public String getAsker() {
// return asker;
// }
//
//
// public void setAsker(String asker) {
// this.asker = asker;
// }
//
//
//
//
// }
//
// Path: trunk/src/com/yunstudio/service/MessageService.java
// public interface MessageService extends BaseService<RepMessage>{
//
// }
// Path: trunk/src/com/yunstudio/struts/action/admin/asks/AsksAction.java
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.yunstudio.entity.Page;
import com.yunstudio.entity.RepAdmin;
import com.yunstudio.entity.RepMessage;
import com.yunstudio.service.AdminService;
import com.yunstudio.service.MessageService;
import com.yunstudio.service.UserService;
import com.yunstudio.struts.action.BaseAction;
package com.yunstudio.struts.action.admin.asks;
@SuppressWarnings("serial")
public class AsksAction extends BaseAction{
private UserService userService;
private AdminService adminService; | private MessageService messageService; |
binghuo365/csustRepo | trunk/src/com/yunstudio/struts/action/admin/asks/AsksAction.java | // Path: trunk/src/com/yunstudio/entity/RepMessage.java
// @SuppressWarnings("serial")
// public class RepMessage implements Serializable {
//
//
// private Integer id;
//
//
// private String title;
//
//
// private Date addtime;
//
//
// private String content;
//
//
// private Integer ispassed;
//
// private String notpassreason;
//
// private Integer isreplied;
//
//
// private Date passtime;
//
//
// private Date reptime;
//
//
// private String repcontent;
//
//
// private Integer sort;
//
//
// private RepUser repUser;
//
//
// private RepAdmin repAdmin;
//
// private String replyer;
//
// private String asker;
//
//
// public Integer getId() {
// return id;
// }
//
//
// public void setId(Integer id) {
// this.id = id;
// }
//
//
// public String getTitle() {
// return title;
// }
//
//
// public void setTitle(String title) {
// this.title = title;
// }
//
//
// public Date getAddtime() {
// return addtime;
// }
//
//
// public void setAddtime(Date addtime) {
// this.addtime = addtime;
// }
//
//
// public String getContent() {
// return content;
// }
//
//
// public void setContent(String content) {
// this.content = content;
// }
//
//
// public Integer getIspassed() {
// return ispassed;
// }
//
//
// public void setIspassed(Integer ispassed) {
// this.ispassed = ispassed;
// }
//
//
// public Integer getIsreplied() {
// return isreplied;
// }
//
//
// public void setIsreplied(Integer isreplied) {
// this.isreplied = isreplied;
// }
//
// public Date getPasstime() {
// return passtime;
// }
//
//
// public void setPasstime(Date passtime) {
// this.passtime = passtime;
// }
//
//
// public Date getReptime() {
// return reptime;
// }
//
//
// public void setReptime(Date reptime) {
// this.reptime = reptime;
// }
//
//
// public String getRepcontent() {
// return repcontent;
// }
//
//
// public void setRepcontent(String repcontent) {
// this.repcontent = repcontent;
// }
//
//
// public Integer getSort() {
// return sort;
// }
//
//
// public void setSort(Integer sort) {
// this.sort = sort;
// }
//
//
// public RepUser getRepUser() {
// return repUser;
// }
//
//
// public void setRepUser(RepUser repUser) {
// this.repUser = repUser;
// }
//
//
// public RepAdmin getRepAdmin() {
// return repAdmin;
// }
//
//
// public void setRepAdmin(RepAdmin repAdmin) {
// this.repAdmin = repAdmin;
// }
//
//
// public String getReplyer() {
// return replyer;
// }
//
//
// public void setReplyer(String replyer) {
// this.replyer = replyer;
// }
//
//
// public String getNotpassreason() {
// return notpassreason;
// }
//
//
// public void setNotpassreason(String notpassreason) {
// this.notpassreason = notpassreason;
// }
//
//
// public String getAsker() {
// return asker;
// }
//
//
// public void setAsker(String asker) {
// this.asker = asker;
// }
//
//
//
//
// }
//
// Path: trunk/src/com/yunstudio/service/MessageService.java
// public interface MessageService extends BaseService<RepMessage>{
//
// }
| import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.yunstudio.entity.Page;
import com.yunstudio.entity.RepAdmin;
import com.yunstudio.entity.RepMessage;
import com.yunstudio.service.AdminService;
import com.yunstudio.service.MessageService;
import com.yunstudio.service.UserService;
import com.yunstudio.struts.action.BaseAction; | orders.remove(order);
orders.add(Order.asc("id"));
}else if (value.equals("addtime_desc")) {
orders.remove(order);
orders.add(Order.desc("addtime"));
}else if (value.equals("addtime_asc")) {
orders.remove(order);
orders.add(Order.asc("addtime"));
}
} else if (name.equals(Page.PAGESIZE)) {
pageSize = Integer.parseInt(value);
if (pageSize <= 0) {
pageSize = 20;
}
}
}
}
Page page = messageService.pageCQuery(pageNum, pageSize, criterions,orders, "id");
getContextMap().put("page", page);
getContextMap().put("params", getParameters());
return "list";
}
//添加留言
public String add(){
if(getRequest().getMethod().equals("GET")){
return "add";
}
Date now=new Date();
| // Path: trunk/src/com/yunstudio/entity/RepMessage.java
// @SuppressWarnings("serial")
// public class RepMessage implements Serializable {
//
//
// private Integer id;
//
//
// private String title;
//
//
// private Date addtime;
//
//
// private String content;
//
//
// private Integer ispassed;
//
// private String notpassreason;
//
// private Integer isreplied;
//
//
// private Date passtime;
//
//
// private Date reptime;
//
//
// private String repcontent;
//
//
// private Integer sort;
//
//
// private RepUser repUser;
//
//
// private RepAdmin repAdmin;
//
// private String replyer;
//
// private String asker;
//
//
// public Integer getId() {
// return id;
// }
//
//
// public void setId(Integer id) {
// this.id = id;
// }
//
//
// public String getTitle() {
// return title;
// }
//
//
// public void setTitle(String title) {
// this.title = title;
// }
//
//
// public Date getAddtime() {
// return addtime;
// }
//
//
// public void setAddtime(Date addtime) {
// this.addtime = addtime;
// }
//
//
// public String getContent() {
// return content;
// }
//
//
// public void setContent(String content) {
// this.content = content;
// }
//
//
// public Integer getIspassed() {
// return ispassed;
// }
//
//
// public void setIspassed(Integer ispassed) {
// this.ispassed = ispassed;
// }
//
//
// public Integer getIsreplied() {
// return isreplied;
// }
//
//
// public void setIsreplied(Integer isreplied) {
// this.isreplied = isreplied;
// }
//
// public Date getPasstime() {
// return passtime;
// }
//
//
// public void setPasstime(Date passtime) {
// this.passtime = passtime;
// }
//
//
// public Date getReptime() {
// return reptime;
// }
//
//
// public void setReptime(Date reptime) {
// this.reptime = reptime;
// }
//
//
// public String getRepcontent() {
// return repcontent;
// }
//
//
// public void setRepcontent(String repcontent) {
// this.repcontent = repcontent;
// }
//
//
// public Integer getSort() {
// return sort;
// }
//
//
// public void setSort(Integer sort) {
// this.sort = sort;
// }
//
//
// public RepUser getRepUser() {
// return repUser;
// }
//
//
// public void setRepUser(RepUser repUser) {
// this.repUser = repUser;
// }
//
//
// public RepAdmin getRepAdmin() {
// return repAdmin;
// }
//
//
// public void setRepAdmin(RepAdmin repAdmin) {
// this.repAdmin = repAdmin;
// }
//
//
// public String getReplyer() {
// return replyer;
// }
//
//
// public void setReplyer(String replyer) {
// this.replyer = replyer;
// }
//
//
// public String getNotpassreason() {
// return notpassreason;
// }
//
//
// public void setNotpassreason(String notpassreason) {
// this.notpassreason = notpassreason;
// }
//
//
// public String getAsker() {
// return asker;
// }
//
//
// public void setAsker(String asker) {
// this.asker = asker;
// }
//
//
//
//
// }
//
// Path: trunk/src/com/yunstudio/service/MessageService.java
// public interface MessageService extends BaseService<RepMessage>{
//
// }
// Path: trunk/src/com/yunstudio/struts/action/admin/asks/AsksAction.java
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.yunstudio.entity.Page;
import com.yunstudio.entity.RepAdmin;
import com.yunstudio.entity.RepMessage;
import com.yunstudio.service.AdminService;
import com.yunstudio.service.MessageService;
import com.yunstudio.service.UserService;
import com.yunstudio.struts.action.BaseAction;
orders.remove(order);
orders.add(Order.asc("id"));
}else if (value.equals("addtime_desc")) {
orders.remove(order);
orders.add(Order.desc("addtime"));
}else if (value.equals("addtime_asc")) {
orders.remove(order);
orders.add(Order.asc("addtime"));
}
} else if (name.equals(Page.PAGESIZE)) {
pageSize = Integer.parseInt(value);
if (pageSize <= 0) {
pageSize = 20;
}
}
}
}
Page page = messageService.pageCQuery(pageNum, pageSize, criterions,orders, "id");
getContextMap().put("page", page);
getContextMap().put("params", getParameters());
return "list";
}
//添加留言
public String add(){
if(getRequest().getMethod().equals("GET")){
return "add";
}
Date now=new Date();
| RepMessage message=new RepMessage(); |
binghuo365/csustRepo | trunk/src/com/yunstudio/entity/RepResource.java | // Path: trunk/src/com/yunstudio/utils/StringUtil.java
// public class StringUtil {
// public static boolean isNullOrEmpty(String s) {
// return s==null||s.isEmpty();
// }
// public static List<RepFormat> paramsFormatParseList(String formatStr) {
// List<RepFormat> list=new ArrayList<RepFormat>();
// if (isNullOrEmpty(formatStr)) {
// return list;
// }
// String[] formatItems=formatStr.split(",");
// if(formatItems==null){
// return list;
// }
// for (String formatItem : formatItems) {
// String[] str=formatItem.split(":");
//
// RepFormat format=new RepFormat();
// format.setName(str[0]);
// format.setSize(Integer.parseInt(str[1]));
//
// list.add(format);
// }
// return list;
// }
// /**
// * 对系统配置中支持的文件格式以及大小进行解码,
// *
// * @param formatStr
// * @return 输出为map格式,大小为long类型,单位仍为mb
// */
// public static Map<String,Long> paramsFormatParseMap(String formatStr) {
// Map<String, Long> formatItemMap=new HashMap<String, Long>();
// if (isNullOrEmpty(formatStr)) {
// return formatItemMap;
// }
// String[] formatItems=formatStr.split(",");
// if(formatItems==null){
// return formatItemMap;
// }
// for (String formatItem : formatItems) {
// String[] str=formatItem.split(":");
//
// formatItemMap.put(str[0], Long.parseLong(str[1]));
// }
// return formatItemMap;
// }
//
// /**
// * 从文件的路径提取出文件名称
// * @param encodefilepath
// * @return
// */
// public static String filepath2filename(String encodefilepath){
// int i1=encodefilepath.lastIndexOf("/");
// int i2=encodefilepath.lastIndexOf("\\");
// int i=i1>i2?i1:i2;
// return encodefilepath.substring(i+1, encodefilepath.lastIndexOf("_"));
// }
// public static String encodeFilename(String filename){
// String filenameExt=filename.substring(filename.lastIndexOf("."));
// StringBuilder sb=new StringBuilder(UUIDUtils.uuid().toString());
// sb.append(filenameExt.toLowerCase());
// return sb.toString();
// }
// }
| import java.io.File;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.struts2.ServletActionContext;
import com.yunstudio.utils.StringUtil; |
private Set<RepComment> repComments=new HashSet<RepComment>(0);
public RepResource(){}
public RepResource(String path,String translateurl) {
super();
this.path = path;
this.translateurl=translateurl;
}
public RepResource(String path,String title,String translateurl) {
super();
this.path = path;
this.title=title;
this.translateurl=translateurl;
}
public RepResource(Integer id, String title, Integer likenum,
Integer downloadnum, Integer ispassed, Date passtime,
String repUserName, String repAdminName, String repGscatalogName,
String repZycatalogName, String repTopicTitle, String uploader,
String translateurl,Integer commentSize,String realname) {
super();
this.id = id;
this.title = title;
this.likenum = likenum;
this.downloadnum = downloadnum;
this.ispassed = ispassed;
this.passtime = passtime; | // Path: trunk/src/com/yunstudio/utils/StringUtil.java
// public class StringUtil {
// public static boolean isNullOrEmpty(String s) {
// return s==null||s.isEmpty();
// }
// public static List<RepFormat> paramsFormatParseList(String formatStr) {
// List<RepFormat> list=new ArrayList<RepFormat>();
// if (isNullOrEmpty(formatStr)) {
// return list;
// }
// String[] formatItems=formatStr.split(",");
// if(formatItems==null){
// return list;
// }
// for (String formatItem : formatItems) {
// String[] str=formatItem.split(":");
//
// RepFormat format=new RepFormat();
// format.setName(str[0]);
// format.setSize(Integer.parseInt(str[1]));
//
// list.add(format);
// }
// return list;
// }
// /**
// * 对系统配置中支持的文件格式以及大小进行解码,
// *
// * @param formatStr
// * @return 输出为map格式,大小为long类型,单位仍为mb
// */
// public static Map<String,Long> paramsFormatParseMap(String formatStr) {
// Map<String, Long> formatItemMap=new HashMap<String, Long>();
// if (isNullOrEmpty(formatStr)) {
// return formatItemMap;
// }
// String[] formatItems=formatStr.split(",");
// if(formatItems==null){
// return formatItemMap;
// }
// for (String formatItem : formatItems) {
// String[] str=formatItem.split(":");
//
// formatItemMap.put(str[0], Long.parseLong(str[1]));
// }
// return formatItemMap;
// }
//
// /**
// * 从文件的路径提取出文件名称
// * @param encodefilepath
// * @return
// */
// public static String filepath2filename(String encodefilepath){
// int i1=encodefilepath.lastIndexOf("/");
// int i2=encodefilepath.lastIndexOf("\\");
// int i=i1>i2?i1:i2;
// return encodefilepath.substring(i+1, encodefilepath.lastIndexOf("_"));
// }
// public static String encodeFilename(String filename){
// String filenameExt=filename.substring(filename.lastIndexOf("."));
// StringBuilder sb=new StringBuilder(UUIDUtils.uuid().toString());
// sb.append(filenameExt.toLowerCase());
// return sb.toString();
// }
// }
// Path: trunk/src/com/yunstudio/entity/RepResource.java
import java.io.File;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.struts2.ServletActionContext;
import com.yunstudio.utils.StringUtil;
private Set<RepComment> repComments=new HashSet<RepComment>(0);
public RepResource(){}
public RepResource(String path,String translateurl) {
super();
this.path = path;
this.translateurl=translateurl;
}
public RepResource(String path,String title,String translateurl) {
super();
this.path = path;
this.title=title;
this.translateurl=translateurl;
}
public RepResource(Integer id, String title, Integer likenum,
Integer downloadnum, Integer ispassed, Date passtime,
String repUserName, String repAdminName, String repGscatalogName,
String repZycatalogName, String repTopicTitle, String uploader,
String translateurl,Integer commentSize,String realname) {
super();
this.id = id;
this.title = title;
this.likenum = likenum;
this.downloadnum = downloadnum;
this.ispassed = ispassed;
this.passtime = passtime; | if(!StringUtil.isNullOrEmpty(repUserName)){ |
binghuo365/csustRepo | trunk/src/com/yunstudio/struts/action/admin/catalog/GsCatalogAction.java | // Path: trunk/src/com/yunstudio/utils/StringUtil.java
// public class StringUtil {
// public static boolean isNullOrEmpty(String s) {
// return s==null||s.isEmpty();
// }
// public static List<RepFormat> paramsFormatParseList(String formatStr) {
// List<RepFormat> list=new ArrayList<RepFormat>();
// if (isNullOrEmpty(formatStr)) {
// return list;
// }
// String[] formatItems=formatStr.split(",");
// if(formatItems==null){
// return list;
// }
// for (String formatItem : formatItems) {
// String[] str=formatItem.split(":");
//
// RepFormat format=new RepFormat();
// format.setName(str[0]);
// format.setSize(Integer.parseInt(str[1]));
//
// list.add(format);
// }
// return list;
// }
// /**
// * 对系统配置中支持的文件格式以及大小进行解码,
// *
// * @param formatStr
// * @return 输出为map格式,大小为long类型,单位仍为mb
// */
// public static Map<String,Long> paramsFormatParseMap(String formatStr) {
// Map<String, Long> formatItemMap=new HashMap<String, Long>();
// if (isNullOrEmpty(formatStr)) {
// return formatItemMap;
// }
// String[] formatItems=formatStr.split(",");
// if(formatItems==null){
// return formatItemMap;
// }
// for (String formatItem : formatItems) {
// String[] str=formatItem.split(":");
//
// formatItemMap.put(str[0], Long.parseLong(str[1]));
// }
// return formatItemMap;
// }
//
// /**
// * 从文件的路径提取出文件名称
// * @param encodefilepath
// * @return
// */
// public static String filepath2filename(String encodefilepath){
// int i1=encodefilepath.lastIndexOf("/");
// int i2=encodefilepath.lastIndexOf("\\");
// int i=i1>i2?i1:i2;
// return encodefilepath.substring(i+1, encodefilepath.lastIndexOf("_"));
// }
// public static String encodeFilename(String filename){
// String filenameExt=filename.substring(filename.lastIndexOf("."));
// StringBuilder sb=new StringBuilder(UUIDUtils.uuid().toString());
// sb.append(filenameExt.toLowerCase());
// return sb.toString();
// }
// }
| import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.yunstudio.entity.Page;
import com.yunstudio.entity.RepGscatalog;
import com.yunstudio.service.GsCatalogService;
import com.yunstudio.struts.action.BaseAction;
import com.yunstudio.utils.StringUtil; | package com.yunstudio.struts.action.admin.catalog;
public class GsCatalogAction extends BaseAction{
@Resource(name="gsCatalogService")
private GsCatalogService gsCatalogService;
@SuppressWarnings("unchecked")
public String list() {
int pageNum=1;
int pageSize=20;
String name=getRequest().getParameter("name");
String fatheridStr=getRequest().getParameter("fatherid");
String queryOrderBy=getRequest().getParameter("queryOrderBy");
String pageSizeStr=getRequest().getParameter("pageSize");
String pageNumStr=getRequest().getParameter("pageNo");
Set<Criterion> criterions=new HashSet<Criterion>(2);
Set<Order> orders=new HashSet<Order>(1);
Order orderByIdDesc=Order.desc("id");
orders.add(orderByIdDesc);
| // Path: trunk/src/com/yunstudio/utils/StringUtil.java
// public class StringUtil {
// public static boolean isNullOrEmpty(String s) {
// return s==null||s.isEmpty();
// }
// public static List<RepFormat> paramsFormatParseList(String formatStr) {
// List<RepFormat> list=new ArrayList<RepFormat>();
// if (isNullOrEmpty(formatStr)) {
// return list;
// }
// String[] formatItems=formatStr.split(",");
// if(formatItems==null){
// return list;
// }
// for (String formatItem : formatItems) {
// String[] str=formatItem.split(":");
//
// RepFormat format=new RepFormat();
// format.setName(str[0]);
// format.setSize(Integer.parseInt(str[1]));
//
// list.add(format);
// }
// return list;
// }
// /**
// * 对系统配置中支持的文件格式以及大小进行解码,
// *
// * @param formatStr
// * @return 输出为map格式,大小为long类型,单位仍为mb
// */
// public static Map<String,Long> paramsFormatParseMap(String formatStr) {
// Map<String, Long> formatItemMap=new HashMap<String, Long>();
// if (isNullOrEmpty(formatStr)) {
// return formatItemMap;
// }
// String[] formatItems=formatStr.split(",");
// if(formatItems==null){
// return formatItemMap;
// }
// for (String formatItem : formatItems) {
// String[] str=formatItem.split(":");
//
// formatItemMap.put(str[0], Long.parseLong(str[1]));
// }
// return formatItemMap;
// }
//
// /**
// * 从文件的路径提取出文件名称
// * @param encodefilepath
// * @return
// */
// public static String filepath2filename(String encodefilepath){
// int i1=encodefilepath.lastIndexOf("/");
// int i2=encodefilepath.lastIndexOf("\\");
// int i=i1>i2?i1:i2;
// return encodefilepath.substring(i+1, encodefilepath.lastIndexOf("_"));
// }
// public static String encodeFilename(String filename){
// String filenameExt=filename.substring(filename.lastIndexOf("."));
// StringBuilder sb=new StringBuilder(UUIDUtils.uuid().toString());
// sb.append(filenameExt.toLowerCase());
// return sb.toString();
// }
// }
// Path: trunk/src/com/yunstudio/struts/action/admin/catalog/GsCatalogAction.java
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.yunstudio.entity.Page;
import com.yunstudio.entity.RepGscatalog;
import com.yunstudio.service.GsCatalogService;
import com.yunstudio.struts.action.BaseAction;
import com.yunstudio.utils.StringUtil;
package com.yunstudio.struts.action.admin.catalog;
public class GsCatalogAction extends BaseAction{
@Resource(name="gsCatalogService")
private GsCatalogService gsCatalogService;
@SuppressWarnings("unchecked")
public String list() {
int pageNum=1;
int pageSize=20;
String name=getRequest().getParameter("name");
String fatheridStr=getRequest().getParameter("fatherid");
String queryOrderBy=getRequest().getParameter("queryOrderBy");
String pageSizeStr=getRequest().getParameter("pageSize");
String pageNumStr=getRequest().getParameter("pageNo");
Set<Criterion> criterions=new HashSet<Criterion>(2);
Set<Order> orders=new HashSet<Order>(1);
Order orderByIdDesc=Order.desc("id");
orders.add(orderByIdDesc);
| if(!StringUtil.isNullOrEmpty(name)){ |
binghuo365/csustRepo | trunk/src/com/yunstudio/struts/action/admin/catalog/TagAction.java | // Path: trunk/src/com/yunstudio/utils/StringUtil.java
// public class StringUtil {
// public static boolean isNullOrEmpty(String s) {
// return s==null||s.isEmpty();
// }
// public static List<RepFormat> paramsFormatParseList(String formatStr) {
// List<RepFormat> list=new ArrayList<RepFormat>();
// if (isNullOrEmpty(formatStr)) {
// return list;
// }
// String[] formatItems=formatStr.split(",");
// if(formatItems==null){
// return list;
// }
// for (String formatItem : formatItems) {
// String[] str=formatItem.split(":");
//
// RepFormat format=new RepFormat();
// format.setName(str[0]);
// format.setSize(Integer.parseInt(str[1]));
//
// list.add(format);
// }
// return list;
// }
// /**
// * 对系统配置中支持的文件格式以及大小进行解码,
// *
// * @param formatStr
// * @return 输出为map格式,大小为long类型,单位仍为mb
// */
// public static Map<String,Long> paramsFormatParseMap(String formatStr) {
// Map<String, Long> formatItemMap=new HashMap<String, Long>();
// if (isNullOrEmpty(formatStr)) {
// return formatItemMap;
// }
// String[] formatItems=formatStr.split(",");
// if(formatItems==null){
// return formatItemMap;
// }
// for (String formatItem : formatItems) {
// String[] str=formatItem.split(":");
//
// formatItemMap.put(str[0], Long.parseLong(str[1]));
// }
// return formatItemMap;
// }
//
// /**
// * 从文件的路径提取出文件名称
// * @param encodefilepath
// * @return
// */
// public static String filepath2filename(String encodefilepath){
// int i1=encodefilepath.lastIndexOf("/");
// int i2=encodefilepath.lastIndexOf("\\");
// int i=i1>i2?i1:i2;
// return encodefilepath.substring(i+1, encodefilepath.lastIndexOf("_"));
// }
// public static String encodeFilename(String filename){
// String filenameExt=filename.substring(filename.lastIndexOf("."));
// StringBuilder sb=new StringBuilder(UUIDUtils.uuid().toString());
// sb.append(filenameExt.toLowerCase());
// return sb.toString();
// }
// }
| import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.yunstudio.entity.Page;
import com.yunstudio.entity.RepTag;
import com.yunstudio.service.GsCatalogService;
import com.yunstudio.service.TagService;
import com.yunstudio.struts.action.BaseAction;
import com.yunstudio.utils.StringUtil; | package com.yunstudio.struts.action.admin.catalog;
public class TagAction extends BaseAction{
@Resource(name="tagService")
private TagService tagService;
@SuppressWarnings("unchecked")
public String list() {
int pageNum=1;
int pageSize=20;
String name=getRequest().getParameter("name");
String queryOrderBy=getRequest().getParameter("queryOrderBy");
String pageSizeStr=getRequest().getParameter("pageSize");
String pageNumStr=getRequest().getParameter("pageNo");
Set<Criterion> criterions=new HashSet<Criterion>(2);
Set<Order> orders=new HashSet<Order>(1);
Order orderByIdDesc=Order.desc("id");
orders.add(orderByIdDesc);
| // Path: trunk/src/com/yunstudio/utils/StringUtil.java
// public class StringUtil {
// public static boolean isNullOrEmpty(String s) {
// return s==null||s.isEmpty();
// }
// public static List<RepFormat> paramsFormatParseList(String formatStr) {
// List<RepFormat> list=new ArrayList<RepFormat>();
// if (isNullOrEmpty(formatStr)) {
// return list;
// }
// String[] formatItems=formatStr.split(",");
// if(formatItems==null){
// return list;
// }
// for (String formatItem : formatItems) {
// String[] str=formatItem.split(":");
//
// RepFormat format=new RepFormat();
// format.setName(str[0]);
// format.setSize(Integer.parseInt(str[1]));
//
// list.add(format);
// }
// return list;
// }
// /**
// * 对系统配置中支持的文件格式以及大小进行解码,
// *
// * @param formatStr
// * @return 输出为map格式,大小为long类型,单位仍为mb
// */
// public static Map<String,Long> paramsFormatParseMap(String formatStr) {
// Map<String, Long> formatItemMap=new HashMap<String, Long>();
// if (isNullOrEmpty(formatStr)) {
// return formatItemMap;
// }
// String[] formatItems=formatStr.split(",");
// if(formatItems==null){
// return formatItemMap;
// }
// for (String formatItem : formatItems) {
// String[] str=formatItem.split(":");
//
// formatItemMap.put(str[0], Long.parseLong(str[1]));
// }
// return formatItemMap;
// }
//
// /**
// * 从文件的路径提取出文件名称
// * @param encodefilepath
// * @return
// */
// public static String filepath2filename(String encodefilepath){
// int i1=encodefilepath.lastIndexOf("/");
// int i2=encodefilepath.lastIndexOf("\\");
// int i=i1>i2?i1:i2;
// return encodefilepath.substring(i+1, encodefilepath.lastIndexOf("_"));
// }
// public static String encodeFilename(String filename){
// String filenameExt=filename.substring(filename.lastIndexOf("."));
// StringBuilder sb=new StringBuilder(UUIDUtils.uuid().toString());
// sb.append(filenameExt.toLowerCase());
// return sb.toString();
// }
// }
// Path: trunk/src/com/yunstudio/struts/action/admin/catalog/TagAction.java
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.yunstudio.entity.Page;
import com.yunstudio.entity.RepTag;
import com.yunstudio.service.GsCatalogService;
import com.yunstudio.service.TagService;
import com.yunstudio.struts.action.BaseAction;
import com.yunstudio.utils.StringUtil;
package com.yunstudio.struts.action.admin.catalog;
public class TagAction extends BaseAction{
@Resource(name="tagService")
private TagService tagService;
@SuppressWarnings("unchecked")
public String list() {
int pageNum=1;
int pageSize=20;
String name=getRequest().getParameter("name");
String queryOrderBy=getRequest().getParameter("queryOrderBy");
String pageSizeStr=getRequest().getParameter("pageSize");
String pageNumStr=getRequest().getParameter("pageNo");
Set<Criterion> criterions=new HashSet<Criterion>(2);
Set<Order> orders=new HashSet<Order>(1);
Order orderByIdDesc=Order.desc("id");
orders.add(orderByIdDesc);
| if(!StringUtil.isNullOrEmpty(name)){ |
Coreoz/Plume | plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydsl.java | // Path: plume-db/src/main/java/com/coreoz/plume/db/crud/CrudDao.java
// public interface CrudDao<T> {
//
// List<T> findAll();
//
// T findById(Long id);
//
// T save(T entityToUpdate);
//
// long delete(Long id);
//
// }
//
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydsl.java
// @Singleton
// public class TransactionManagerQuerydsl extends TransactionManager {
//
// private final Configuration querydslConfiguration;
//
// @Inject
// public TransactionManagerQuerydsl(Config config) {
// this(config, "db");
// }
//
// public TransactionManagerQuerydsl(Config config, String prefix) {
// super(config, prefix);
//
// String dialect = config.getString(prefix + ".dialect");
// this.querydslConfiguration = new Configuration(QuerydslTemplates.valueOf(dialect).sqlTemplates());
// }
//
// public TransactionManagerQuerydsl(DataSource dataSource, Configuration querydslConfiguration) {
// super(dataSource);
//
// this.querydslConfiguration = querydslConfiguration;
// }
//
// // API
//
// public <Q> SQLQuery<Q> selectQuery() {
// SQLQuery<Q> query = new SQLQuery<>(getConnectionProvider(), querydslConfiguration);
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// public <Q> SQLQuery<Q> selectQuery(Connection connection) {
// return new SQLQuery<>(connection, querydslConfiguration);
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path) {
// return autoCloseQuery(new SQLDeleteClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path, Connection connection) {
// return new SQLDeleteClause(connection, querydslConfiguration, path);
// }
//
// public SQLInsertClause insert(RelationalPath<?> path) {
// return autoCloseQuery(new SQLInsertClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLInsertClause insert(RelationalPath<?> path, Connection connection) {
// return new SQLInsertClause(connection, querydslConfiguration, path);
// }
//
// public SQLUpdateClause update(RelationalPath<?> path) {
// return autoCloseQuery(new SQLUpdateClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLUpdateClause update(RelationalPath<?> path, Connection connection) {
// return new SQLUpdateClause(connection, querydslConfiguration, path);
// }
//
// // internal
//
// private <T extends AbstractSQLClause<?>> T autoCloseQuery(T query) {
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// private Supplier<Connection> getConnectionProvider() {
// return () -> {
// try {
// return dataSource().getConnection();
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// };
// }
//
// }
//
// Path: plume-db/src/main/java/com/coreoz/plume/db/utils/IdGenerator.java
// public class IdGenerator {
//
// private static long counterMax = 0;
// private static long counter = counterMax+1;
//
// private static void calcCounter() {
// // bits 33 -> 62 (30) : current time in seconds
// counter = ((System.currentTimeMillis() / 1000) & 0x3FFFFFFFL) << 33;
//
// String ip = "127.0.0.1";
// try {
// ip = InetAddress.getLocalHost().getHostAddress();
// } catch (Throwable t) {
// // Don't care any error
// }
//
// // bits 25 -> 32 (8)
// if (ip.equals("127.0.0.1")) {
// // 127.0.0.1 is too common. Instead, generate a unique string.
// counter |= (ThreadLocalRandom.current().nextInt(256) & 0xFFL) << 25;
// } else {
// counter |= (Long.parseLong(ip.substring(ip.lastIndexOf('.')+1)) & 0xFF) << 25;
// }
//
// // bits 21 -> 24 (3)
// counter |= (ThreadLocalRandom.current().nextInt(16) & 0x0FL) << 21;
//
// // All remaining bits 0 -> 20 (21) are the counter
//
// // It will count until it reach
// counterMax = counter + 0x1FFFFF; // 21 bits
// }
//
// public static synchronized long generate() {
// if (counter>counterMax) {
// calcCounter();
// }
// return counter++;
// }
//
// }
| import java.sql.Connection;
import com.coreoz.plume.db.crud.CrudDao;
import com.coreoz.plume.db.querydsl.transaction.TransactionManagerQuerydsl;
import com.coreoz.plume.db.utils.IdGenerator;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.sql.RelationalPath;
import com.querydsl.sql.dml.DefaultMapper; | package com.coreoz.plume.db.querydsl.crud;
public class CrudDaoQuerydsl<T extends CrudEntity> extends QueryDslDao<T> implements CrudDao<T> {
private final NumberPath<Long> idPath;
| // Path: plume-db/src/main/java/com/coreoz/plume/db/crud/CrudDao.java
// public interface CrudDao<T> {
//
// List<T> findAll();
//
// T findById(Long id);
//
// T save(T entityToUpdate);
//
// long delete(Long id);
//
// }
//
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydsl.java
// @Singleton
// public class TransactionManagerQuerydsl extends TransactionManager {
//
// private final Configuration querydslConfiguration;
//
// @Inject
// public TransactionManagerQuerydsl(Config config) {
// this(config, "db");
// }
//
// public TransactionManagerQuerydsl(Config config, String prefix) {
// super(config, prefix);
//
// String dialect = config.getString(prefix + ".dialect");
// this.querydslConfiguration = new Configuration(QuerydslTemplates.valueOf(dialect).sqlTemplates());
// }
//
// public TransactionManagerQuerydsl(DataSource dataSource, Configuration querydslConfiguration) {
// super(dataSource);
//
// this.querydslConfiguration = querydslConfiguration;
// }
//
// // API
//
// public <Q> SQLQuery<Q> selectQuery() {
// SQLQuery<Q> query = new SQLQuery<>(getConnectionProvider(), querydslConfiguration);
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// public <Q> SQLQuery<Q> selectQuery(Connection connection) {
// return new SQLQuery<>(connection, querydslConfiguration);
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path) {
// return autoCloseQuery(new SQLDeleteClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path, Connection connection) {
// return new SQLDeleteClause(connection, querydslConfiguration, path);
// }
//
// public SQLInsertClause insert(RelationalPath<?> path) {
// return autoCloseQuery(new SQLInsertClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLInsertClause insert(RelationalPath<?> path, Connection connection) {
// return new SQLInsertClause(connection, querydslConfiguration, path);
// }
//
// public SQLUpdateClause update(RelationalPath<?> path) {
// return autoCloseQuery(new SQLUpdateClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLUpdateClause update(RelationalPath<?> path, Connection connection) {
// return new SQLUpdateClause(connection, querydslConfiguration, path);
// }
//
// // internal
//
// private <T extends AbstractSQLClause<?>> T autoCloseQuery(T query) {
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// private Supplier<Connection> getConnectionProvider() {
// return () -> {
// try {
// return dataSource().getConnection();
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// };
// }
//
// }
//
// Path: plume-db/src/main/java/com/coreoz/plume/db/utils/IdGenerator.java
// public class IdGenerator {
//
// private static long counterMax = 0;
// private static long counter = counterMax+1;
//
// private static void calcCounter() {
// // bits 33 -> 62 (30) : current time in seconds
// counter = ((System.currentTimeMillis() / 1000) & 0x3FFFFFFFL) << 33;
//
// String ip = "127.0.0.1";
// try {
// ip = InetAddress.getLocalHost().getHostAddress();
// } catch (Throwable t) {
// // Don't care any error
// }
//
// // bits 25 -> 32 (8)
// if (ip.equals("127.0.0.1")) {
// // 127.0.0.1 is too common. Instead, generate a unique string.
// counter |= (ThreadLocalRandom.current().nextInt(256) & 0xFFL) << 25;
// } else {
// counter |= (Long.parseLong(ip.substring(ip.lastIndexOf('.')+1)) & 0xFF) << 25;
// }
//
// // bits 21 -> 24 (3)
// counter |= (ThreadLocalRandom.current().nextInt(16) & 0x0FL) << 21;
//
// // All remaining bits 0 -> 20 (21) are the counter
//
// // It will count until it reach
// counterMax = counter + 0x1FFFFF; // 21 bits
// }
//
// public static synchronized long generate() {
// if (counter>counterMax) {
// calcCounter();
// }
// return counter++;
// }
//
// }
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydsl.java
import java.sql.Connection;
import com.coreoz.plume.db.crud.CrudDao;
import com.coreoz.plume.db.querydsl.transaction.TransactionManagerQuerydsl;
import com.coreoz.plume.db.utils.IdGenerator;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.sql.RelationalPath;
import com.querydsl.sql.dml.DefaultMapper;
package com.coreoz.plume.db.querydsl.crud;
public class CrudDaoQuerydsl<T extends CrudEntity> extends QueryDslDao<T> implements CrudDao<T> {
private final NumberPath<Long> idPath;
| public CrudDaoQuerydsl(TransactionManagerQuerydsl transactionManager, |
Coreoz/Plume | plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydsl.java | // Path: plume-db/src/main/java/com/coreoz/plume/db/crud/CrudDao.java
// public interface CrudDao<T> {
//
// List<T> findAll();
//
// T findById(Long id);
//
// T save(T entityToUpdate);
//
// long delete(Long id);
//
// }
//
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydsl.java
// @Singleton
// public class TransactionManagerQuerydsl extends TransactionManager {
//
// private final Configuration querydslConfiguration;
//
// @Inject
// public TransactionManagerQuerydsl(Config config) {
// this(config, "db");
// }
//
// public TransactionManagerQuerydsl(Config config, String prefix) {
// super(config, prefix);
//
// String dialect = config.getString(prefix + ".dialect");
// this.querydslConfiguration = new Configuration(QuerydslTemplates.valueOf(dialect).sqlTemplates());
// }
//
// public TransactionManagerQuerydsl(DataSource dataSource, Configuration querydslConfiguration) {
// super(dataSource);
//
// this.querydslConfiguration = querydslConfiguration;
// }
//
// // API
//
// public <Q> SQLQuery<Q> selectQuery() {
// SQLQuery<Q> query = new SQLQuery<>(getConnectionProvider(), querydslConfiguration);
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// public <Q> SQLQuery<Q> selectQuery(Connection connection) {
// return new SQLQuery<>(connection, querydslConfiguration);
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path) {
// return autoCloseQuery(new SQLDeleteClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path, Connection connection) {
// return new SQLDeleteClause(connection, querydslConfiguration, path);
// }
//
// public SQLInsertClause insert(RelationalPath<?> path) {
// return autoCloseQuery(new SQLInsertClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLInsertClause insert(RelationalPath<?> path, Connection connection) {
// return new SQLInsertClause(connection, querydslConfiguration, path);
// }
//
// public SQLUpdateClause update(RelationalPath<?> path) {
// return autoCloseQuery(new SQLUpdateClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLUpdateClause update(RelationalPath<?> path, Connection connection) {
// return new SQLUpdateClause(connection, querydslConfiguration, path);
// }
//
// // internal
//
// private <T extends AbstractSQLClause<?>> T autoCloseQuery(T query) {
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// private Supplier<Connection> getConnectionProvider() {
// return () -> {
// try {
// return dataSource().getConnection();
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// };
// }
//
// }
//
// Path: plume-db/src/main/java/com/coreoz/plume/db/utils/IdGenerator.java
// public class IdGenerator {
//
// private static long counterMax = 0;
// private static long counter = counterMax+1;
//
// private static void calcCounter() {
// // bits 33 -> 62 (30) : current time in seconds
// counter = ((System.currentTimeMillis() / 1000) & 0x3FFFFFFFL) << 33;
//
// String ip = "127.0.0.1";
// try {
// ip = InetAddress.getLocalHost().getHostAddress();
// } catch (Throwable t) {
// // Don't care any error
// }
//
// // bits 25 -> 32 (8)
// if (ip.equals("127.0.0.1")) {
// // 127.0.0.1 is too common. Instead, generate a unique string.
// counter |= (ThreadLocalRandom.current().nextInt(256) & 0xFFL) << 25;
// } else {
// counter |= (Long.parseLong(ip.substring(ip.lastIndexOf('.')+1)) & 0xFF) << 25;
// }
//
// // bits 21 -> 24 (3)
// counter |= (ThreadLocalRandom.current().nextInt(16) & 0x0FL) << 21;
//
// // All remaining bits 0 -> 20 (21) are the counter
//
// // It will count until it reach
// counterMax = counter + 0x1FFFFF; // 21 bits
// }
//
// public static synchronized long generate() {
// if (counter>counterMax) {
// calcCounter();
// }
// return counter++;
// }
//
// }
| import java.sql.Connection;
import com.coreoz.plume.db.crud.CrudDao;
import com.coreoz.plume.db.querydsl.transaction.TransactionManagerQuerydsl;
import com.coreoz.plume.db.utils.IdGenerator;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.sql.RelationalPath;
import com.querydsl.sql.dml.DefaultMapper; | .populate(entityToUpdate)
.execute();
return entityToUpdate;
}
// update
transactionManager
.update(table, connection)
.populate(entityToUpdate, DefaultMapper.WITH_NULL_BINDINGS)
.where(idPath.eq(entityToUpdate.getId()))
.execute();
return entityToUpdate;
}
@Override
public long delete(Long id) {
return transactionManager.executeAndReturn(connection ->
delete(id, connection)
);
}
public long delete(Long id, Connection connection) {
return transactionManager
.delete(table, connection)
.where(idPath.eq(id))
.execute();
}
// dao API
protected long generateIdentifier() { | // Path: plume-db/src/main/java/com/coreoz/plume/db/crud/CrudDao.java
// public interface CrudDao<T> {
//
// List<T> findAll();
//
// T findById(Long id);
//
// T save(T entityToUpdate);
//
// long delete(Long id);
//
// }
//
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydsl.java
// @Singleton
// public class TransactionManagerQuerydsl extends TransactionManager {
//
// private final Configuration querydslConfiguration;
//
// @Inject
// public TransactionManagerQuerydsl(Config config) {
// this(config, "db");
// }
//
// public TransactionManagerQuerydsl(Config config, String prefix) {
// super(config, prefix);
//
// String dialect = config.getString(prefix + ".dialect");
// this.querydslConfiguration = new Configuration(QuerydslTemplates.valueOf(dialect).sqlTemplates());
// }
//
// public TransactionManagerQuerydsl(DataSource dataSource, Configuration querydslConfiguration) {
// super(dataSource);
//
// this.querydslConfiguration = querydslConfiguration;
// }
//
// // API
//
// public <Q> SQLQuery<Q> selectQuery() {
// SQLQuery<Q> query = new SQLQuery<>(getConnectionProvider(), querydslConfiguration);
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// public <Q> SQLQuery<Q> selectQuery(Connection connection) {
// return new SQLQuery<>(connection, querydslConfiguration);
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path) {
// return autoCloseQuery(new SQLDeleteClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path, Connection connection) {
// return new SQLDeleteClause(connection, querydslConfiguration, path);
// }
//
// public SQLInsertClause insert(RelationalPath<?> path) {
// return autoCloseQuery(new SQLInsertClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLInsertClause insert(RelationalPath<?> path, Connection connection) {
// return new SQLInsertClause(connection, querydslConfiguration, path);
// }
//
// public SQLUpdateClause update(RelationalPath<?> path) {
// return autoCloseQuery(new SQLUpdateClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLUpdateClause update(RelationalPath<?> path, Connection connection) {
// return new SQLUpdateClause(connection, querydslConfiguration, path);
// }
//
// // internal
//
// private <T extends AbstractSQLClause<?>> T autoCloseQuery(T query) {
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// private Supplier<Connection> getConnectionProvider() {
// return () -> {
// try {
// return dataSource().getConnection();
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// };
// }
//
// }
//
// Path: plume-db/src/main/java/com/coreoz/plume/db/utils/IdGenerator.java
// public class IdGenerator {
//
// private static long counterMax = 0;
// private static long counter = counterMax+1;
//
// private static void calcCounter() {
// // bits 33 -> 62 (30) : current time in seconds
// counter = ((System.currentTimeMillis() / 1000) & 0x3FFFFFFFL) << 33;
//
// String ip = "127.0.0.1";
// try {
// ip = InetAddress.getLocalHost().getHostAddress();
// } catch (Throwable t) {
// // Don't care any error
// }
//
// // bits 25 -> 32 (8)
// if (ip.equals("127.0.0.1")) {
// // 127.0.0.1 is too common. Instead, generate a unique string.
// counter |= (ThreadLocalRandom.current().nextInt(256) & 0xFFL) << 25;
// } else {
// counter |= (Long.parseLong(ip.substring(ip.lastIndexOf('.')+1)) & 0xFF) << 25;
// }
//
// // bits 21 -> 24 (3)
// counter |= (ThreadLocalRandom.current().nextInt(16) & 0x0FL) << 21;
//
// // All remaining bits 0 -> 20 (21) are the counter
//
// // It will count until it reach
// counterMax = counter + 0x1FFFFF; // 21 bits
// }
//
// public static synchronized long generate() {
// if (counter>counterMax) {
// calcCounter();
// }
// return counter++;
// }
//
// }
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydsl.java
import java.sql.Connection;
import com.coreoz.plume.db.crud.CrudDao;
import com.coreoz.plume.db.querydsl.transaction.TransactionManagerQuerydsl;
import com.coreoz.plume.db.utils.IdGenerator;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.sql.RelationalPath;
import com.querydsl.sql.dml.DefaultMapper;
.populate(entityToUpdate)
.execute();
return entityToUpdate;
}
// update
transactionManager
.update(table, connection)
.populate(entityToUpdate, DefaultMapper.WITH_NULL_BINDINGS)
.where(idPath.eq(entityToUpdate.getId()))
.execute();
return entityToUpdate;
}
@Override
public long delete(Long id) {
return transactionManager.executeAndReturn(connection ->
delete(id, connection)
);
}
public long delete(Long id, Connection connection) {
return transactionManager
.delete(table, connection)
.where(idPath.eq(id))
.execute();
}
// dao API
protected long generateIdentifier() { | return IdGenerator.generate(); |
Coreoz/Plume | plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydslTransactionTest.java | // Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
// public class DbQuerydslTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// install(new GuiceConfModule());
// install(new DataSourceModule());
// install(new GuiceDbTestModule());
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/User.java
// @Generated("com.coreoz.plume.db.querydsl.generation.IdBeanSerializer")
// public class User extends com.coreoz.plume.db.querydsl.crud.CrudEntityQuerydsl {
//
// @Column("ACTIVE")
// private Boolean active;
//
// @Column("CREATION_DATE")
// private java.time.LocalDateTime creationDate;
//
// @Column("ID")
// private Long id;
//
// @Column("NAME")
// private String name;
//
// public Boolean getActive() {
// return active;
// }
//
// public void setActive(Boolean active) {
// this.active = active;
// }
//
// public java.time.LocalDateTime getCreationDate() {
// return creationDate;
// }
//
// public void setCreationDate(java.time.LocalDateTime creationDate) {
// this.creationDate = creationDate;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (id == null) {
// return super.equals(o);
// }
// if (!(o instanceof User)) {
// return false;
// }
// User obj = (User) o;
// return id.equals(obj.id);
// }
//
// @Override
// public int hashCode() {
// if (id == null) {
// return super.hashCode();
// }
// final int prime = 31;
// int result = 1;
// result = prime * result + id.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "User#" + id;
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/UserDao.java
// @Singleton
// public class UserDao extends CrudDaoQuerydsl<User> {
//
// @Inject
// public UserDao(TransactionManagerQuerydsl transactionManagerQuerydsl) {
// super(transactionManagerQuerydsl, QUser.user);
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/transaction/TransactionInstancesHolder.java
// public class TransactionInstancesHolder {
//
// private DataSourceMocked mockedDataSource;
// private ConnectionMocked mockedConnection;
// private TransactionManagerQuerydsl transactionManager;
//
// public TransactionInstancesHolder(DataSource realDataSource) {
// try {
// Connection realConnection = realDataSource.getConnection();
// mockedConnection = new ConnectionMocked(realConnection);
// mockedDataSource = new DataSourceMocked(mockedConnection);
//
// transactionManager = new TransactionManagerQuerydsl(
// mockedDataSource,
// new Configuration(H2Templates.DEFAULT)
// );
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// }
//
// public DataSourceMocked getMockedDataSource() {
// return mockedDataSource;
// }
//
// public ConnectionMocked getMockedConnection() {
// return mockedConnection;
// }
//
// public TransactionManagerQuerydsl getTransactionManager() {
// return transactionManager;
// }
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import java.sql.SQLException;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.carlosbecker.guice.GuiceModules;
import com.carlosbecker.guice.GuiceTestRunner;
import com.coreoz.plume.db.querydsl.DbQuerydslTestModule;
import com.coreoz.plume.db.querydsl.db.User;
import com.coreoz.plume.db.querydsl.db.UserDao;
import com.coreoz.plume.db.querydsl.transaction.TransactionInstancesHolder; | package com.coreoz.plume.db.querydsl.crud;
/**
* Ensure that transaction management behave as expected for daos
*/
@RunWith(GuiceTestRunner.class)
@GuiceModules(DbQuerydslTestModule.class)
public class CrudDaoQuerydslTransactionTest {
@Inject
DataSource dataSource;
@Test
public void check_that_connection_is_released_after_findAll() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
daoInstancesHolder.userDao.findAll();
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isTrue();
}
@Test
public void check_that_connection_is_released_after_findById() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
daoInstancesHolder.userDao.findById(1L);
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isTrue();
}
@Test
public void check_that_connection_is_released_after_save() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
| // Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
// public class DbQuerydslTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// install(new GuiceConfModule());
// install(new DataSourceModule());
// install(new GuiceDbTestModule());
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/User.java
// @Generated("com.coreoz.plume.db.querydsl.generation.IdBeanSerializer")
// public class User extends com.coreoz.plume.db.querydsl.crud.CrudEntityQuerydsl {
//
// @Column("ACTIVE")
// private Boolean active;
//
// @Column("CREATION_DATE")
// private java.time.LocalDateTime creationDate;
//
// @Column("ID")
// private Long id;
//
// @Column("NAME")
// private String name;
//
// public Boolean getActive() {
// return active;
// }
//
// public void setActive(Boolean active) {
// this.active = active;
// }
//
// public java.time.LocalDateTime getCreationDate() {
// return creationDate;
// }
//
// public void setCreationDate(java.time.LocalDateTime creationDate) {
// this.creationDate = creationDate;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (id == null) {
// return super.equals(o);
// }
// if (!(o instanceof User)) {
// return false;
// }
// User obj = (User) o;
// return id.equals(obj.id);
// }
//
// @Override
// public int hashCode() {
// if (id == null) {
// return super.hashCode();
// }
// final int prime = 31;
// int result = 1;
// result = prime * result + id.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "User#" + id;
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/UserDao.java
// @Singleton
// public class UserDao extends CrudDaoQuerydsl<User> {
//
// @Inject
// public UserDao(TransactionManagerQuerydsl transactionManagerQuerydsl) {
// super(transactionManagerQuerydsl, QUser.user);
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/transaction/TransactionInstancesHolder.java
// public class TransactionInstancesHolder {
//
// private DataSourceMocked mockedDataSource;
// private ConnectionMocked mockedConnection;
// private TransactionManagerQuerydsl transactionManager;
//
// public TransactionInstancesHolder(DataSource realDataSource) {
// try {
// Connection realConnection = realDataSource.getConnection();
// mockedConnection = new ConnectionMocked(realConnection);
// mockedDataSource = new DataSourceMocked(mockedConnection);
//
// transactionManager = new TransactionManagerQuerydsl(
// mockedDataSource,
// new Configuration(H2Templates.DEFAULT)
// );
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// }
//
// public DataSourceMocked getMockedDataSource() {
// return mockedDataSource;
// }
//
// public ConnectionMocked getMockedConnection() {
// return mockedConnection;
// }
//
// public TransactionManagerQuerydsl getTransactionManager() {
// return transactionManager;
// }
//
// }
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydslTransactionTest.java
import static org.assertj.core.api.Assertions.assertThat;
import java.sql.SQLException;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.carlosbecker.guice.GuiceModules;
import com.carlosbecker.guice.GuiceTestRunner;
import com.coreoz.plume.db.querydsl.DbQuerydslTestModule;
import com.coreoz.plume.db.querydsl.db.User;
import com.coreoz.plume.db.querydsl.db.UserDao;
import com.coreoz.plume.db.querydsl.transaction.TransactionInstancesHolder;
package com.coreoz.plume.db.querydsl.crud;
/**
* Ensure that transaction management behave as expected for daos
*/
@RunWith(GuiceTestRunner.class)
@GuiceModules(DbQuerydslTestModule.class)
public class CrudDaoQuerydslTransactionTest {
@Inject
DataSource dataSource;
@Test
public void check_that_connection_is_released_after_findAll() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
daoInstancesHolder.userDao.findAll();
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isTrue();
}
@Test
public void check_that_connection_is_released_after_findById() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
daoInstancesHolder.userDao.findById(1L);
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isTrue();
}
@Test
public void check_that_connection_is_released_after_save() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
| User user = new User(); |
Coreoz/Plume | plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydslTransactionTest.java | // Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
// public class DbQuerydslTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// install(new GuiceConfModule());
// install(new DataSourceModule());
// install(new GuiceDbTestModule());
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/User.java
// @Generated("com.coreoz.plume.db.querydsl.generation.IdBeanSerializer")
// public class User extends com.coreoz.plume.db.querydsl.crud.CrudEntityQuerydsl {
//
// @Column("ACTIVE")
// private Boolean active;
//
// @Column("CREATION_DATE")
// private java.time.LocalDateTime creationDate;
//
// @Column("ID")
// private Long id;
//
// @Column("NAME")
// private String name;
//
// public Boolean getActive() {
// return active;
// }
//
// public void setActive(Boolean active) {
// this.active = active;
// }
//
// public java.time.LocalDateTime getCreationDate() {
// return creationDate;
// }
//
// public void setCreationDate(java.time.LocalDateTime creationDate) {
// this.creationDate = creationDate;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (id == null) {
// return super.equals(o);
// }
// if (!(o instanceof User)) {
// return false;
// }
// User obj = (User) o;
// return id.equals(obj.id);
// }
//
// @Override
// public int hashCode() {
// if (id == null) {
// return super.hashCode();
// }
// final int prime = 31;
// int result = 1;
// result = prime * result + id.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "User#" + id;
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/UserDao.java
// @Singleton
// public class UserDao extends CrudDaoQuerydsl<User> {
//
// @Inject
// public UserDao(TransactionManagerQuerydsl transactionManagerQuerydsl) {
// super(transactionManagerQuerydsl, QUser.user);
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/transaction/TransactionInstancesHolder.java
// public class TransactionInstancesHolder {
//
// private DataSourceMocked mockedDataSource;
// private ConnectionMocked mockedConnection;
// private TransactionManagerQuerydsl transactionManager;
//
// public TransactionInstancesHolder(DataSource realDataSource) {
// try {
// Connection realConnection = realDataSource.getConnection();
// mockedConnection = new ConnectionMocked(realConnection);
// mockedDataSource = new DataSourceMocked(mockedConnection);
//
// transactionManager = new TransactionManagerQuerydsl(
// mockedDataSource,
// new Configuration(H2Templates.DEFAULT)
// );
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// }
//
// public DataSourceMocked getMockedDataSource() {
// return mockedDataSource;
// }
//
// public ConnectionMocked getMockedConnection() {
// return mockedConnection;
// }
//
// public TransactionManagerQuerydsl getTransactionManager() {
// return transactionManager;
// }
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import java.sql.SQLException;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.carlosbecker.guice.GuiceModules;
import com.carlosbecker.guice.GuiceTestRunner;
import com.coreoz.plume.db.querydsl.DbQuerydslTestModule;
import com.coreoz.plume.db.querydsl.db.User;
import com.coreoz.plume.db.querydsl.db.UserDao;
import com.coreoz.plume.db.querydsl.transaction.TransactionInstancesHolder; |
@Test
public void check_that_connection_is_NOT_released_after_transactional_save() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
User user = new User();
user.setName("test");
daoInstancesHolder.userDao.save(user, daoInstancesHolder.getMockedConnection());
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isFalse();
}
@Test
public void check_that_connection_is_released_after_delete() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
daoInstancesHolder.userDao.delete(123132464L);
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isTrue();
}
@Test
public void check_that_connection_is_NOT_released_after_transactional_delete() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
daoInstancesHolder.userDao.delete(123132464L, daoInstancesHolder.getMockedConnection());
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isFalse();
}
| // Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
// public class DbQuerydslTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// install(new GuiceConfModule());
// install(new DataSourceModule());
// install(new GuiceDbTestModule());
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/User.java
// @Generated("com.coreoz.plume.db.querydsl.generation.IdBeanSerializer")
// public class User extends com.coreoz.plume.db.querydsl.crud.CrudEntityQuerydsl {
//
// @Column("ACTIVE")
// private Boolean active;
//
// @Column("CREATION_DATE")
// private java.time.LocalDateTime creationDate;
//
// @Column("ID")
// private Long id;
//
// @Column("NAME")
// private String name;
//
// public Boolean getActive() {
// return active;
// }
//
// public void setActive(Boolean active) {
// this.active = active;
// }
//
// public java.time.LocalDateTime getCreationDate() {
// return creationDate;
// }
//
// public void setCreationDate(java.time.LocalDateTime creationDate) {
// this.creationDate = creationDate;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (id == null) {
// return super.equals(o);
// }
// if (!(o instanceof User)) {
// return false;
// }
// User obj = (User) o;
// return id.equals(obj.id);
// }
//
// @Override
// public int hashCode() {
// if (id == null) {
// return super.hashCode();
// }
// final int prime = 31;
// int result = 1;
// result = prime * result + id.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "User#" + id;
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/UserDao.java
// @Singleton
// public class UserDao extends CrudDaoQuerydsl<User> {
//
// @Inject
// public UserDao(TransactionManagerQuerydsl transactionManagerQuerydsl) {
// super(transactionManagerQuerydsl, QUser.user);
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/transaction/TransactionInstancesHolder.java
// public class TransactionInstancesHolder {
//
// private DataSourceMocked mockedDataSource;
// private ConnectionMocked mockedConnection;
// private TransactionManagerQuerydsl transactionManager;
//
// public TransactionInstancesHolder(DataSource realDataSource) {
// try {
// Connection realConnection = realDataSource.getConnection();
// mockedConnection = new ConnectionMocked(realConnection);
// mockedDataSource = new DataSourceMocked(mockedConnection);
//
// transactionManager = new TransactionManagerQuerydsl(
// mockedDataSource,
// new Configuration(H2Templates.DEFAULT)
// );
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// }
//
// public DataSourceMocked getMockedDataSource() {
// return mockedDataSource;
// }
//
// public ConnectionMocked getMockedConnection() {
// return mockedConnection;
// }
//
// public TransactionManagerQuerydsl getTransactionManager() {
// return transactionManager;
// }
//
// }
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydslTransactionTest.java
import static org.assertj.core.api.Assertions.assertThat;
import java.sql.SQLException;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.carlosbecker.guice.GuiceModules;
import com.carlosbecker.guice.GuiceTestRunner;
import com.coreoz.plume.db.querydsl.DbQuerydslTestModule;
import com.coreoz.plume.db.querydsl.db.User;
import com.coreoz.plume.db.querydsl.db.UserDao;
import com.coreoz.plume.db.querydsl.transaction.TransactionInstancesHolder;
@Test
public void check_that_connection_is_NOT_released_after_transactional_save() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
User user = new User();
user.setName("test");
daoInstancesHolder.userDao.save(user, daoInstancesHolder.getMockedConnection());
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isFalse();
}
@Test
public void check_that_connection_is_released_after_delete() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
daoInstancesHolder.userDao.delete(123132464L);
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isTrue();
}
@Test
public void check_that_connection_is_NOT_released_after_transactional_delete() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
daoInstancesHolder.userDao.delete(123132464L, daoInstancesHolder.getMockedConnection());
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isFalse();
}
| private static class DaoInstancesHolder extends TransactionInstancesHolder { |
Coreoz/Plume | plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydslTransactionTest.java | // Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
// public class DbQuerydslTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// install(new GuiceConfModule());
// install(new DataSourceModule());
// install(new GuiceDbTestModule());
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/User.java
// @Generated("com.coreoz.plume.db.querydsl.generation.IdBeanSerializer")
// public class User extends com.coreoz.plume.db.querydsl.crud.CrudEntityQuerydsl {
//
// @Column("ACTIVE")
// private Boolean active;
//
// @Column("CREATION_DATE")
// private java.time.LocalDateTime creationDate;
//
// @Column("ID")
// private Long id;
//
// @Column("NAME")
// private String name;
//
// public Boolean getActive() {
// return active;
// }
//
// public void setActive(Boolean active) {
// this.active = active;
// }
//
// public java.time.LocalDateTime getCreationDate() {
// return creationDate;
// }
//
// public void setCreationDate(java.time.LocalDateTime creationDate) {
// this.creationDate = creationDate;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (id == null) {
// return super.equals(o);
// }
// if (!(o instanceof User)) {
// return false;
// }
// User obj = (User) o;
// return id.equals(obj.id);
// }
//
// @Override
// public int hashCode() {
// if (id == null) {
// return super.hashCode();
// }
// final int prime = 31;
// int result = 1;
// result = prime * result + id.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "User#" + id;
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/UserDao.java
// @Singleton
// public class UserDao extends CrudDaoQuerydsl<User> {
//
// @Inject
// public UserDao(TransactionManagerQuerydsl transactionManagerQuerydsl) {
// super(transactionManagerQuerydsl, QUser.user);
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/transaction/TransactionInstancesHolder.java
// public class TransactionInstancesHolder {
//
// private DataSourceMocked mockedDataSource;
// private ConnectionMocked mockedConnection;
// private TransactionManagerQuerydsl transactionManager;
//
// public TransactionInstancesHolder(DataSource realDataSource) {
// try {
// Connection realConnection = realDataSource.getConnection();
// mockedConnection = new ConnectionMocked(realConnection);
// mockedDataSource = new DataSourceMocked(mockedConnection);
//
// transactionManager = new TransactionManagerQuerydsl(
// mockedDataSource,
// new Configuration(H2Templates.DEFAULT)
// );
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// }
//
// public DataSourceMocked getMockedDataSource() {
// return mockedDataSource;
// }
//
// public ConnectionMocked getMockedConnection() {
// return mockedConnection;
// }
//
// public TransactionManagerQuerydsl getTransactionManager() {
// return transactionManager;
// }
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import java.sql.SQLException;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.carlosbecker.guice.GuiceModules;
import com.carlosbecker.guice.GuiceTestRunner;
import com.coreoz.plume.db.querydsl.DbQuerydslTestModule;
import com.coreoz.plume.db.querydsl.db.User;
import com.coreoz.plume.db.querydsl.db.UserDao;
import com.coreoz.plume.db.querydsl.transaction.TransactionInstancesHolder; | @Test
public void check_that_connection_is_NOT_released_after_transactional_save() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
User user = new User();
user.setName("test");
daoInstancesHolder.userDao.save(user, daoInstancesHolder.getMockedConnection());
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isFalse();
}
@Test
public void check_that_connection_is_released_after_delete() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
daoInstancesHolder.userDao.delete(123132464L);
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isTrue();
}
@Test
public void check_that_connection_is_NOT_released_after_transactional_delete() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
daoInstancesHolder.userDao.delete(123132464L, daoInstancesHolder.getMockedConnection());
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isFalse();
}
private static class DaoInstancesHolder extends TransactionInstancesHolder { | // Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
// public class DbQuerydslTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// install(new GuiceConfModule());
// install(new DataSourceModule());
// install(new GuiceDbTestModule());
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/User.java
// @Generated("com.coreoz.plume.db.querydsl.generation.IdBeanSerializer")
// public class User extends com.coreoz.plume.db.querydsl.crud.CrudEntityQuerydsl {
//
// @Column("ACTIVE")
// private Boolean active;
//
// @Column("CREATION_DATE")
// private java.time.LocalDateTime creationDate;
//
// @Column("ID")
// private Long id;
//
// @Column("NAME")
// private String name;
//
// public Boolean getActive() {
// return active;
// }
//
// public void setActive(Boolean active) {
// this.active = active;
// }
//
// public java.time.LocalDateTime getCreationDate() {
// return creationDate;
// }
//
// public void setCreationDate(java.time.LocalDateTime creationDate) {
// this.creationDate = creationDate;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (id == null) {
// return super.equals(o);
// }
// if (!(o instanceof User)) {
// return false;
// }
// User obj = (User) o;
// return id.equals(obj.id);
// }
//
// @Override
// public int hashCode() {
// if (id == null) {
// return super.hashCode();
// }
// final int prime = 31;
// int result = 1;
// result = prime * result + id.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "User#" + id;
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/UserDao.java
// @Singleton
// public class UserDao extends CrudDaoQuerydsl<User> {
//
// @Inject
// public UserDao(TransactionManagerQuerydsl transactionManagerQuerydsl) {
// super(transactionManagerQuerydsl, QUser.user);
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/transaction/TransactionInstancesHolder.java
// public class TransactionInstancesHolder {
//
// private DataSourceMocked mockedDataSource;
// private ConnectionMocked mockedConnection;
// private TransactionManagerQuerydsl transactionManager;
//
// public TransactionInstancesHolder(DataSource realDataSource) {
// try {
// Connection realConnection = realDataSource.getConnection();
// mockedConnection = new ConnectionMocked(realConnection);
// mockedDataSource = new DataSourceMocked(mockedConnection);
//
// transactionManager = new TransactionManagerQuerydsl(
// mockedDataSource,
// new Configuration(H2Templates.DEFAULT)
// );
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// }
//
// public DataSourceMocked getMockedDataSource() {
// return mockedDataSource;
// }
//
// public ConnectionMocked getMockedConnection() {
// return mockedConnection;
// }
//
// public TransactionManagerQuerydsl getTransactionManager() {
// return transactionManager;
// }
//
// }
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydslTransactionTest.java
import static org.assertj.core.api.Assertions.assertThat;
import java.sql.SQLException;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.carlosbecker.guice.GuiceModules;
import com.carlosbecker.guice.GuiceTestRunner;
import com.coreoz.plume.db.querydsl.DbQuerydslTestModule;
import com.coreoz.plume.db.querydsl.db.User;
import com.coreoz.plume.db.querydsl.db.UserDao;
import com.coreoz.plume.db.querydsl.transaction.TransactionInstancesHolder;
@Test
public void check_that_connection_is_NOT_released_after_transactional_save() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
User user = new User();
user.setName("test");
daoInstancesHolder.userDao.save(user, daoInstancesHolder.getMockedConnection());
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isFalse();
}
@Test
public void check_that_connection_is_released_after_delete() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
daoInstancesHolder.userDao.delete(123132464L);
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isTrue();
}
@Test
public void check_that_connection_is_NOT_released_after_transactional_delete() throws SQLException {
DaoInstancesHolder daoInstancesHolder = new DaoInstancesHolder(dataSource);
daoInstancesHolder.userDao.delete(123132464L, daoInstancesHolder.getMockedConnection());
assertThat(daoInstancesHolder.getMockedConnection().isCloseCalled()).isFalse();
}
private static class DaoInstancesHolder extends TransactionInstancesHolder { | private UserDao userDao; |
Coreoz/Plume | plume-conf/src/main/java/com/coreoz/plume/conf/dagger/DaggerConfModule.java | // Path: plume-conf/src/main/java/com/coreoz/plume/conf/ConfigProvider.java
// @Singleton
// public class ConfigProvider implements Provider<Config> {
//
// private Config config;
//
// @Inject
// public ConfigProvider() {
// this.config = ConfigFactory.load();
// }
//
// @Override
// public Config get() {
// return config;
// }
//
// }
| import com.coreoz.plume.conf.ConfigProvider;
import com.typesafe.config.Config;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton; | package com.coreoz.plume.conf.dagger;
@Module
public class DaggerConfModule {
@Provides
@Singleton | // Path: plume-conf/src/main/java/com/coreoz/plume/conf/ConfigProvider.java
// @Singleton
// public class ConfigProvider implements Provider<Config> {
//
// private Config config;
//
// @Inject
// public ConfigProvider() {
// this.config = ConfigFactory.load();
// }
//
// @Override
// public Config get() {
// return config;
// }
//
// }
// Path: plume-conf/src/main/java/com/coreoz/plume/conf/dagger/DaggerConfModule.java
import com.coreoz.plume.conf.ConfigProvider;
import com.typesafe.config.Config;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
package com.coreoz.plume.conf.dagger;
@Module
public class DaggerConfModule {
@Provides
@Singleton | static Config provideConfig(ConfigProvider configProvider) { |
Coreoz/Plume | plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java | // Path: plume-conf/src/main/java/com/coreoz/plume/conf/guice/GuiceConfModule.java
// public class GuiceConfModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(Config.class).toProvider(ConfigProvider.class);
// }
//
// }
//
// Path: plume-db/src/main/java/com/coreoz/plume/db/guice/DataSourceModule.java
// public class DataSourceModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(DataSource.class).toProvider(DataSourceProvider.class);
// }
//
// }
//
// Path: plume-db-test/src/main/java/com/coreoz/plume/db/guice/GuiceDbTestModule.java
// public class GuiceDbTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(InitializeDatabase.class).asEagerSingleton();
// }
//
// }
| import com.coreoz.plume.conf.guice.GuiceConfModule;
import com.coreoz.plume.db.guice.DataSourceModule;
import com.coreoz.plume.db.guice.GuiceDbTestModule;
import com.google.inject.AbstractModule; | package com.coreoz.plume.db.querydsl;
public class DbQuerydslTestModule extends AbstractModule {
@Override
protected void configure() { | // Path: plume-conf/src/main/java/com/coreoz/plume/conf/guice/GuiceConfModule.java
// public class GuiceConfModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(Config.class).toProvider(ConfigProvider.class);
// }
//
// }
//
// Path: plume-db/src/main/java/com/coreoz/plume/db/guice/DataSourceModule.java
// public class DataSourceModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(DataSource.class).toProvider(DataSourceProvider.class);
// }
//
// }
//
// Path: plume-db-test/src/main/java/com/coreoz/plume/db/guice/GuiceDbTestModule.java
// public class GuiceDbTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(InitializeDatabase.class).asEagerSingleton();
// }
//
// }
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
import com.coreoz.plume.conf.guice.GuiceConfModule;
import com.coreoz.plume.db.guice.DataSourceModule;
import com.coreoz.plume.db.guice.GuiceDbTestModule;
import com.google.inject.AbstractModule;
package com.coreoz.plume.db.querydsl;
public class DbQuerydslTestModule extends AbstractModule {
@Override
protected void configure() { | install(new GuiceConfModule()); |
Coreoz/Plume | plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java | // Path: plume-conf/src/main/java/com/coreoz/plume/conf/guice/GuiceConfModule.java
// public class GuiceConfModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(Config.class).toProvider(ConfigProvider.class);
// }
//
// }
//
// Path: plume-db/src/main/java/com/coreoz/plume/db/guice/DataSourceModule.java
// public class DataSourceModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(DataSource.class).toProvider(DataSourceProvider.class);
// }
//
// }
//
// Path: plume-db-test/src/main/java/com/coreoz/plume/db/guice/GuiceDbTestModule.java
// public class GuiceDbTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(InitializeDatabase.class).asEagerSingleton();
// }
//
// }
| import com.coreoz.plume.conf.guice.GuiceConfModule;
import com.coreoz.plume.db.guice.DataSourceModule;
import com.coreoz.plume.db.guice.GuiceDbTestModule;
import com.google.inject.AbstractModule; | package com.coreoz.plume.db.querydsl;
public class DbQuerydslTestModule extends AbstractModule {
@Override
protected void configure() {
install(new GuiceConfModule()); | // Path: plume-conf/src/main/java/com/coreoz/plume/conf/guice/GuiceConfModule.java
// public class GuiceConfModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(Config.class).toProvider(ConfigProvider.class);
// }
//
// }
//
// Path: plume-db/src/main/java/com/coreoz/plume/db/guice/DataSourceModule.java
// public class DataSourceModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(DataSource.class).toProvider(DataSourceProvider.class);
// }
//
// }
//
// Path: plume-db-test/src/main/java/com/coreoz/plume/db/guice/GuiceDbTestModule.java
// public class GuiceDbTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(InitializeDatabase.class).asEagerSingleton();
// }
//
// }
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
import com.coreoz.plume.conf.guice.GuiceConfModule;
import com.coreoz.plume.db.guice.DataSourceModule;
import com.coreoz.plume.db.guice.GuiceDbTestModule;
import com.google.inject.AbstractModule;
package com.coreoz.plume.db.querydsl;
public class DbQuerydslTestModule extends AbstractModule {
@Override
protected void configure() {
install(new GuiceConfModule()); | install(new DataSourceModule()); |
Coreoz/Plume | plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java | // Path: plume-conf/src/main/java/com/coreoz/plume/conf/guice/GuiceConfModule.java
// public class GuiceConfModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(Config.class).toProvider(ConfigProvider.class);
// }
//
// }
//
// Path: plume-db/src/main/java/com/coreoz/plume/db/guice/DataSourceModule.java
// public class DataSourceModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(DataSource.class).toProvider(DataSourceProvider.class);
// }
//
// }
//
// Path: plume-db-test/src/main/java/com/coreoz/plume/db/guice/GuiceDbTestModule.java
// public class GuiceDbTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(InitializeDatabase.class).asEagerSingleton();
// }
//
// }
| import com.coreoz.plume.conf.guice.GuiceConfModule;
import com.coreoz.plume.db.guice.DataSourceModule;
import com.coreoz.plume.db.guice.GuiceDbTestModule;
import com.google.inject.AbstractModule; | package com.coreoz.plume.db.querydsl;
public class DbQuerydslTestModule extends AbstractModule {
@Override
protected void configure() {
install(new GuiceConfModule());
install(new DataSourceModule()); | // Path: plume-conf/src/main/java/com/coreoz/plume/conf/guice/GuiceConfModule.java
// public class GuiceConfModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(Config.class).toProvider(ConfigProvider.class);
// }
//
// }
//
// Path: plume-db/src/main/java/com/coreoz/plume/db/guice/DataSourceModule.java
// public class DataSourceModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(DataSource.class).toProvider(DataSourceProvider.class);
// }
//
// }
//
// Path: plume-db-test/src/main/java/com/coreoz/plume/db/guice/GuiceDbTestModule.java
// public class GuiceDbTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(InitializeDatabase.class).asEagerSingleton();
// }
//
// }
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
import com.coreoz.plume.conf.guice.GuiceConfModule;
import com.coreoz.plume.db.guice.DataSourceModule;
import com.coreoz.plume.db.guice.GuiceDbTestModule;
import com.google.inject.AbstractModule;
package com.coreoz.plume.db.querydsl;
public class DbQuerydslTestModule extends AbstractModule {
@Override
protected void configure() {
install(new GuiceConfModule());
install(new DataSourceModule()); | install(new GuiceDbTestModule()); |
Coreoz/Plume | plume-web-jersey/src/main/java/com/coreoz/plume/jersey/async/AsyncJersey.java | // Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/errors/ErrorResponse.java
// public class ErrorResponse {
//
// private final String errorCode;
// private final Iterable<String> statusArguments;
//
// public ErrorResponse(WsError error, Iterable<String> statusArguments) {
// this.errorCode = error.name();
// this.statusArguments = statusArguments;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public Iterable<String> getStatusArguments() {
// return statusArguments;
// }
//
// }
//
// Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/errors/WsError.java
// public interface WsError {
//
// // common errors
// WsError INTERNAL_ERROR = new WsErrorInternal("INTERNAL_ERROR");
// WsError REQUEST_INVALID = new WsErrorInternal("REQUEST_INVALID");
// WsError FIELD_REQUIRED = new WsErrorInternal("FIELD_REQUIRED");
// WsError EMAIL_INVALID = new WsErrorInternal("EMAIL_INVALID");
// WsError COLOR_INVALID = new WsErrorInternal("COLOR_INVALID");
//
// /**
// * Returns the name of the error
// */
// String name();
//
// class WsErrorInternal implements WsError {
//
// private final String name;
//
// public WsErrorInternal(String name) {
// this.name = name;
// }
//
// @Override
// public String name() {
// return name;
// }
// }
//
// }
| import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import javax.ws.rs.container.AsyncResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.coreoz.plume.jersey.errors.ErrorResponse;
import com.coreoz.plume.jersey.errors.WsError;
import com.google.common.collect.ImmutableList; | package com.coreoz.plume.jersey.async;
/**
* Provides a bridge between JAX-RS asynchronous API and Java 8 asynchronous API
* @see CompletableFuture
* @see AsyncResponse
*/
public class AsyncJersey {
private static final Logger logger = LoggerFactory.getLogger(AsyncJersey.class);
/**
* Provides a {@link BiConsumer} from an {@link AsyncResponse}
* that should be called when a {@link CompletableFuture} is terminated.<br>
* <br>
* Usage example:
* <code><pre>
* @GET
* public void fetchAsync(@Suspended AsyncResponse asyncResponse) {
* asyncService
* .fetchDataAsync()
* .whenCompleteAsync(toAsyncConsumer(asyncResponse));
* }
* </pre></code>
*/
public static BiConsumer<? super Object, ? super Throwable> toAsyncConsumer(AsyncResponse asyncResponse) {
return (responseBody, exception) -> {
if (exception == null) {
asyncResponse.resume(responseBody);
} else {
logger.error("An exception was raised during the promise execution", exception); | // Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/errors/ErrorResponse.java
// public class ErrorResponse {
//
// private final String errorCode;
// private final Iterable<String> statusArguments;
//
// public ErrorResponse(WsError error, Iterable<String> statusArguments) {
// this.errorCode = error.name();
// this.statusArguments = statusArguments;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public Iterable<String> getStatusArguments() {
// return statusArguments;
// }
//
// }
//
// Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/errors/WsError.java
// public interface WsError {
//
// // common errors
// WsError INTERNAL_ERROR = new WsErrorInternal("INTERNAL_ERROR");
// WsError REQUEST_INVALID = new WsErrorInternal("REQUEST_INVALID");
// WsError FIELD_REQUIRED = new WsErrorInternal("FIELD_REQUIRED");
// WsError EMAIL_INVALID = new WsErrorInternal("EMAIL_INVALID");
// WsError COLOR_INVALID = new WsErrorInternal("COLOR_INVALID");
//
// /**
// * Returns the name of the error
// */
// String name();
//
// class WsErrorInternal implements WsError {
//
// private final String name;
//
// public WsErrorInternal(String name) {
// this.name = name;
// }
//
// @Override
// public String name() {
// return name;
// }
// }
//
// }
// Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/async/AsyncJersey.java
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import javax.ws.rs.container.AsyncResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.coreoz.plume.jersey.errors.ErrorResponse;
import com.coreoz.plume.jersey.errors.WsError;
import com.google.common.collect.ImmutableList;
package com.coreoz.plume.jersey.async;
/**
* Provides a bridge between JAX-RS asynchronous API and Java 8 asynchronous API
* @see CompletableFuture
* @see AsyncResponse
*/
public class AsyncJersey {
private static final Logger logger = LoggerFactory.getLogger(AsyncJersey.class);
/**
* Provides a {@link BiConsumer} from an {@link AsyncResponse}
* that should be called when a {@link CompletableFuture} is terminated.<br>
* <br>
* Usage example:
* <code><pre>
* @GET
* public void fetchAsync(@Suspended AsyncResponse asyncResponse) {
* asyncService
* .fetchDataAsync()
* .whenCompleteAsync(toAsyncConsumer(asyncResponse));
* }
* </pre></code>
*/
public static BiConsumer<? super Object, ? super Throwable> toAsyncConsumer(AsyncResponse asyncResponse) {
return (responseBody, exception) -> {
if (exception == null) {
asyncResponse.resume(responseBody);
} else {
logger.error("An exception was raised during the promise execution", exception); | asyncResponse.resume(new ErrorResponse(WsError.INTERNAL_ERROR, ImmutableList.of())); |
Coreoz/Plume | plume-web-jersey/src/main/java/com/coreoz/plume/jersey/async/AsyncJersey.java | // Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/errors/ErrorResponse.java
// public class ErrorResponse {
//
// private final String errorCode;
// private final Iterable<String> statusArguments;
//
// public ErrorResponse(WsError error, Iterable<String> statusArguments) {
// this.errorCode = error.name();
// this.statusArguments = statusArguments;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public Iterable<String> getStatusArguments() {
// return statusArguments;
// }
//
// }
//
// Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/errors/WsError.java
// public interface WsError {
//
// // common errors
// WsError INTERNAL_ERROR = new WsErrorInternal("INTERNAL_ERROR");
// WsError REQUEST_INVALID = new WsErrorInternal("REQUEST_INVALID");
// WsError FIELD_REQUIRED = new WsErrorInternal("FIELD_REQUIRED");
// WsError EMAIL_INVALID = new WsErrorInternal("EMAIL_INVALID");
// WsError COLOR_INVALID = new WsErrorInternal("COLOR_INVALID");
//
// /**
// * Returns the name of the error
// */
// String name();
//
// class WsErrorInternal implements WsError {
//
// private final String name;
//
// public WsErrorInternal(String name) {
// this.name = name;
// }
//
// @Override
// public String name() {
// return name;
// }
// }
//
// }
| import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import javax.ws.rs.container.AsyncResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.coreoz.plume.jersey.errors.ErrorResponse;
import com.coreoz.plume.jersey.errors.WsError;
import com.google.common.collect.ImmutableList; | package com.coreoz.plume.jersey.async;
/**
* Provides a bridge between JAX-RS asynchronous API and Java 8 asynchronous API
* @see CompletableFuture
* @see AsyncResponse
*/
public class AsyncJersey {
private static final Logger logger = LoggerFactory.getLogger(AsyncJersey.class);
/**
* Provides a {@link BiConsumer} from an {@link AsyncResponse}
* that should be called when a {@link CompletableFuture} is terminated.<br>
* <br>
* Usage example:
* <code><pre>
* @GET
* public void fetchAsync(@Suspended AsyncResponse asyncResponse) {
* asyncService
* .fetchDataAsync()
* .whenCompleteAsync(toAsyncConsumer(asyncResponse));
* }
* </pre></code>
*/
public static BiConsumer<? super Object, ? super Throwable> toAsyncConsumer(AsyncResponse asyncResponse) {
return (responseBody, exception) -> {
if (exception == null) {
asyncResponse.resume(responseBody);
} else {
logger.error("An exception was raised during the promise execution", exception); | // Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/errors/ErrorResponse.java
// public class ErrorResponse {
//
// private final String errorCode;
// private final Iterable<String> statusArguments;
//
// public ErrorResponse(WsError error, Iterable<String> statusArguments) {
// this.errorCode = error.name();
// this.statusArguments = statusArguments;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public Iterable<String> getStatusArguments() {
// return statusArguments;
// }
//
// }
//
// Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/errors/WsError.java
// public interface WsError {
//
// // common errors
// WsError INTERNAL_ERROR = new WsErrorInternal("INTERNAL_ERROR");
// WsError REQUEST_INVALID = new WsErrorInternal("REQUEST_INVALID");
// WsError FIELD_REQUIRED = new WsErrorInternal("FIELD_REQUIRED");
// WsError EMAIL_INVALID = new WsErrorInternal("EMAIL_INVALID");
// WsError COLOR_INVALID = new WsErrorInternal("COLOR_INVALID");
//
// /**
// * Returns the name of the error
// */
// String name();
//
// class WsErrorInternal implements WsError {
//
// private final String name;
//
// public WsErrorInternal(String name) {
// this.name = name;
// }
//
// @Override
// public String name() {
// return name;
// }
// }
//
// }
// Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/async/AsyncJersey.java
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import javax.ws.rs.container.AsyncResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.coreoz.plume.jersey.errors.ErrorResponse;
import com.coreoz.plume.jersey.errors.WsError;
import com.google.common.collect.ImmutableList;
package com.coreoz.plume.jersey.async;
/**
* Provides a bridge between JAX-RS asynchronous API and Java 8 asynchronous API
* @see CompletableFuture
* @see AsyncResponse
*/
public class AsyncJersey {
private static final Logger logger = LoggerFactory.getLogger(AsyncJersey.class);
/**
* Provides a {@link BiConsumer} from an {@link AsyncResponse}
* that should be called when a {@link CompletableFuture} is terminated.<br>
* <br>
* Usage example:
* <code><pre>
* @GET
* public void fetchAsync(@Suspended AsyncResponse asyncResponse) {
* asyncService
* .fetchDataAsync()
* .whenCompleteAsync(toAsyncConsumer(asyncResponse));
* }
* </pre></code>
*/
public static BiConsumer<? super Object, ? super Throwable> toAsyncConsumer(AsyncResponse asyncResponse) {
return (responseBody, exception) -> {
if (exception == null) {
asyncResponse.resume(responseBody);
} else {
logger.error("An exception was raised during the promise execution", exception); | asyncResponse.resume(new ErrorResponse(WsError.INTERNAL_ERROR, ImmutableList.of())); |
Coreoz/Plume | plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydslTest.java | // Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
// public class DbQuerydslTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// install(new GuiceConfModule());
// install(new DataSourceModule());
// install(new GuiceDbTestModule());
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/QUser.java
// @Generated("com.querydsl.sql.codegen.MetaDataSerializer")
// public class QUser extends com.querydsl.sql.RelationalPathBase<User> {
//
// private static final long serialVersionUID = -50309753;
//
// public static final QUser user = new QUser("USER");
//
// public final BooleanPath active = createBoolean("active");
//
// public final DateTimePath<java.time.LocalDateTime> creationDate = createDateTime("creationDate", java.time.LocalDateTime.class);
//
// public final NumberPath<Long> id = createNumber("id", Long.class);
//
// public final StringPath name = createString("name");
//
// public final com.querydsl.sql.PrimaryKey<User> constraint2 = createPrimaryKey(id);
//
// public QUser(String variable) {
// super(User.class, forVariable(variable), "PUBLIC", "USER");
// addMetadata();
// }
//
// public QUser(String variable, String schema, String table) {
// super(User.class, forVariable(variable), schema, table);
// addMetadata();
// }
//
// public QUser(Path<? extends User> path) {
// super(path.getType(), path.getMetadata(), "PUBLIC", "USER");
// addMetadata();
// }
//
// public QUser(PathMetadata metadata) {
// super(User.class, metadata, "PUBLIC", "USER");
// addMetadata();
// }
//
// public void addMetadata() {
// addMetadata(active, ColumnMetadata.named("ACTIVE").withIndex(3).ofType(Types.BOOLEAN).withSize(1));
// addMetadata(creationDate, ColumnMetadata.named("CREATION_DATE").withIndex(4).ofType(Types.TIMESTAMP).withSize(23).withDigits(10));
// addMetadata(id, ColumnMetadata.named("ID").withIndex(1).ofType(Types.BIGINT).withSize(19).notNull());
// addMetadata(name, ColumnMetadata.named("NAME").withIndex(2).ofType(Types.VARCHAR).withSize(255));
// }
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import java.sql.SQLException;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.carlosbecker.guice.GuiceModules;
import com.carlosbecker.guice.GuiceTestRunner;
import com.coreoz.plume.db.querydsl.DbQuerydslTestModule;
import com.coreoz.plume.db.querydsl.db.QUser; | package com.coreoz.plume.db.querydsl.transaction;
@RunWith(GuiceTestRunner.class)
@GuiceModules(DbQuerydslTestModule.class)
public class TransactionManagerQuerydslTest {
@Inject
DataSource dataSource;
// exception release checks
@Test
public void check_that_connection_is_released_after_exception_during_select_query() throws SQLException {
TransactionInstancesHolder testInstancesHolder = new TransactionInstancesHolder(dataSource);
try {
testInstancesHolder
.getTransactionManager()
.selectQuery();
throw new Exception();
} catch (Exception e) {
// as expected
}
assertThat(testInstancesHolder.getMockedDataSource().isConnectionAvailable()).isTrue();
}
@Test
public void check_that_connection_is_released_after_exception_during_delete_query() throws SQLException {
TransactionInstancesHolder testInstancesHolder = new TransactionInstancesHolder(dataSource);
try {
testInstancesHolder
.getTransactionManager() | // Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
// public class DbQuerydslTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// install(new GuiceConfModule());
// install(new DataSourceModule());
// install(new GuiceDbTestModule());
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/QUser.java
// @Generated("com.querydsl.sql.codegen.MetaDataSerializer")
// public class QUser extends com.querydsl.sql.RelationalPathBase<User> {
//
// private static final long serialVersionUID = -50309753;
//
// public static final QUser user = new QUser("USER");
//
// public final BooleanPath active = createBoolean("active");
//
// public final DateTimePath<java.time.LocalDateTime> creationDate = createDateTime("creationDate", java.time.LocalDateTime.class);
//
// public final NumberPath<Long> id = createNumber("id", Long.class);
//
// public final StringPath name = createString("name");
//
// public final com.querydsl.sql.PrimaryKey<User> constraint2 = createPrimaryKey(id);
//
// public QUser(String variable) {
// super(User.class, forVariable(variable), "PUBLIC", "USER");
// addMetadata();
// }
//
// public QUser(String variable, String schema, String table) {
// super(User.class, forVariable(variable), schema, table);
// addMetadata();
// }
//
// public QUser(Path<? extends User> path) {
// super(path.getType(), path.getMetadata(), "PUBLIC", "USER");
// addMetadata();
// }
//
// public QUser(PathMetadata metadata) {
// super(User.class, metadata, "PUBLIC", "USER");
// addMetadata();
// }
//
// public void addMetadata() {
// addMetadata(active, ColumnMetadata.named("ACTIVE").withIndex(3).ofType(Types.BOOLEAN).withSize(1));
// addMetadata(creationDate, ColumnMetadata.named("CREATION_DATE").withIndex(4).ofType(Types.TIMESTAMP).withSize(23).withDigits(10));
// addMetadata(id, ColumnMetadata.named("ID").withIndex(1).ofType(Types.BIGINT).withSize(19).notNull());
// addMetadata(name, ColumnMetadata.named("NAME").withIndex(2).ofType(Types.VARCHAR).withSize(255));
// }
//
// }
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydslTest.java
import static org.assertj.core.api.Assertions.assertThat;
import java.sql.SQLException;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.carlosbecker.guice.GuiceModules;
import com.carlosbecker.guice.GuiceTestRunner;
import com.coreoz.plume.db.querydsl.DbQuerydslTestModule;
import com.coreoz.plume.db.querydsl.db.QUser;
package com.coreoz.plume.db.querydsl.transaction;
@RunWith(GuiceTestRunner.class)
@GuiceModules(DbQuerydslTestModule.class)
public class TransactionManagerQuerydslTest {
@Inject
DataSource dataSource;
// exception release checks
@Test
public void check_that_connection_is_released_after_exception_during_select_query() throws SQLException {
TransactionInstancesHolder testInstancesHolder = new TransactionInstancesHolder(dataSource);
try {
testInstancesHolder
.getTransactionManager()
.selectQuery();
throw new Exception();
} catch (Exception e) {
// as expected
}
assertThat(testInstancesHolder.getMockedDataSource().isConnectionAvailable()).isTrue();
}
@Test
public void check_that_connection_is_released_after_exception_during_delete_query() throws SQLException {
TransactionInstancesHolder testInstancesHolder = new TransactionInstancesHolder(dataSource);
try {
testInstancesHolder
.getTransactionManager() | .delete(QUser.user); |
Coreoz/Plume | plume-conf/src/main/java/com/coreoz/plume/conf/guice/GuiceConfModule.java | // Path: plume-conf/src/main/java/com/coreoz/plume/conf/ConfigProvider.java
// @Singleton
// public class ConfigProvider implements Provider<Config> {
//
// private Config config;
//
// @Inject
// public ConfigProvider() {
// this.config = ConfigFactory.load();
// }
//
// @Override
// public Config get() {
// return config;
// }
//
// }
| import com.coreoz.plume.conf.ConfigProvider;
import com.google.inject.AbstractModule;
import com.typesafe.config.Config; | package com.coreoz.plume.conf.guice;
public class GuiceConfModule extends AbstractModule {
@Override
protected void configure() { | // Path: plume-conf/src/main/java/com/coreoz/plume/conf/ConfigProvider.java
// @Singleton
// public class ConfigProvider implements Provider<Config> {
//
// private Config config;
//
// @Inject
// public ConfigProvider() {
// this.config = ConfigFactory.load();
// }
//
// @Override
// public Config get() {
// return config;
// }
//
// }
// Path: plume-conf/src/main/java/com/coreoz/plume/conf/guice/GuiceConfModule.java
import com.coreoz.plume.conf.ConfigProvider;
import com.google.inject.AbstractModule;
import com.typesafe.config.Config;
package com.coreoz.plume.conf.guice;
public class GuiceConfModule extends AbstractModule {
@Override
protected void configure() { | bind(Config.class).toProvider(ConfigProvider.class); |
Coreoz/Plume | plume-db-test/src/main/java/com/coreoz/plume/db/guice/GuiceDbTestModule.java | // Path: plume-db-test/src/main/java/com/coreoz/plume/db/InitializeDatabase.java
// @Singleton
// public class InitializeDatabase {
//
// @Inject
// public InitializeDatabase(DataSource dataSource) {
// Flyway
// .configure()
// .dataSource(dataSource)
// .outOfOrder(true)
// .load()
// .migrate();
// }
//
// }
| import com.coreoz.plume.db.InitializeDatabase;
import com.google.inject.AbstractModule; | package com.coreoz.plume.db.guice;
public class GuiceDbTestModule extends AbstractModule {
@Override
protected void configure() { | // Path: plume-db-test/src/main/java/com/coreoz/plume/db/InitializeDatabase.java
// @Singleton
// public class InitializeDatabase {
//
// @Inject
// public InitializeDatabase(DataSource dataSource) {
// Flyway
// .configure()
// .dataSource(dataSource)
// .outOfOrder(true)
// .load()
// .migrate();
// }
//
// }
// Path: plume-db-test/src/main/java/com/coreoz/plume/db/guice/GuiceDbTestModule.java
import com.coreoz.plume.db.InitializeDatabase;
import com.google.inject.AbstractModule;
package com.coreoz.plume.db.guice;
public class GuiceDbTestModule extends AbstractModule {
@Override
protected void configure() { | bind(InitializeDatabase.class).asEagerSingleton(); |
Coreoz/Plume | plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydslTest.java | // Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
// public class DbQuerydslTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// install(new GuiceConfModule());
// install(new DataSourceModule());
// install(new GuiceDbTestModule());
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/QUser.java
// @Generated("com.querydsl.sql.codegen.MetaDataSerializer")
// public class QUser extends com.querydsl.sql.RelationalPathBase<User> {
//
// private static final long serialVersionUID = -50309753;
//
// public static final QUser user = new QUser("USER");
//
// public final BooleanPath active = createBoolean("active");
//
// public final DateTimePath<java.time.LocalDateTime> creationDate = createDateTime("creationDate", java.time.LocalDateTime.class);
//
// public final NumberPath<Long> id = createNumber("id", Long.class);
//
// public final StringPath name = createString("name");
//
// public final com.querydsl.sql.PrimaryKey<User> constraint2 = createPrimaryKey(id);
//
// public QUser(String variable) {
// super(User.class, forVariable(variable), "PUBLIC", "USER");
// addMetadata();
// }
//
// public QUser(String variable, String schema, String table) {
// super(User.class, forVariable(variable), schema, table);
// addMetadata();
// }
//
// public QUser(Path<? extends User> path) {
// super(path.getType(), path.getMetadata(), "PUBLIC", "USER");
// addMetadata();
// }
//
// public QUser(PathMetadata metadata) {
// super(User.class, metadata, "PUBLIC", "USER");
// addMetadata();
// }
//
// public void addMetadata() {
// addMetadata(active, ColumnMetadata.named("ACTIVE").withIndex(3).ofType(Types.BOOLEAN).withSize(1));
// addMetadata(creationDate, ColumnMetadata.named("CREATION_DATE").withIndex(4).ofType(Types.TIMESTAMP).withSize(23).withDigits(10));
// addMetadata(id, ColumnMetadata.named("ID").withIndex(1).ofType(Types.BIGINT).withSize(19).notNull());
// addMetadata(name, ColumnMetadata.named("NAME").withIndex(2).ofType(Types.VARCHAR).withSize(255));
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/User.java
// @Generated("com.coreoz.plume.db.querydsl.generation.IdBeanSerializer")
// public class User extends com.coreoz.plume.db.querydsl.crud.CrudEntityQuerydsl {
//
// @Column("ACTIVE")
// private Boolean active;
//
// @Column("CREATION_DATE")
// private java.time.LocalDateTime creationDate;
//
// @Column("ID")
// private Long id;
//
// @Column("NAME")
// private String name;
//
// public Boolean getActive() {
// return active;
// }
//
// public void setActive(Boolean active) {
// this.active = active;
// }
//
// public java.time.LocalDateTime getCreationDate() {
// return creationDate;
// }
//
// public void setCreationDate(java.time.LocalDateTime creationDate) {
// this.creationDate = creationDate;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (id == null) {
// return super.equals(o);
// }
// if (!(o instanceof User)) {
// return false;
// }
// User obj = (User) o;
// return id.equals(obj.id);
// }
//
// @Override
// public int hashCode() {
// if (id == null) {
// return super.hashCode();
// }
// final int prime = 31;
// int result = 1;
// result = prime * result + id.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "User#" + id;
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/UserDao.java
// @Singleton
// public class UserDao extends CrudDaoQuerydsl<User> {
//
// @Inject
// public UserDao(TransactionManagerQuerydsl transactionManagerQuerydsl) {
// super(transactionManagerQuerydsl, QUser.user);
// }
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import javax.inject.Inject;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.carlosbecker.guice.GuiceModules;
import com.carlosbecker.guice.GuiceTestRunner;
import com.coreoz.plume.db.querydsl.DbQuerydslTestModule;
import com.coreoz.plume.db.querydsl.db.QUser;
import com.coreoz.plume.db.querydsl.db.User;
import com.coreoz.plume.db.querydsl.db.UserDao; | package com.coreoz.plume.db.querydsl.crud;
@RunWith(GuiceTestRunner.class)
@GuiceModules(DbQuerydslTestModule.class)
public class CrudDaoQuerydslTest {
@Inject | // Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
// public class DbQuerydslTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// install(new GuiceConfModule());
// install(new DataSourceModule());
// install(new GuiceDbTestModule());
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/QUser.java
// @Generated("com.querydsl.sql.codegen.MetaDataSerializer")
// public class QUser extends com.querydsl.sql.RelationalPathBase<User> {
//
// private static final long serialVersionUID = -50309753;
//
// public static final QUser user = new QUser("USER");
//
// public final BooleanPath active = createBoolean("active");
//
// public final DateTimePath<java.time.LocalDateTime> creationDate = createDateTime("creationDate", java.time.LocalDateTime.class);
//
// public final NumberPath<Long> id = createNumber("id", Long.class);
//
// public final StringPath name = createString("name");
//
// public final com.querydsl.sql.PrimaryKey<User> constraint2 = createPrimaryKey(id);
//
// public QUser(String variable) {
// super(User.class, forVariable(variable), "PUBLIC", "USER");
// addMetadata();
// }
//
// public QUser(String variable, String schema, String table) {
// super(User.class, forVariable(variable), schema, table);
// addMetadata();
// }
//
// public QUser(Path<? extends User> path) {
// super(path.getType(), path.getMetadata(), "PUBLIC", "USER");
// addMetadata();
// }
//
// public QUser(PathMetadata metadata) {
// super(User.class, metadata, "PUBLIC", "USER");
// addMetadata();
// }
//
// public void addMetadata() {
// addMetadata(active, ColumnMetadata.named("ACTIVE").withIndex(3).ofType(Types.BOOLEAN).withSize(1));
// addMetadata(creationDate, ColumnMetadata.named("CREATION_DATE").withIndex(4).ofType(Types.TIMESTAMP).withSize(23).withDigits(10));
// addMetadata(id, ColumnMetadata.named("ID").withIndex(1).ofType(Types.BIGINT).withSize(19).notNull());
// addMetadata(name, ColumnMetadata.named("NAME").withIndex(2).ofType(Types.VARCHAR).withSize(255));
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/User.java
// @Generated("com.coreoz.plume.db.querydsl.generation.IdBeanSerializer")
// public class User extends com.coreoz.plume.db.querydsl.crud.CrudEntityQuerydsl {
//
// @Column("ACTIVE")
// private Boolean active;
//
// @Column("CREATION_DATE")
// private java.time.LocalDateTime creationDate;
//
// @Column("ID")
// private Long id;
//
// @Column("NAME")
// private String name;
//
// public Boolean getActive() {
// return active;
// }
//
// public void setActive(Boolean active) {
// this.active = active;
// }
//
// public java.time.LocalDateTime getCreationDate() {
// return creationDate;
// }
//
// public void setCreationDate(java.time.LocalDateTime creationDate) {
// this.creationDate = creationDate;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (id == null) {
// return super.equals(o);
// }
// if (!(o instanceof User)) {
// return false;
// }
// User obj = (User) o;
// return id.equals(obj.id);
// }
//
// @Override
// public int hashCode() {
// if (id == null) {
// return super.hashCode();
// }
// final int prime = 31;
// int result = 1;
// result = prime * result + id.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "User#" + id;
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/UserDao.java
// @Singleton
// public class UserDao extends CrudDaoQuerydsl<User> {
//
// @Inject
// public UserDao(TransactionManagerQuerydsl transactionManagerQuerydsl) {
// super(transactionManagerQuerydsl, QUser.user);
// }
//
// }
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydslTest.java
import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import javax.inject.Inject;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.carlosbecker.guice.GuiceModules;
import com.carlosbecker.guice.GuiceTestRunner;
import com.coreoz.plume.db.querydsl.DbQuerydslTestModule;
import com.coreoz.plume.db.querydsl.db.QUser;
import com.coreoz.plume.db.querydsl.db.User;
import com.coreoz.plume.db.querydsl.db.UserDao;
package com.coreoz.plume.db.querydsl.crud;
@RunWith(GuiceTestRunner.class)
@GuiceModules(DbQuerydslTestModule.class)
public class CrudDaoQuerydslTest {
@Inject | UserDao userDao; |
Coreoz/Plume | plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydslTest.java | // Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
// public class DbQuerydslTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// install(new GuiceConfModule());
// install(new DataSourceModule());
// install(new GuiceDbTestModule());
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/QUser.java
// @Generated("com.querydsl.sql.codegen.MetaDataSerializer")
// public class QUser extends com.querydsl.sql.RelationalPathBase<User> {
//
// private static final long serialVersionUID = -50309753;
//
// public static final QUser user = new QUser("USER");
//
// public final BooleanPath active = createBoolean("active");
//
// public final DateTimePath<java.time.LocalDateTime> creationDate = createDateTime("creationDate", java.time.LocalDateTime.class);
//
// public final NumberPath<Long> id = createNumber("id", Long.class);
//
// public final StringPath name = createString("name");
//
// public final com.querydsl.sql.PrimaryKey<User> constraint2 = createPrimaryKey(id);
//
// public QUser(String variable) {
// super(User.class, forVariable(variable), "PUBLIC", "USER");
// addMetadata();
// }
//
// public QUser(String variable, String schema, String table) {
// super(User.class, forVariable(variable), schema, table);
// addMetadata();
// }
//
// public QUser(Path<? extends User> path) {
// super(path.getType(), path.getMetadata(), "PUBLIC", "USER");
// addMetadata();
// }
//
// public QUser(PathMetadata metadata) {
// super(User.class, metadata, "PUBLIC", "USER");
// addMetadata();
// }
//
// public void addMetadata() {
// addMetadata(active, ColumnMetadata.named("ACTIVE").withIndex(3).ofType(Types.BOOLEAN).withSize(1));
// addMetadata(creationDate, ColumnMetadata.named("CREATION_DATE").withIndex(4).ofType(Types.TIMESTAMP).withSize(23).withDigits(10));
// addMetadata(id, ColumnMetadata.named("ID").withIndex(1).ofType(Types.BIGINT).withSize(19).notNull());
// addMetadata(name, ColumnMetadata.named("NAME").withIndex(2).ofType(Types.VARCHAR).withSize(255));
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/User.java
// @Generated("com.coreoz.plume.db.querydsl.generation.IdBeanSerializer")
// public class User extends com.coreoz.plume.db.querydsl.crud.CrudEntityQuerydsl {
//
// @Column("ACTIVE")
// private Boolean active;
//
// @Column("CREATION_DATE")
// private java.time.LocalDateTime creationDate;
//
// @Column("ID")
// private Long id;
//
// @Column("NAME")
// private String name;
//
// public Boolean getActive() {
// return active;
// }
//
// public void setActive(Boolean active) {
// this.active = active;
// }
//
// public java.time.LocalDateTime getCreationDate() {
// return creationDate;
// }
//
// public void setCreationDate(java.time.LocalDateTime creationDate) {
// this.creationDate = creationDate;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (id == null) {
// return super.equals(o);
// }
// if (!(o instanceof User)) {
// return false;
// }
// User obj = (User) o;
// return id.equals(obj.id);
// }
//
// @Override
// public int hashCode() {
// if (id == null) {
// return super.hashCode();
// }
// final int prime = 31;
// int result = 1;
// result = prime * result + id.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "User#" + id;
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/UserDao.java
// @Singleton
// public class UserDao extends CrudDaoQuerydsl<User> {
//
// @Inject
// public UserDao(TransactionManagerQuerydsl transactionManagerQuerydsl) {
// super(transactionManagerQuerydsl, QUser.user);
// }
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import javax.inject.Inject;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.carlosbecker.guice.GuiceModules;
import com.carlosbecker.guice.GuiceTestRunner;
import com.coreoz.plume.db.querydsl.DbQuerydslTestModule;
import com.coreoz.plume.db.querydsl.db.QUser;
import com.coreoz.plume.db.querydsl.db.User;
import com.coreoz.plume.db.querydsl.db.UserDao; | package com.coreoz.plume.db.querydsl.crud;
@RunWith(GuiceTestRunner.class)
@GuiceModules(DbQuerydslTestModule.class)
public class CrudDaoQuerydslTest {
@Inject
UserDao userDao;
@Test
public void should_list_users() { | // Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/DbQuerydslTestModule.java
// public class DbQuerydslTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// install(new GuiceConfModule());
// install(new DataSourceModule());
// install(new GuiceDbTestModule());
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/QUser.java
// @Generated("com.querydsl.sql.codegen.MetaDataSerializer")
// public class QUser extends com.querydsl.sql.RelationalPathBase<User> {
//
// private static final long serialVersionUID = -50309753;
//
// public static final QUser user = new QUser("USER");
//
// public final BooleanPath active = createBoolean("active");
//
// public final DateTimePath<java.time.LocalDateTime> creationDate = createDateTime("creationDate", java.time.LocalDateTime.class);
//
// public final NumberPath<Long> id = createNumber("id", Long.class);
//
// public final StringPath name = createString("name");
//
// public final com.querydsl.sql.PrimaryKey<User> constraint2 = createPrimaryKey(id);
//
// public QUser(String variable) {
// super(User.class, forVariable(variable), "PUBLIC", "USER");
// addMetadata();
// }
//
// public QUser(String variable, String schema, String table) {
// super(User.class, forVariable(variable), schema, table);
// addMetadata();
// }
//
// public QUser(Path<? extends User> path) {
// super(path.getType(), path.getMetadata(), "PUBLIC", "USER");
// addMetadata();
// }
//
// public QUser(PathMetadata metadata) {
// super(User.class, metadata, "PUBLIC", "USER");
// addMetadata();
// }
//
// public void addMetadata() {
// addMetadata(active, ColumnMetadata.named("ACTIVE").withIndex(3).ofType(Types.BOOLEAN).withSize(1));
// addMetadata(creationDate, ColumnMetadata.named("CREATION_DATE").withIndex(4).ofType(Types.TIMESTAMP).withSize(23).withDigits(10));
// addMetadata(id, ColumnMetadata.named("ID").withIndex(1).ofType(Types.BIGINT).withSize(19).notNull());
// addMetadata(name, ColumnMetadata.named("NAME").withIndex(2).ofType(Types.VARCHAR).withSize(255));
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/User.java
// @Generated("com.coreoz.plume.db.querydsl.generation.IdBeanSerializer")
// public class User extends com.coreoz.plume.db.querydsl.crud.CrudEntityQuerydsl {
//
// @Column("ACTIVE")
// private Boolean active;
//
// @Column("CREATION_DATE")
// private java.time.LocalDateTime creationDate;
//
// @Column("ID")
// private Long id;
//
// @Column("NAME")
// private String name;
//
// public Boolean getActive() {
// return active;
// }
//
// public void setActive(Boolean active) {
// this.active = active;
// }
//
// public java.time.LocalDateTime getCreationDate() {
// return creationDate;
// }
//
// public void setCreationDate(java.time.LocalDateTime creationDate) {
// this.creationDate = creationDate;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (id == null) {
// return super.equals(o);
// }
// if (!(o instanceof User)) {
// return false;
// }
// User obj = (User) o;
// return id.equals(obj.id);
// }
//
// @Override
// public int hashCode() {
// if (id == null) {
// return super.hashCode();
// }
// final int prime = 31;
// int result = 1;
// result = prime * result + id.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "User#" + id;
// }
//
// }
//
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/UserDao.java
// @Singleton
// public class UserDao extends CrudDaoQuerydsl<User> {
//
// @Inject
// public UserDao(TransactionManagerQuerydsl transactionManagerQuerydsl) {
// super(transactionManagerQuerydsl, QUser.user);
// }
//
// }
// Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydslTest.java
import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import javax.inject.Inject;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.carlosbecker.guice.GuiceModules;
import com.carlosbecker.guice.GuiceTestRunner;
import com.coreoz.plume.db.querydsl.DbQuerydslTestModule;
import com.coreoz.plume.db.querydsl.db.QUser;
import com.coreoz.plume.db.querydsl.db.User;
import com.coreoz.plume.db.querydsl.db.UserDao;
package com.coreoz.plume.db.querydsl.crud;
@RunWith(GuiceTestRunner.class)
@GuiceModules(DbQuerydslTestModule.class)
public class CrudDaoQuerydslTest {
@Inject
UserDao userDao;
@Test
public void should_list_users() { | User user = new User(); |
Coreoz/Plume | plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/dagger/DaggerQuerydslModule.java | // Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydsl.java
// @Singleton
// public class TransactionManagerQuerydsl extends TransactionManager {
//
// private final Configuration querydslConfiguration;
//
// @Inject
// public TransactionManagerQuerydsl(Config config) {
// this(config, "db");
// }
//
// public TransactionManagerQuerydsl(Config config, String prefix) {
// super(config, prefix);
//
// String dialect = config.getString(prefix + ".dialect");
// this.querydslConfiguration = new Configuration(QuerydslTemplates.valueOf(dialect).sqlTemplates());
// }
//
// public TransactionManagerQuerydsl(DataSource dataSource, Configuration querydslConfiguration) {
// super(dataSource);
//
// this.querydslConfiguration = querydslConfiguration;
// }
//
// // API
//
// public <Q> SQLQuery<Q> selectQuery() {
// SQLQuery<Q> query = new SQLQuery<>(getConnectionProvider(), querydslConfiguration);
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// public <Q> SQLQuery<Q> selectQuery(Connection connection) {
// return new SQLQuery<>(connection, querydslConfiguration);
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path) {
// return autoCloseQuery(new SQLDeleteClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path, Connection connection) {
// return new SQLDeleteClause(connection, querydslConfiguration, path);
// }
//
// public SQLInsertClause insert(RelationalPath<?> path) {
// return autoCloseQuery(new SQLInsertClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLInsertClause insert(RelationalPath<?> path, Connection connection) {
// return new SQLInsertClause(connection, querydslConfiguration, path);
// }
//
// public SQLUpdateClause update(RelationalPath<?> path) {
// return autoCloseQuery(new SQLUpdateClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLUpdateClause update(RelationalPath<?> path, Connection connection) {
// return new SQLUpdateClause(connection, querydslConfiguration, path);
// }
//
// // internal
//
// private <T extends AbstractSQLClause<?>> T autoCloseQuery(T query) {
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// private Supplier<Connection> getConnectionProvider() {
// return () -> {
// try {
// return dataSource().getConnection();
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// };
// }
//
// }
//
// Path: plume-db/src/main/java/com/coreoz/plume/db/transaction/TransactionManager.java
// @Singleton
// public class TransactionManager {
//
// private final DataSource dataSource;
//
// @Inject
// public TransactionManager(Config config) {
// this(config, "db");
// }
//
// public TransactionManager(Config config, String prefix) {
// this(HikariDataSources.fromConfig(config, prefix + ".hikari"));
// }
//
// public TransactionManager(DataSource dataSource) {
// this.dataSource = dataSource;
// }
//
// // API
//
// public DataSource dataSource() {
// return dataSource;
// }
//
// public <T> T executeAndReturn(Function<Connection, T> toExecuteOnDb) {
// Connection connection = null;
// Boolean initialAutoCommit = null;
// try {
// connection = dataSource.getConnection();
// initialAutoCommit = connection.getAutoCommit();
// connection.setAutoCommit(false);
// T result = toExecuteOnDb.apply(connection);
// connection.commit();
// return result;
// } catch(Throwable e) {
// try {
// if(connection != null) {
// connection.rollback();
// }
// } catch (Throwable e2) {
// // never mind if the connection cannot be rolled back
// }
// Throwables.throwIfUnchecked(e);
// throw new RuntimeException(e);
// } finally {
// if(connection != null) {
// try {
// if(initialAutoCommit != null) {
// connection.setAutoCommit(initialAutoCommit);
// }
// connection.close();
// } catch (SQLException e) {
// // never mind if the connection cannot be closed
// }
// }
// }
// }
//
// public void execute(Consumer<Connection> toExecuteOnDb) {
// executeAndReturn(connection -> {
// toExecuteOnDb.accept(connection);
// return null;
// });
// }
//
// }
| import javax.inject.Singleton;
import com.coreoz.plume.db.querydsl.transaction.TransactionManagerQuerydsl;
import com.coreoz.plume.db.transaction.TransactionManager;
import dagger.Module;
import dagger.Provides; | package com.coreoz.plume.db.querydsl.dagger;
@Module
public class DaggerQuerydslModule {
@Provides
@Singleton | // Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydsl.java
// @Singleton
// public class TransactionManagerQuerydsl extends TransactionManager {
//
// private final Configuration querydslConfiguration;
//
// @Inject
// public TransactionManagerQuerydsl(Config config) {
// this(config, "db");
// }
//
// public TransactionManagerQuerydsl(Config config, String prefix) {
// super(config, prefix);
//
// String dialect = config.getString(prefix + ".dialect");
// this.querydslConfiguration = new Configuration(QuerydslTemplates.valueOf(dialect).sqlTemplates());
// }
//
// public TransactionManagerQuerydsl(DataSource dataSource, Configuration querydslConfiguration) {
// super(dataSource);
//
// this.querydslConfiguration = querydslConfiguration;
// }
//
// // API
//
// public <Q> SQLQuery<Q> selectQuery() {
// SQLQuery<Q> query = new SQLQuery<>(getConnectionProvider(), querydslConfiguration);
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// public <Q> SQLQuery<Q> selectQuery(Connection connection) {
// return new SQLQuery<>(connection, querydslConfiguration);
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path) {
// return autoCloseQuery(new SQLDeleteClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path, Connection connection) {
// return new SQLDeleteClause(connection, querydslConfiguration, path);
// }
//
// public SQLInsertClause insert(RelationalPath<?> path) {
// return autoCloseQuery(new SQLInsertClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLInsertClause insert(RelationalPath<?> path, Connection connection) {
// return new SQLInsertClause(connection, querydslConfiguration, path);
// }
//
// public SQLUpdateClause update(RelationalPath<?> path) {
// return autoCloseQuery(new SQLUpdateClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLUpdateClause update(RelationalPath<?> path, Connection connection) {
// return new SQLUpdateClause(connection, querydslConfiguration, path);
// }
//
// // internal
//
// private <T extends AbstractSQLClause<?>> T autoCloseQuery(T query) {
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// private Supplier<Connection> getConnectionProvider() {
// return () -> {
// try {
// return dataSource().getConnection();
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// };
// }
//
// }
//
// Path: plume-db/src/main/java/com/coreoz/plume/db/transaction/TransactionManager.java
// @Singleton
// public class TransactionManager {
//
// private final DataSource dataSource;
//
// @Inject
// public TransactionManager(Config config) {
// this(config, "db");
// }
//
// public TransactionManager(Config config, String prefix) {
// this(HikariDataSources.fromConfig(config, prefix + ".hikari"));
// }
//
// public TransactionManager(DataSource dataSource) {
// this.dataSource = dataSource;
// }
//
// // API
//
// public DataSource dataSource() {
// return dataSource;
// }
//
// public <T> T executeAndReturn(Function<Connection, T> toExecuteOnDb) {
// Connection connection = null;
// Boolean initialAutoCommit = null;
// try {
// connection = dataSource.getConnection();
// initialAutoCommit = connection.getAutoCommit();
// connection.setAutoCommit(false);
// T result = toExecuteOnDb.apply(connection);
// connection.commit();
// return result;
// } catch(Throwable e) {
// try {
// if(connection != null) {
// connection.rollback();
// }
// } catch (Throwable e2) {
// // never mind if the connection cannot be rolled back
// }
// Throwables.throwIfUnchecked(e);
// throw new RuntimeException(e);
// } finally {
// if(connection != null) {
// try {
// if(initialAutoCommit != null) {
// connection.setAutoCommit(initialAutoCommit);
// }
// connection.close();
// } catch (SQLException e) {
// // never mind if the connection cannot be closed
// }
// }
// }
// }
//
// public void execute(Consumer<Connection> toExecuteOnDb) {
// executeAndReturn(connection -> {
// toExecuteOnDb.accept(connection);
// return null;
// });
// }
//
// }
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/dagger/DaggerQuerydslModule.java
import javax.inject.Singleton;
import com.coreoz.plume.db.querydsl.transaction.TransactionManagerQuerydsl;
import com.coreoz.plume.db.transaction.TransactionManager;
import dagger.Module;
import dagger.Provides;
package com.coreoz.plume.db.querydsl.dagger;
@Module
public class DaggerQuerydslModule {
@Provides
@Singleton | static TransactionManager provideTransactionManager(TransactionManagerQuerydsl transactionManagerQuerydsl) { |
Coreoz/Plume | plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/dagger/DaggerQuerydslModule.java | // Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydsl.java
// @Singleton
// public class TransactionManagerQuerydsl extends TransactionManager {
//
// private final Configuration querydslConfiguration;
//
// @Inject
// public TransactionManagerQuerydsl(Config config) {
// this(config, "db");
// }
//
// public TransactionManagerQuerydsl(Config config, String prefix) {
// super(config, prefix);
//
// String dialect = config.getString(prefix + ".dialect");
// this.querydslConfiguration = new Configuration(QuerydslTemplates.valueOf(dialect).sqlTemplates());
// }
//
// public TransactionManagerQuerydsl(DataSource dataSource, Configuration querydslConfiguration) {
// super(dataSource);
//
// this.querydslConfiguration = querydslConfiguration;
// }
//
// // API
//
// public <Q> SQLQuery<Q> selectQuery() {
// SQLQuery<Q> query = new SQLQuery<>(getConnectionProvider(), querydslConfiguration);
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// public <Q> SQLQuery<Q> selectQuery(Connection connection) {
// return new SQLQuery<>(connection, querydslConfiguration);
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path) {
// return autoCloseQuery(new SQLDeleteClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path, Connection connection) {
// return new SQLDeleteClause(connection, querydslConfiguration, path);
// }
//
// public SQLInsertClause insert(RelationalPath<?> path) {
// return autoCloseQuery(new SQLInsertClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLInsertClause insert(RelationalPath<?> path, Connection connection) {
// return new SQLInsertClause(connection, querydslConfiguration, path);
// }
//
// public SQLUpdateClause update(RelationalPath<?> path) {
// return autoCloseQuery(new SQLUpdateClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLUpdateClause update(RelationalPath<?> path, Connection connection) {
// return new SQLUpdateClause(connection, querydslConfiguration, path);
// }
//
// // internal
//
// private <T extends AbstractSQLClause<?>> T autoCloseQuery(T query) {
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// private Supplier<Connection> getConnectionProvider() {
// return () -> {
// try {
// return dataSource().getConnection();
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// };
// }
//
// }
//
// Path: plume-db/src/main/java/com/coreoz/plume/db/transaction/TransactionManager.java
// @Singleton
// public class TransactionManager {
//
// private final DataSource dataSource;
//
// @Inject
// public TransactionManager(Config config) {
// this(config, "db");
// }
//
// public TransactionManager(Config config, String prefix) {
// this(HikariDataSources.fromConfig(config, prefix + ".hikari"));
// }
//
// public TransactionManager(DataSource dataSource) {
// this.dataSource = dataSource;
// }
//
// // API
//
// public DataSource dataSource() {
// return dataSource;
// }
//
// public <T> T executeAndReturn(Function<Connection, T> toExecuteOnDb) {
// Connection connection = null;
// Boolean initialAutoCommit = null;
// try {
// connection = dataSource.getConnection();
// initialAutoCommit = connection.getAutoCommit();
// connection.setAutoCommit(false);
// T result = toExecuteOnDb.apply(connection);
// connection.commit();
// return result;
// } catch(Throwable e) {
// try {
// if(connection != null) {
// connection.rollback();
// }
// } catch (Throwable e2) {
// // never mind if the connection cannot be rolled back
// }
// Throwables.throwIfUnchecked(e);
// throw new RuntimeException(e);
// } finally {
// if(connection != null) {
// try {
// if(initialAutoCommit != null) {
// connection.setAutoCommit(initialAutoCommit);
// }
// connection.close();
// } catch (SQLException e) {
// // never mind if the connection cannot be closed
// }
// }
// }
// }
//
// public void execute(Consumer<Connection> toExecuteOnDb) {
// executeAndReturn(connection -> {
// toExecuteOnDb.accept(connection);
// return null;
// });
// }
//
// }
| import javax.inject.Singleton;
import com.coreoz.plume.db.querydsl.transaction.TransactionManagerQuerydsl;
import com.coreoz.plume.db.transaction.TransactionManager;
import dagger.Module;
import dagger.Provides; | package com.coreoz.plume.db.querydsl.dagger;
@Module
public class DaggerQuerydslModule {
@Provides
@Singleton | // Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydsl.java
// @Singleton
// public class TransactionManagerQuerydsl extends TransactionManager {
//
// private final Configuration querydslConfiguration;
//
// @Inject
// public TransactionManagerQuerydsl(Config config) {
// this(config, "db");
// }
//
// public TransactionManagerQuerydsl(Config config, String prefix) {
// super(config, prefix);
//
// String dialect = config.getString(prefix + ".dialect");
// this.querydslConfiguration = new Configuration(QuerydslTemplates.valueOf(dialect).sqlTemplates());
// }
//
// public TransactionManagerQuerydsl(DataSource dataSource, Configuration querydslConfiguration) {
// super(dataSource);
//
// this.querydslConfiguration = querydslConfiguration;
// }
//
// // API
//
// public <Q> SQLQuery<Q> selectQuery() {
// SQLQuery<Q> query = new SQLQuery<>(getConnectionProvider(), querydslConfiguration);
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// public <Q> SQLQuery<Q> selectQuery(Connection connection) {
// return new SQLQuery<>(connection, querydslConfiguration);
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path) {
// return autoCloseQuery(new SQLDeleteClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLDeleteClause delete(RelationalPath<?> path, Connection connection) {
// return new SQLDeleteClause(connection, querydslConfiguration, path);
// }
//
// public SQLInsertClause insert(RelationalPath<?> path) {
// return autoCloseQuery(new SQLInsertClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLInsertClause insert(RelationalPath<?> path, Connection connection) {
// return new SQLInsertClause(connection, querydslConfiguration, path);
// }
//
// public SQLUpdateClause update(RelationalPath<?> path) {
// return autoCloseQuery(new SQLUpdateClause(getConnectionProvider(), querydslConfiguration, path));
// }
//
// public SQLUpdateClause update(RelationalPath<?> path, Connection connection) {
// return new SQLUpdateClause(connection, querydslConfiguration, path);
// }
//
// // internal
//
// private <T extends AbstractSQLClause<?>> T autoCloseQuery(T query) {
// query.addListener(SQLCloseListener.DEFAULT);
// return query;
// }
//
// private Supplier<Connection> getConnectionProvider() {
// return () -> {
// try {
// return dataSource().getConnection();
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
// };
// }
//
// }
//
// Path: plume-db/src/main/java/com/coreoz/plume/db/transaction/TransactionManager.java
// @Singleton
// public class TransactionManager {
//
// private final DataSource dataSource;
//
// @Inject
// public TransactionManager(Config config) {
// this(config, "db");
// }
//
// public TransactionManager(Config config, String prefix) {
// this(HikariDataSources.fromConfig(config, prefix + ".hikari"));
// }
//
// public TransactionManager(DataSource dataSource) {
// this.dataSource = dataSource;
// }
//
// // API
//
// public DataSource dataSource() {
// return dataSource;
// }
//
// public <T> T executeAndReturn(Function<Connection, T> toExecuteOnDb) {
// Connection connection = null;
// Boolean initialAutoCommit = null;
// try {
// connection = dataSource.getConnection();
// initialAutoCommit = connection.getAutoCommit();
// connection.setAutoCommit(false);
// T result = toExecuteOnDb.apply(connection);
// connection.commit();
// return result;
// } catch(Throwable e) {
// try {
// if(connection != null) {
// connection.rollback();
// }
// } catch (Throwable e2) {
// // never mind if the connection cannot be rolled back
// }
// Throwables.throwIfUnchecked(e);
// throw new RuntimeException(e);
// } finally {
// if(connection != null) {
// try {
// if(initialAutoCommit != null) {
// connection.setAutoCommit(initialAutoCommit);
// }
// connection.close();
// } catch (SQLException e) {
// // never mind if the connection cannot be closed
// }
// }
// }
// }
//
// public void execute(Consumer<Connection> toExecuteOnDb) {
// executeAndReturn(connection -> {
// toExecuteOnDb.accept(connection);
// return null;
// });
// }
//
// }
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/dagger/DaggerQuerydslModule.java
import javax.inject.Singleton;
import com.coreoz.plume.db.querydsl.transaction.TransactionManagerQuerydsl;
import com.coreoz.plume.db.transaction.TransactionManager;
import dagger.Module;
import dagger.Provides;
package com.coreoz.plume.db.querydsl.dagger;
@Module
public class DaggerQuerydslModule {
@Provides
@Singleton | static TransactionManager provideTransactionManager(TransactionManagerQuerydsl transactionManagerQuerydsl) { |