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
childe/hangout
hangout-output-plugins/hangout-output-plugins-elasticsearch/src/main/java/com/ctrip/ops/sysdev/outputs/Elasticsearch.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseOutput.java // @Log4j2 // public abstract class BaseOutput extends Base { // protected Map config; // protected List<TemplateRender> IF; // // public BaseOutput(Map config) { // super(config); // // this.config = config; // // // if (this.config.containsKey("if")) { // IF = new ArrayList<TemplateRender>(); // for (String c : (List<String>) this.config.get("if")) { // try { // IF.add(new FreeMarkerRender(c, c)); // } catch (IOException e) { // log.fatal(e.getMessage()); // System.exit(1); // } // } // } else { // IF = null; // } // // this.prepare(); // } // // protected abstract void prepare(); // // protected abstract void emit(Map event); // // public void shutdown() { // log.info("shutdown" + this.getClass().getName()); // } // // public void process(Map event) { // boolean ifSuccess = true; // if (this.IF != null) { // for (TemplateRender render : this.IF) { // if (!render.render(event).equals("true")) { // ifSuccess = false; // break; // } // } // } // if (ifSuccess) { // this.emit(event); // if (this.enableMeter) { // this.meter.mark(); // } // } // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/TemplateRender.java // public interface TemplateRender { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Object render(Map event); // // static public TemplateRender getRender(Object template) throws IOException { // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher((String) template).matches()) { // return new FieldRender((String) template); // } // // return new FreeMarkerRender((String) template, (String) template); // // } // // // static public TemplateRender getRender(String template, boolean ignoreOneLevelRender) throws IOException { // if (ignoreOneLevelRender == true) { // return getRender(template); // } // // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher(template).matches()) { // return new FieldRender(template); // } // if (template.contains("$")) { // return new FreeMarkerRender(template, template); // } // return new OneLevelRender(template); // } // // // static public TemplateRender getRender(String template, String timezone) throws IOException { // Pattern p = Pattern.compile("\\%\\{\\+.*?\\}"); // if (p.matcher(template).find()) { // return new DateFormatter(template, timezone); // } // return getRender(template); // } // }
import com.ctrip.ops.sysdev.baseplugin.BaseOutput; import com.ctrip.ops.sysdev.render.TemplateRender; import lombok.extern.log4j.Log4j2; import org.elasticsearch.action.DocWriteRequest; import org.elasticsearch.action.bulk.*; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.transport.client.PreBuiltTransportClient; import org.elasticsearch.client.transport.NoNodeAvailableException; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit;
package com.ctrip.ops.sysdev.outputs; /** * @author liujia */ @Log4j2 public class Elasticsearch extends BaseOutput { private final static int BULKACTION = 20000; private final static int BULKSIZE = 15; //MB private final static int FLUSHINTERVAL = 10; private final static int CONCURRENTREQSIZE = 0; private final static boolean DEFAULTSNIFF = true; private final static boolean DEFAULTCOMPRESS = false;
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseOutput.java // @Log4j2 // public abstract class BaseOutput extends Base { // protected Map config; // protected List<TemplateRender> IF; // // public BaseOutput(Map config) { // super(config); // // this.config = config; // // // if (this.config.containsKey("if")) { // IF = new ArrayList<TemplateRender>(); // for (String c : (List<String>) this.config.get("if")) { // try { // IF.add(new FreeMarkerRender(c, c)); // } catch (IOException e) { // log.fatal(e.getMessage()); // System.exit(1); // } // } // } else { // IF = null; // } // // this.prepare(); // } // // protected abstract void prepare(); // // protected abstract void emit(Map event); // // public void shutdown() { // log.info("shutdown" + this.getClass().getName()); // } // // public void process(Map event) { // boolean ifSuccess = true; // if (this.IF != null) { // for (TemplateRender render : this.IF) { // if (!render.render(event).equals("true")) { // ifSuccess = false; // break; // } // } // } // if (ifSuccess) { // this.emit(event); // if (this.enableMeter) { // this.meter.mark(); // } // } // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/TemplateRender.java // public interface TemplateRender { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Object render(Map event); // // static public TemplateRender getRender(Object template) throws IOException { // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher((String) template).matches()) { // return new FieldRender((String) template); // } // // return new FreeMarkerRender((String) template, (String) template); // // } // // // static public TemplateRender getRender(String template, boolean ignoreOneLevelRender) throws IOException { // if (ignoreOneLevelRender == true) { // return getRender(template); // } // // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher(template).matches()) { // return new FieldRender(template); // } // if (template.contains("$")) { // return new FreeMarkerRender(template, template); // } // return new OneLevelRender(template); // } // // // static public TemplateRender getRender(String template, String timezone) throws IOException { // Pattern p = Pattern.compile("\\%\\{\\+.*?\\}"); // if (p.matcher(template).find()) { // return new DateFormatter(template, timezone); // } // return getRender(template); // } // } // Path: hangout-output-plugins/hangout-output-plugins-elasticsearch/src/main/java/com/ctrip/ops/sysdev/outputs/Elasticsearch.java import com.ctrip.ops.sysdev.baseplugin.BaseOutput; import com.ctrip.ops.sysdev.render.TemplateRender; import lombok.extern.log4j.Log4j2; import org.elasticsearch.action.DocWriteRequest; import org.elasticsearch.action.bulk.*; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.transport.client.PreBuiltTransportClient; import org.elasticsearch.client.transport.NoNodeAvailableException; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; package com.ctrip.ops.sysdev.outputs; /** * @author liujia */ @Log4j2 public class Elasticsearch extends BaseOutput { private final static int BULKACTION = 20000; private final static int BULKSIZE = 15; //MB private final static int FLUSHINTERVAL = 10; private final static int CONCURRENTREQSIZE = 0; private final static boolean DEFAULTSNIFF = true; private final static boolean DEFAULTCOMPRESS = false;
private TemplateRender indexRender;
childe/hangout
hangout-filters/hangout-filters-remove/src/main/java/com/ctrip/ops/sysdev/filters/Remove.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseFilter.java // @Log4j2 // public class BaseFilter extends Base { // // protected Map config; // protected String tagOnFailure; // protected List<FieldDeleter> removeFields; // protected Map<FieldSetter, TemplateRender> addFields; // private List<TemplateRender> IF; // public boolean processExtraEventsFunc; // public BaseFilter nextFilter; // public List<BaseOutput> outputs; // // public BaseFilter(Map config) { // super(config); // this.config = config; // // this.nextFilter = null; // this.outputs = new ArrayList<BaseOutput>(); // // final List<String> ifConditions = (List<String>) this.config.get("if"); // if (ifConditions != null) { // IF = new ArrayList<TemplateRender>(ifConditions.size()); // for (String c : ifConditions) { // try { // IF.add(new FreeMarkerRender(c, c)); // } catch (IOException e) { // log.fatal(e.getMessage(),e); // System.exit(1); // } // } // } // // this.tagOnFailure = (String) config.get("tag_on_failure"); // // final List<String> remove_fields = (ArrayList<String>) config.get("remove_fields"); // if (remove_fields != null) { // this.removeFields = new ArrayList<>(remove_fields.size()); // for (String field : remove_fields) { // this.removeFields.add(FieldDeleter.getFieldDeleter(field)); // } // } // // final Map<String, String> add_fields = (Map<String, String>) config.get("add_fields"); // if (add_fields != null) { // this.addFields = new HashMap<>(add_fields.size()); // final Iterator<Map.Entry<String, String>> it = add_fields.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry<String, String> entry = it.next(); // // String field = entry.getKey(); // Object value = entry.getValue(); // // try { // this.addFields.put(FieldSetter.getFieldSetter(field), TemplateRender.getRender(value)); // } catch (IOException e) { // log.fatal(e.getMessage()); // System.exit(1); // } // } // } // // this.prepare(); // } // // protected void prepare() { // } // // public boolean needProcess(Map event) { // if (this.IF != null) { // for (TemplateRender render : this.IF) { // if (!render.render(event).equals("true")) { // return false; // } // } // } // return true; // } // // public Map process(Map event) { // if (event == null) { // return null; // } // // if (this.needProcess(event) == true) { // event = this.filter(event); // } // // if (event == null) { // return null; // } // // if (this.nextFilter != null) { // event = this.nextFilter.process(event); // } else { // for (BaseOutput o : this.outputs) { // o.process(event); // } // } // return event; // } // // public void processExtraEvents(Stack<Map<String, Object>> to_st) { // this.filterExtraEvents(to_st); // } // // protected Map filter(Map event) { // return event; // } // // protected void filterExtraEvents(Stack<Map<String, Object>> to_stt) { // return; // } // // public void postProcess(Map event, boolean ifSuccess) { // if (ifSuccess == false) { // if (this.tagOnFailure == null || this.tagOnFailure.length() <= 0) { // return; // } // if (!event.containsKey("tags")) { // event.put("tags", new ArrayList<String>(Arrays.asList(this.tagOnFailure))); // } else { // Object tags = event.get("tags"); // if (tags.getClass() == ArrayList.class // && ((ArrayList) tags).indexOf(this.tagOnFailure) == -1) { // ((ArrayList) tags).add(this.tagOnFailure); // } // } // } else { // if (this.removeFields != null) { // for (FieldDeleter f : this.removeFields) { // f.delete(event); // } // } // // if (this.addFields != null) { // Iterator<Map.Entry<FieldSetter, TemplateRender>> it = this.addFields.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry<FieldSetter, TemplateRender> entry = it.next(); // FieldSetter fieldSetter = entry.getKey(); // TemplateRender templateRender = entry.getValue(); // fieldSetter.setField(event, templateRender.render(event)); // } // } // } // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldDeleter/FieldDeleter.java // public interface FieldDeleter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Map delete(Map event); // // public static FieldDeleter getFieldDeleter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelDeleter(field); // } // return new OneLevelDeleter(field); // } // }
import com.ctrip.ops.sysdev.baseplugin.BaseFilter; import com.ctrip.ops.sysdev.fieldDeleter.FieldDeleter; import java.util.ArrayList; import java.util.Map;
package com.ctrip.ops.sysdev.filters; @SuppressWarnings("ALL") public class Remove extends BaseFilter { public Remove(Map config) { super(config); }
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseFilter.java // @Log4j2 // public class BaseFilter extends Base { // // protected Map config; // protected String tagOnFailure; // protected List<FieldDeleter> removeFields; // protected Map<FieldSetter, TemplateRender> addFields; // private List<TemplateRender> IF; // public boolean processExtraEventsFunc; // public BaseFilter nextFilter; // public List<BaseOutput> outputs; // // public BaseFilter(Map config) { // super(config); // this.config = config; // // this.nextFilter = null; // this.outputs = new ArrayList<BaseOutput>(); // // final List<String> ifConditions = (List<String>) this.config.get("if"); // if (ifConditions != null) { // IF = new ArrayList<TemplateRender>(ifConditions.size()); // for (String c : ifConditions) { // try { // IF.add(new FreeMarkerRender(c, c)); // } catch (IOException e) { // log.fatal(e.getMessage(),e); // System.exit(1); // } // } // } // // this.tagOnFailure = (String) config.get("tag_on_failure"); // // final List<String> remove_fields = (ArrayList<String>) config.get("remove_fields"); // if (remove_fields != null) { // this.removeFields = new ArrayList<>(remove_fields.size()); // for (String field : remove_fields) { // this.removeFields.add(FieldDeleter.getFieldDeleter(field)); // } // } // // final Map<String, String> add_fields = (Map<String, String>) config.get("add_fields"); // if (add_fields != null) { // this.addFields = new HashMap<>(add_fields.size()); // final Iterator<Map.Entry<String, String>> it = add_fields.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry<String, String> entry = it.next(); // // String field = entry.getKey(); // Object value = entry.getValue(); // // try { // this.addFields.put(FieldSetter.getFieldSetter(field), TemplateRender.getRender(value)); // } catch (IOException e) { // log.fatal(e.getMessage()); // System.exit(1); // } // } // } // // this.prepare(); // } // // protected void prepare() { // } // // public boolean needProcess(Map event) { // if (this.IF != null) { // for (TemplateRender render : this.IF) { // if (!render.render(event).equals("true")) { // return false; // } // } // } // return true; // } // // public Map process(Map event) { // if (event == null) { // return null; // } // // if (this.needProcess(event) == true) { // event = this.filter(event); // } // // if (event == null) { // return null; // } // // if (this.nextFilter != null) { // event = this.nextFilter.process(event); // } else { // for (BaseOutput o : this.outputs) { // o.process(event); // } // } // return event; // } // // public void processExtraEvents(Stack<Map<String, Object>> to_st) { // this.filterExtraEvents(to_st); // } // // protected Map filter(Map event) { // return event; // } // // protected void filterExtraEvents(Stack<Map<String, Object>> to_stt) { // return; // } // // public void postProcess(Map event, boolean ifSuccess) { // if (ifSuccess == false) { // if (this.tagOnFailure == null || this.tagOnFailure.length() <= 0) { // return; // } // if (!event.containsKey("tags")) { // event.put("tags", new ArrayList<String>(Arrays.asList(this.tagOnFailure))); // } else { // Object tags = event.get("tags"); // if (tags.getClass() == ArrayList.class // && ((ArrayList) tags).indexOf(this.tagOnFailure) == -1) { // ((ArrayList) tags).add(this.tagOnFailure); // } // } // } else { // if (this.removeFields != null) { // for (FieldDeleter f : this.removeFields) { // f.delete(event); // } // } // // if (this.addFields != null) { // Iterator<Map.Entry<FieldSetter, TemplateRender>> it = this.addFields.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry<FieldSetter, TemplateRender> entry = it.next(); // FieldSetter fieldSetter = entry.getKey(); // TemplateRender templateRender = entry.getValue(); // fieldSetter.setField(event, templateRender.render(event)); // } // } // } // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldDeleter/FieldDeleter.java // public interface FieldDeleter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Map delete(Map event); // // public static FieldDeleter getFieldDeleter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelDeleter(field); // } // return new OneLevelDeleter(field); // } // } // Path: hangout-filters/hangout-filters-remove/src/main/java/com/ctrip/ops/sysdev/filters/Remove.java import com.ctrip.ops.sysdev.baseplugin.BaseFilter; import com.ctrip.ops.sysdev.fieldDeleter.FieldDeleter; import java.util.ArrayList; import java.util.Map; package com.ctrip.ops.sysdev.filters; @SuppressWarnings("ALL") public class Remove extends BaseFilter { public Remove(Map config) { super(config); }
private ArrayList<FieldDeleter> fields;
childe/hangout
hangout-filters/hangout-filters-add/src/test/java/com/ctrip/ops/sysdev/test/TestAddFilter.java
// Path: hangout-filters/hangout-filters-add/src/main/java/com/ctrip/ops/sysdev/filters/Add.java // @Log4j2 // public class Add extends BaseFilter { // public Add(Map config) { // super(config); // } // // private Map<FieldSetter, TemplateRender> f; // // protected void prepare() { // f = new HashMap(); // // Map<String, String> fields = (Map<String, String>) config.get("fields"); // Iterator<Entry<String, String>> it = fields.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry<String, String> entry = it.next(); // // String field = entry.getKey(); // String value = entry.getValue(); // // try { // this.f.put(FieldSetter.getFieldSetter(field), TemplateRender.getRender(value)); // } catch (IOException e) { // log.fatal(e.getMessage()); // System.exit(1); // } // } // } // // @Override // protected Map filter(final Map event) { // Iterator<Entry<FieldSetter, TemplateRender>> it = f.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry<FieldSetter, TemplateRender> entry = it.next(); // // FieldSetter fieldSetter = entry.getKey(); // TemplateRender render = entry.getValue(); // fieldSetter.setField(event, render.render(event)); // } // return event; // } // }
import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Add; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml;
package com.ctrip.ops.sysdev.test; public class TestAddFilter { @Test public void testAddFilter() { String c = String.format("%s\n%s\n%s\n%s\n%s\n%s\n%s", " fields:", " nick: '${name}-badboy'", " gender: 'male'", " '[metric][value1]': '10'", " '[metric][value2]': ${name}", " '[metric][value3]': '[extra][value]'", " '[metric][value4]': '[extra][value2]'" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
// Path: hangout-filters/hangout-filters-add/src/main/java/com/ctrip/ops/sysdev/filters/Add.java // @Log4j2 // public class Add extends BaseFilter { // public Add(Map config) { // super(config); // } // // private Map<FieldSetter, TemplateRender> f; // // protected void prepare() { // f = new HashMap(); // // Map<String, String> fields = (Map<String, String>) config.get("fields"); // Iterator<Entry<String, String>> it = fields.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry<String, String> entry = it.next(); // // String field = entry.getKey(); // String value = entry.getValue(); // // try { // this.f.put(FieldSetter.getFieldSetter(field), TemplateRender.getRender(value)); // } catch (IOException e) { // log.fatal(e.getMessage()); // System.exit(1); // } // } // } // // @Override // protected Map filter(final Map event) { // Iterator<Entry<FieldSetter, TemplateRender>> it = f.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry<FieldSetter, TemplateRender> entry = it.next(); // // FieldSetter fieldSetter = entry.getKey(); // TemplateRender render = entry.getValue(); // fieldSetter.setField(event, render.render(event)); // } // return event; // } // } // Path: hangout-filters/hangout-filters-add/src/test/java/com/ctrip/ops/sysdev/test/TestAddFilter.java import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Add; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; package com.ctrip.ops.sysdev.test; public class TestAddFilter { @Test public void testAddFilter() { String c = String.format("%s\n%s\n%s\n%s\n%s\n%s\n%s", " fields:", " nick: '${name}-badboy'", " gender: 'male'", " '[metric][value1]': '10'", " '[metric][value2]': ${name}", " '[metric][value3]': '[extra][value]'", " '[metric][value4]': '[extra][value2]'" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
Add addFilter = new Add(config);
childe/hangout
hangout-metric-plugins/hangout-metric-graphit/src/main/java/com/ctrip/ops/sysdev/metrics/Graphit.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseMetric.java // public abstract class BaseMetric extends Base { // public BaseMetric(Map config) { // super(config); // } // // public void register() { // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/metric/Metric.java // public class Metric { // // private static MetricRegistry metricRegistry = new MetricRegistry(); // // public static Meter setMetric(String metricName) { // return metricRegistry.meter(metricName); // } // // public static MetricRegistry getMetricRegistry() // { // return metricRegistry; // } // }
import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.MetricSet; import com.codahale.metrics.graphite.GraphiteReporter; import com.codahale.metrics.graphite.PickledGraphite; import com.ctrip.ops.sysdev.baseplugin.BaseMetric; import lombok.extern.log4j.Log4j2; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import com.ctrip.ops.sysdev.metric.Metric;
package com.ctrip.ops.sysdev.metrics; /** * Created by liujia on 17/7/4. */ @Log4j2 public class Graphit extends BaseMetric { private final String host; private final int port; private String prefix; private HashMap<String, ArrayList<String>> metrics; private final MetricRegistry metricRegistry = new MetricRegistry(); public Graphit(Map config) { super(config); this.host = (String) config.get("host"); this.port = (Integer) config.get("port"); this.prefix = (String) config.get("prefix"); this.metrics = (HashMap<String, ArrayList<String>>) config.get("metrics"); } public void register() {
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseMetric.java // public abstract class BaseMetric extends Base { // public BaseMetric(Map config) { // super(config); // } // // public void register() { // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/metric/Metric.java // public class Metric { // // private static MetricRegistry metricRegistry = new MetricRegistry(); // // public static Meter setMetric(String metricName) { // return metricRegistry.meter(metricName); // } // // public static MetricRegistry getMetricRegistry() // { // return metricRegistry; // } // } // Path: hangout-metric-plugins/hangout-metric-graphit/src/main/java/com/ctrip/ops/sysdev/metrics/Graphit.java import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.MetricSet; import com.codahale.metrics.graphite.GraphiteReporter; import com.codahale.metrics.graphite.PickledGraphite; import com.ctrip.ops.sysdev.baseplugin.BaseMetric; import lombok.extern.log4j.Log4j2; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import com.ctrip.ops.sysdev.metric.Metric; package com.ctrip.ops.sysdev.metrics; /** * Created by liujia on 17/7/4. */ @Log4j2 public class Graphit extends BaseMetric { private final String host; private final int port; private String prefix; private HashMap<String, ArrayList<String>> metrics; private final MetricRegistry metricRegistry = new MetricRegistry(); public Graphit(Map config) { super(config); this.host = (String) config.get("host"); this.port = (Integer) config.get("port"); this.prefix = (String) config.get("prefix"); this.metrics = (HashMap<String, ArrayList<String>>) config.get("metrics"); } public void register() {
this.metricRegistry.registerAll(Metric.getMetricRegistry());
childe/hangout
hangout-filters/hangout-filters-kv/src/test/java/com/ctrip/ops/sysdev/test/TestKV.java
// Path: hangout-filters/hangout-filters-kv/src/main/java/com/ctrip/ops/sysdev/filters/KV.java // @Log4j2 // public class KV extends BaseFilter { // // private String source; // private String target; // private String field_split; // private String value_split; // private String trim; // private String trimkey; // // private ArrayList<String> excludeKeys, includeKeys; // // @SuppressWarnings("rawtypes") // public KV(Map config) { // super(config); // } // // @SuppressWarnings("unchecked") // protected void prepare() { // // if (this.config.containsKey("source")) { // this.source = (String) this.config.get("source"); // } else { // this.source = "message"; // } // // if (this.config.containsKey("target")) { // this.target = (String) this.config.get("target"); // } // // if (this.config.containsKey("field_split")) { // this.field_split = (String) this.config.get("field_split"); // } else { // this.field_split = " "; // } // if (this.config.containsKey("value_split")) { // this.value_split = (String) this.config.get("value_split"); // } else { // this.value_split = "="; // } // // if (this.config.containsKey("trim")) { // this.trim = (String) this.config.get("trim"); // this.trim = "^[" + this.trim + "]+|[" + this.trim + "]+$"; // } // // if (this.config.containsKey("trimkey")) { // this.trimkey = (String) this.config.get("trimkey"); // this.trimkey = "^[" + this.trimkey + "]+|[" + this.trimkey + "]+$"; // } // // if (this.config.containsKey("tag_on_failure")) { // this.tagOnFailure = (String) this.config.get("tag_on_failure"); // } else { // this.tagOnFailure = "KVfail"; // } // // this.excludeKeys = (ArrayList<String>) this.config.get("exclude_keys"); // this.includeKeys = (ArrayList<String>) this.config.get("include_keys"); // // } // // @SuppressWarnings({"rawtypes", "unchecked"}) // @Override // protected Map filter(Map event) { // if (!event.containsKey(this.source)) { // return event; // } // boolean success = true; // // HashMap targetObj = new HashMap(); // // try { // String sourceStr = (String) event.get(this.source); // for (String kv : sourceStr.split(this.field_split)) { // String[] kandv = kv.split(this.value_split, 2); // if (kandv.length != 2) { // success = false; // continue; // } // // String k = kandv[0]; // if (this.includeKeys != null && !this.includeKeys.contains(k) // || this.excludeKeys != null // && this.excludeKeys.contains(k)) { // continue; // } // // String v = kandv[1]; // // if (this.trim != null) { // v = v.replaceAll(this.trim, ""); // } // if (this.trimkey != null) { // k = k.replaceAll(this.trimkey, ""); // } // // if (this.target != null) { // targetObj.put(k, v); // } else { // event.put(k, v); // } // } // // if (this.target != null) { // event.put(this.target, targetObj); // } // } catch (Exception e) { // log.warn(event + "kv faild"); // success = false; // } // // this.postProcess(event, success); // // return event; // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.KV; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml;
package com.ctrip.ops.sysdev.test; public class TestKV { @Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void testGrok() { // General Test String c = String.format("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s", "source: msg", "field_split: ' '", "value_split: '='", "trim: '\t\"'", "trimkey: '\"'", "include_keys: ['a','b','xyz','12']", "exclude_keys: ['b','c']", "tag_on_failure: 'KVfail'", "remove_fields: ['msg']"); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
// Path: hangout-filters/hangout-filters-kv/src/main/java/com/ctrip/ops/sysdev/filters/KV.java // @Log4j2 // public class KV extends BaseFilter { // // private String source; // private String target; // private String field_split; // private String value_split; // private String trim; // private String trimkey; // // private ArrayList<String> excludeKeys, includeKeys; // // @SuppressWarnings("rawtypes") // public KV(Map config) { // super(config); // } // // @SuppressWarnings("unchecked") // protected void prepare() { // // if (this.config.containsKey("source")) { // this.source = (String) this.config.get("source"); // } else { // this.source = "message"; // } // // if (this.config.containsKey("target")) { // this.target = (String) this.config.get("target"); // } // // if (this.config.containsKey("field_split")) { // this.field_split = (String) this.config.get("field_split"); // } else { // this.field_split = " "; // } // if (this.config.containsKey("value_split")) { // this.value_split = (String) this.config.get("value_split"); // } else { // this.value_split = "="; // } // // if (this.config.containsKey("trim")) { // this.trim = (String) this.config.get("trim"); // this.trim = "^[" + this.trim + "]+|[" + this.trim + "]+$"; // } // // if (this.config.containsKey("trimkey")) { // this.trimkey = (String) this.config.get("trimkey"); // this.trimkey = "^[" + this.trimkey + "]+|[" + this.trimkey + "]+$"; // } // // if (this.config.containsKey("tag_on_failure")) { // this.tagOnFailure = (String) this.config.get("tag_on_failure"); // } else { // this.tagOnFailure = "KVfail"; // } // // this.excludeKeys = (ArrayList<String>) this.config.get("exclude_keys"); // this.includeKeys = (ArrayList<String>) this.config.get("include_keys"); // // } // // @SuppressWarnings({"rawtypes", "unchecked"}) // @Override // protected Map filter(Map event) { // if (!event.containsKey(this.source)) { // return event; // } // boolean success = true; // // HashMap targetObj = new HashMap(); // // try { // String sourceStr = (String) event.get(this.source); // for (String kv : sourceStr.split(this.field_split)) { // String[] kandv = kv.split(this.value_split, 2); // if (kandv.length != 2) { // success = false; // continue; // } // // String k = kandv[0]; // if (this.includeKeys != null && !this.includeKeys.contains(k) // || this.excludeKeys != null // && this.excludeKeys.contains(k)) { // continue; // } // // String v = kandv[1]; // // if (this.trim != null) { // v = v.replaceAll(this.trim, ""); // } // if (this.trimkey != null) { // k = k.replaceAll(this.trimkey, ""); // } // // if (this.target != null) { // targetObj.put(k, v); // } else { // event.put(k, v); // } // } // // if (this.target != null) { // event.put(this.target, targetObj); // } // } catch (Exception e) { // log.warn(event + "kv faild"); // success = false; // } // // this.postProcess(event, success); // // return event; // } // } // Path: hangout-filters/hangout-filters-kv/src/test/java/com/ctrip/ops/sysdev/test/TestKV.java import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.KV; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; package com.ctrip.ops.sysdev.test; public class TestKV { @Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void testGrok() { // General Test String c = String.format("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s", "source: msg", "field_split: ' '", "value_split: '='", "trim: '\t\"'", "trimkey: '\"'", "include_keys: ['a','b','xyz','12']", "exclude_keys: ['b','c']", "tag_on_failure: 'KVfail'", "remove_fields: ['msg']"); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
KV KVfilter = new KV(config);
childe/hangout
hangout-filters/hangout-filters-date/src/test/java/com/ctrip/ops/sysdev/test/TestDateFilter.java
// Path: hangout-filters/hangout-filters-date/src/main/java/com/ctrip/ops/sysdev/filters/Date.java // @Log4j2 // public class Date extends BaseFilter { // private TemplateRender templateRender; // private FieldSetter fiedlSetter; // private boolean addYear; // private List<DateParser> parsers; // // public Date(Map config) { // super(config); // } // // @SuppressWarnings("unchecked") // protected void prepare() { // String src = "logtime"; // if (config.containsKey("src")) { // src = (String) config.get("src"); // } // try { // this.templateRender = TemplateRender.getRender(src, false); // } catch (IOException e) { // log.error("could NOT build TemplateRender from " + src); // System.exit(1); // } // // String target = "@timestamp"; // if (config.containsKey("target")) { // target = (String) config.get("target"); // } // this.fiedlSetter = FieldSetter.getFieldSetter(target); // // if (config.containsKey("tag_on_failure")) { // this.tagOnFailure = (String) config.get("tag_on_failure"); // } else { // this.tagOnFailure = "datefail"; // } // // if (config.containsKey("add_year")) { // this.addYear = (Boolean) config.get("add_year"); // } else { // this.addYear = false; // } // this.parsers = new ArrayList<DateParser>(); // for (String format : (List<String>) config.get("formats")) { // if (format.equalsIgnoreCase("ISO8601")) { // parsers.add(new ISODateParser((String) config.get("timezone"))); // } else if (format.equalsIgnoreCase("UNIX")) { // parsers.add(new UnixParser()); // } else if (format.equalsIgnoreCase("UNIX_MS")) { // parsers.add(new UnixMSParser()); // } else { // parsers.add(new FormatParser(format, (String) config // .get("timezone"), (String) config.get("locale"))); // } // } // } // // @Override // protected Map filter(Map event) { // Object inputObj = this.templateRender.render(event); // if (inputObj == null) { // return event; // } // // String input = inputObj.toString(); // boolean success = false; // // if (addYear) { // input = Calendar.getInstance().get(Calendar.YEAR) + input; // } // // for (DateParser parser : this.parsers) { // try { // this.fiedlSetter.setField(event, parser.parse(input)); // success = true; // break; // } catch (Exception e) { // log.trace(String.format("parser %s tailed, try next", parser.toString())); // } // } // // postProcess(event, success); // // return event; // } // // }
import java.util.HashMap; import java.util.List; import java.util.Map; import com.ctrip.ops.sysdev.filters.Date; import org.joda.time.DateTime; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml;
package com.ctrip.ops.sysdev.test; public class TestDateFilter { @Test public void testAddFilter() { // success, remove src field String c = String.format("%s\n%s\n%s\n%s\n%s", "src: logtime", "formats:", " - 'ISO8601'", " - 'YYYY.MM.dd HH:mm:ssZ'", "remove_fields: ['logtime']" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
// Path: hangout-filters/hangout-filters-date/src/main/java/com/ctrip/ops/sysdev/filters/Date.java // @Log4j2 // public class Date extends BaseFilter { // private TemplateRender templateRender; // private FieldSetter fiedlSetter; // private boolean addYear; // private List<DateParser> parsers; // // public Date(Map config) { // super(config); // } // // @SuppressWarnings("unchecked") // protected void prepare() { // String src = "logtime"; // if (config.containsKey("src")) { // src = (String) config.get("src"); // } // try { // this.templateRender = TemplateRender.getRender(src, false); // } catch (IOException e) { // log.error("could NOT build TemplateRender from " + src); // System.exit(1); // } // // String target = "@timestamp"; // if (config.containsKey("target")) { // target = (String) config.get("target"); // } // this.fiedlSetter = FieldSetter.getFieldSetter(target); // // if (config.containsKey("tag_on_failure")) { // this.tagOnFailure = (String) config.get("tag_on_failure"); // } else { // this.tagOnFailure = "datefail"; // } // // if (config.containsKey("add_year")) { // this.addYear = (Boolean) config.get("add_year"); // } else { // this.addYear = false; // } // this.parsers = new ArrayList<DateParser>(); // for (String format : (List<String>) config.get("formats")) { // if (format.equalsIgnoreCase("ISO8601")) { // parsers.add(new ISODateParser((String) config.get("timezone"))); // } else if (format.equalsIgnoreCase("UNIX")) { // parsers.add(new UnixParser()); // } else if (format.equalsIgnoreCase("UNIX_MS")) { // parsers.add(new UnixMSParser()); // } else { // parsers.add(new FormatParser(format, (String) config // .get("timezone"), (String) config.get("locale"))); // } // } // } // // @Override // protected Map filter(Map event) { // Object inputObj = this.templateRender.render(event); // if (inputObj == null) { // return event; // } // // String input = inputObj.toString(); // boolean success = false; // // if (addYear) { // input = Calendar.getInstance().get(Calendar.YEAR) + input; // } // // for (DateParser parser : this.parsers) { // try { // this.fiedlSetter.setField(event, parser.parse(input)); // success = true; // break; // } catch (Exception e) { // log.trace(String.format("parser %s tailed, try next", parser.toString())); // } // } // // postProcess(event, success); // // return event; // } // // } // Path: hangout-filters/hangout-filters-date/src/test/java/com/ctrip/ops/sysdev/test/TestDateFilter.java import java.util.HashMap; import java.util.List; import java.util.Map; import com.ctrip.ops.sysdev.filters.Date; import org.joda.time.DateTime; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; package com.ctrip.ops.sysdev.test; public class TestDateFilter { @Test public void testAddFilter() { // success, remove src field String c = String.format("%s\n%s\n%s\n%s\n%s", "src: logtime", "formats:", " - 'ISO8601'", " - 'YYYY.MM.dd HH:mm:ssZ'", "remove_fields: ['logtime']" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
Date dateFilter = new Date(config);
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // }
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.dontpanic.spanners.springmvc.domain.Spanner; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.core.ParameterizedTypeReference; import org.springframework.hateoas.PagedResources; import org.springframework.hateoas.hal.Jackson2HalModule; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.Collection;
package org.dontpanic.spanners.springmvc.services; /** * Client of the Spanners-API REST service * Created by stevie on 08/06/16. */ @Service public class SpannersService { private RestTemplate restTemplate; public SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri) { restTemplate = builder.messageConverters(halAwareMessageConverter()) .rootUri(rootUri).build(); } private HttpMessageConverter halAwareMessageConverter() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.registerModule(new Jackson2HalModule()); return new MappingJackson2HttpMessageConverter(mapper); }
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.dontpanic.spanners.springmvc.domain.Spanner; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.core.ParameterizedTypeReference; import org.springframework.hateoas.PagedResources; import org.springframework.hateoas.hal.Jackson2HalModule; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.Collection; package org.dontpanic.spanners.springmvc.services; /** * Client of the Spanners-API REST service * Created by stevie on 08/06/16. */ @Service public class SpannersService { private RestTemplate restTemplate; public SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri) { restTemplate = builder.messageConverters(halAwareMessageConverter()) .rootUri(rootUri).build(); } private HttpMessageConverter halAwareMessageConverter() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.registerModule(new Jackson2HalModule()); return new MappingJackson2HttpMessageConverter(mapper); }
public Collection<Spanner> findAll() {
hotblac/spanners
spanners-api/src/test/java/org/dontpanic/spanners/api/data/RestApiTest.java
// Path: spanners-api/src/test/java/org/dontpanic/spanners/api/stubs/SpannerBuilder.java // public static SpannerBuilder aTestSpanner() { // return new SpannerBuilder(); // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import static org.dontpanic.spanners.api.stubs.SpannerBuilder.aTestSpanner; import static org.hamcrest.Matchers.isEmptyString; import static org.hamcrest.Matchers.not; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
package org.dontpanic.spanners.api.data; /** * Tests on the REST API exposed by this application. * Created by stevie on 10/06/16. */ @RunWith(SpringRunner.class) @SpringBootTest @WebAppConfiguration @AutoConfigureMockMvc public class RestApiTest { @Autowired private MockMvc mockMvc; @Autowired private SpannerRepository repository; /** * By default, Spring Data REST does not expose database ids. * The ids are currently used by Spring MVC and must be exposed. */ @Test public void testFindAllContainsDatabaseIds() throws Exception { // Setup: add a spanner to the repository
// Path: spanners-api/src/test/java/org/dontpanic/spanners/api/stubs/SpannerBuilder.java // public static SpannerBuilder aTestSpanner() { // return new SpannerBuilder(); // } // Path: spanners-api/src/test/java/org/dontpanic/spanners/api/data/RestApiTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import static org.dontpanic.spanners.api.stubs.SpannerBuilder.aTestSpanner; import static org.hamcrest.Matchers.isEmptyString; import static org.hamcrest.Matchers.not; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; package org.dontpanic.spanners.api.data; /** * Tests on the REST API exposed by this application. * Created by stevie on 10/06/16. */ @RunWith(SpringRunner.class) @SpringBootTest @WebAppConfiguration @AutoConfigureMockMvc public class RestApiTest { @Autowired private MockMvc mockMvc; @Autowired private SpannerRepository repository; /** * By default, Spring Data REST does not expose database ids. * The ids are currently used by Spring MVC and must be exposed. */ @Test public void testFindAllContainsDatabaseIds() throws Exception { // Setup: add a spanner to the repository
Spanner spanner1 = aTestSpanner().named("Bertha").build();
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/config/WebSecurityConfig.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/RestUserDetailsService.java // @Service // public class RestUserDetailsService implements UserDetailsManager { // // private RestTemplate restTemplate; // // public RestUserDetailsService(RestTemplateBuilder builder, // @Value("${app.service.url.users}") String rootUri) { // // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // @Override // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // return restTemplate.getForObject("/{0}", User.class, username); // } // // @Override // public void createUser(UserDetails userDetails) { // restTemplate.postForLocation("/", userDetails); // } // // @Override // public void updateUser(UserDetails userDetails) { // restTemplate.put("/{0}", userDetails, userDetails.getUsername()); // } // // @Override // public void deleteUser(String username) { // restTemplate.delete("/{0}", username); // } // // @Override // public void changePassword(String username, String password) { // // User user = new User(); // user.setUsername(username); // user.setPassword(password); // // HttpEntity<User> requestEntity = new HttpEntity<>(user); // // restTemplate.exchange("/{0}", HttpMethod.PATCH, requestEntity, Void.class, username); // } // // @Override // public boolean userExists(String username) { // // try { // ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); // return HttpStatus.OK.equals(responseEntity.getStatusCode()); // } catch (HttpClientErrorException e) { // // On HTTP 404 NOT FOUND or any HTTP error, assume user does not exist // return false; // } // } // }
import org.dontpanic.spanners.springmvc.services.RestUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
package org.dontpanic.spanners.springmvc.config; /** * Spring security configuration * Created by stevie on 08/06/16. */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String[] PERMIT_ALL_URLS = {"/", "/css/**", "/img/**", "/js/**", "/signup", "/version.txt"}; @Autowired
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/RestUserDetailsService.java // @Service // public class RestUserDetailsService implements UserDetailsManager { // // private RestTemplate restTemplate; // // public RestUserDetailsService(RestTemplateBuilder builder, // @Value("${app.service.url.users}") String rootUri) { // // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // @Override // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // return restTemplate.getForObject("/{0}", User.class, username); // } // // @Override // public void createUser(UserDetails userDetails) { // restTemplate.postForLocation("/", userDetails); // } // // @Override // public void updateUser(UserDetails userDetails) { // restTemplate.put("/{0}", userDetails, userDetails.getUsername()); // } // // @Override // public void deleteUser(String username) { // restTemplate.delete("/{0}", username); // } // // @Override // public void changePassword(String username, String password) { // // User user = new User(); // user.setUsername(username); // user.setPassword(password); // // HttpEntity<User> requestEntity = new HttpEntity<>(user); // // restTemplate.exchange("/{0}", HttpMethod.PATCH, requestEntity, Void.class, username); // } // // @Override // public boolean userExists(String username) { // // try { // ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); // return HttpStatus.OK.equals(responseEntity.getStatusCode()); // } catch (HttpClientErrorException e) { // // On HTTP 404 NOT FOUND or any HTTP error, assume user does not exist // return false; // } // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/config/WebSecurityConfig.java import org.dontpanic.spanners.springmvc.services.RestUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; package org.dontpanic.spanners.springmvc.config; /** * Spring security configuration * Created by stevie on 08/06/16. */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String[] PERMIT_ALL_URLS = {"/", "/css/**", "/img/**", "/js/**", "/signup", "/version.txt"}; @Autowired
private RestUserDetailsService userDetailsService;
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/EditSpannerController.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/exception/SpannerNotFoundException.java // public class SpannerNotFoundException extends Exception { // // private Long spannerId; // // /** // * New exception // * @param spannerId id of requested spanner // */ // public SpannerNotFoundException(Long spannerId) { // super("Spanner not found: " + spannerId); // this.spannerId = spannerId; // } // // public Long getSpannerId() { // return spannerId; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SpannerForm.java // public class SpannerForm { // // public static final String FIELD_NAME = "name"; // public static final String FIELD_SIZE = "size"; // // private Long id; // @Size(min=1, max=255) // private String name; // @Min(1) @Max(99) // private int size; // // public SpannerForm() { // } // // /** // * Create a spanner form with values initialized to given spanner // */ // public SpannerForm(Spanner spanner) { // this.id = spanner.getId(); // this.name = spanner.getName(); // this.size = spanner.getSize(); // } // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException; import org.dontpanic.spanners.springmvc.forms.SpannerForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid;
package org.dontpanic.spanners.springmvc.controllers; /** * Controller for changing properties of an existing spanner * User: Stevie * Date: 19/10/13 */ @Controller public class EditSpannerController implements ApplicationEventPublisherAware { public static final String VIEW_EDIT_SPANNER = "editSpanner"; public static final String VIEW_UPDATE_SUCCESS = "redirect:/displaySpanners"; public static final String VIEW_VALIDATION_ERRORS = "editSpanner"; public static final String MODEL_SPANNER = "spanner"; public static final String CONTROLLER_URL = "/editSpanner";
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/exception/SpannerNotFoundException.java // public class SpannerNotFoundException extends Exception { // // private Long spannerId; // // /** // * New exception // * @param spannerId id of requested spanner // */ // public SpannerNotFoundException(Long spannerId) { // super("Spanner not found: " + spannerId); // this.spannerId = spannerId; // } // // public Long getSpannerId() { // return spannerId; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SpannerForm.java // public class SpannerForm { // // public static final String FIELD_NAME = "name"; // public static final String FIELD_SIZE = "size"; // // private Long id; // @Size(min=1, max=255) // private String name; // @Min(1) @Max(99) // private int size; // // public SpannerForm() { // } // // /** // * Create a spanner form with values initialized to given spanner // */ // public SpannerForm(Spanner spanner) { // this.id = spanner.getId(); // this.name = spanner.getName(); // this.size = spanner.getSize(); // } // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/EditSpannerController.java import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException; import org.dontpanic.spanners.springmvc.forms.SpannerForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; package org.dontpanic.spanners.springmvc.controllers; /** * Controller for changing properties of an existing spanner * User: Stevie * Date: 19/10/13 */ @Controller public class EditSpannerController implements ApplicationEventPublisherAware { public static final String VIEW_EDIT_SPANNER = "editSpanner"; public static final String VIEW_UPDATE_SUCCESS = "redirect:/displaySpanners"; public static final String VIEW_VALIDATION_ERRORS = "editSpanner"; public static final String MODEL_SPANNER = "spanner"; public static final String CONTROLLER_URL = "/editSpanner";
@Autowired private SpannersService spannersService;
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/SpannerPermissionEvaluator.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import org.springframework.security.access.PermissionEvaluator; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import java.io.Serializable;
package org.dontpanic.spanners.springmvc; /** * Override sstandard Spring ACL based security for one with an awareness of the subtleties of spanners. * User: Stevie * Date: 11/08/12 */ @Component public class SpannerPermissionEvaluator implements PermissionEvaluator{ public static final String OWNER = "owner"; @Override public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { boolean hasPermission = false;
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/SpannerPermissionEvaluator.java import org.dontpanic.spanners.springmvc.domain.Spanner; import org.springframework.security.access.PermissionEvaluator; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import java.io.Serializable; package org.dontpanic.spanners.springmvc; /** * Override sstandard Spring ACL based security for one with an awareness of the subtleties of spanners. * User: Stevie * Date: 11/08/12 */ @Component public class SpannerPermissionEvaluator implements PermissionEvaluator{ public static final String OWNER = "owner"; @Override public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { boolean hasPermission = false;
if (targetDomainObject instanceof Spanner && permission.toString().equals(OWNER)) {
hotblac/spanners
spanners-api/src/test/java/org/dontpanic/spanners/api/stubs/SpannerBuilder.java
// Path: spanners-api/src/main/java/org/dontpanic/spanners/api/data/Spanner.java // @Entity // public class Spanner { // // @Id // @GeneratedValue(strategy= GenerationType.AUTO) // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // }
import org.dontpanic.spanners.api.data.Spanner;
package org.dontpanic.spanners.api.stubs; /** * Builder for spanner test data * User: Stevie * Date: 05/11/14 */ public class SpannerBuilder { public static final String DEFAULT_NAME = "Bertha"; public static final int DEFAULT_SIZE = 16; public static final String DEFAULT_OWNER = "Mr Smith"; private String name = DEFAULT_NAME; private int size = DEFAULT_SIZE; private String owner = DEFAULT_OWNER; public static SpannerBuilder aTestSpanner() { return new SpannerBuilder(); } public SpannerBuilder named(String name) { this.name = name; return this; } public SpannerBuilder withSize(int size) { this.size = size; return this; } public SpannerBuilder ownedBy(String owner) { this.owner = owner; return this; }
// Path: spanners-api/src/main/java/org/dontpanic/spanners/api/data/Spanner.java // @Entity // public class Spanner { // // @Id // @GeneratedValue(strategy= GenerationType.AUTO) // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // Path: spanners-api/src/test/java/org/dontpanic/spanners/api/stubs/SpannerBuilder.java import org.dontpanic.spanners.api.data.Spanner; package org.dontpanic.spanners.api.stubs; /** * Builder for spanner test data * User: Stevie * Date: 05/11/14 */ public class SpannerBuilder { public static final String DEFAULT_NAME = "Bertha"; public static final int DEFAULT_SIZE = 16; public static final String DEFAULT_OWNER = "Mr Smith"; private String name = DEFAULT_NAME; private int size = DEFAULT_SIZE; private String owner = DEFAULT_OWNER; public static SpannerBuilder aTestSpanner() { return new SpannerBuilder(); } public SpannerBuilder named(String name) { this.name = name; return this; } public SpannerBuilder withSize(int size) { this.size = size; return this; } public SpannerBuilder ownedBy(String owner) { this.owner = owner; return this; }
public Spanner build() {
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/AddSpannerController.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SpannerForm.java // public class SpannerForm { // // public static final String FIELD_NAME = "name"; // public static final String FIELD_SIZE = "size"; // // private Long id; // @Size(min=1, max=255) // private String name; // @Min(1) @Max(99) // private int size; // // public SpannerForm() { // } // // /** // * Create a spanner form with values initialized to given spanner // */ // public SpannerForm(Spanner spanner) { // this.id = spanner.getId(); // this.name = spanner.getName(); // this.size = spanner.getSize(); // } // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.dontpanic.spanners.springmvc.forms.SpannerForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; import java.security.Principal;
package org.dontpanic.spanners.springmvc.controllers; /** * Controller for creating a new spanner * User: Stevie * Date: 20/10/13 */ @Controller public class AddSpannerController { public static final String CONTROLLER_URL = "/addSpanner"; public static final String VIEW_ADD_SPANNER = "editSpanner"; public static final String VIEW_SUCCESS = "redirect:/displaySpanners"; public static final String VIEW_VALIDATION_FAIL = "editSpanner"; public static final String MODEL_SPANNER = "spanner";
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SpannerForm.java // public class SpannerForm { // // public static final String FIELD_NAME = "name"; // public static final String FIELD_SIZE = "size"; // // private Long id; // @Size(min=1, max=255) // private String name; // @Min(1) @Max(99) // private int size; // // public SpannerForm() { // } // // /** // * Create a spanner form with values initialized to given spanner // */ // public SpannerForm(Spanner spanner) { // this.id = spanner.getId(); // this.name = spanner.getName(); // this.size = spanner.getSize(); // } // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/AddSpannerController.java import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.dontpanic.spanners.springmvc.forms.SpannerForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; import java.security.Principal; package org.dontpanic.spanners.springmvc.controllers; /** * Controller for creating a new spanner * User: Stevie * Date: 20/10/13 */ @Controller public class AddSpannerController { public static final String CONTROLLER_URL = "/addSpanner"; public static final String VIEW_ADD_SPANNER = "editSpanner"; public static final String VIEW_SUCCESS = "redirect:/displaySpanners"; public static final String VIEW_VALIDATION_FAIL = "editSpanner"; public static final String MODEL_SPANNER = "spanner";
@Autowired private SpannersService spannersService;
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/AddSpannerController.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SpannerForm.java // public class SpannerForm { // // public static final String FIELD_NAME = "name"; // public static final String FIELD_SIZE = "size"; // // private Long id; // @Size(min=1, max=255) // private String name; // @Min(1) @Max(99) // private int size; // // public SpannerForm() { // } // // /** // * Create a spanner form with values initialized to given spanner // */ // public SpannerForm(Spanner spanner) { // this.id = spanner.getId(); // this.name = spanner.getName(); // this.size = spanner.getSize(); // } // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.dontpanic.spanners.springmvc.forms.SpannerForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; import java.security.Principal;
package org.dontpanic.spanners.springmvc.controllers; /** * Controller for creating a new spanner * User: Stevie * Date: 20/10/13 */ @Controller public class AddSpannerController { public static final String CONTROLLER_URL = "/addSpanner"; public static final String VIEW_ADD_SPANNER = "editSpanner"; public static final String VIEW_SUCCESS = "redirect:/displaySpanners"; public static final String VIEW_VALIDATION_FAIL = "editSpanner"; public static final String MODEL_SPANNER = "spanner"; @Autowired private SpannersService spannersService; /** * Display that add spanner page */ @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage() {
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SpannerForm.java // public class SpannerForm { // // public static final String FIELD_NAME = "name"; // public static final String FIELD_SIZE = "size"; // // private Long id; // @Size(min=1, max=255) // private String name; // @Min(1) @Max(99) // private int size; // // public SpannerForm() { // } // // /** // * Create a spanner form with values initialized to given spanner // */ // public SpannerForm(Spanner spanner) { // this.id = spanner.getId(); // this.name = spanner.getName(); // this.size = spanner.getSize(); // } // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/AddSpannerController.java import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.dontpanic.spanners.springmvc.forms.SpannerForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; import java.security.Principal; package org.dontpanic.spanners.springmvc.controllers; /** * Controller for creating a new spanner * User: Stevie * Date: 20/10/13 */ @Controller public class AddSpannerController { public static final String CONTROLLER_URL = "/addSpanner"; public static final String VIEW_ADD_SPANNER = "editSpanner"; public static final String VIEW_SUCCESS = "redirect:/displaySpanners"; public static final String VIEW_VALIDATION_FAIL = "editSpanner"; public static final String MODEL_SPANNER = "spanner"; @Autowired private SpannersService spannersService; /** * Display that add spanner page */ @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage() {
SpannerForm newSpanner = new SpannerForm();
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/AddSpannerController.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SpannerForm.java // public class SpannerForm { // // public static final String FIELD_NAME = "name"; // public static final String FIELD_SIZE = "size"; // // private Long id; // @Size(min=1, max=255) // private String name; // @Min(1) @Max(99) // private int size; // // public SpannerForm() { // } // // /** // * Create a spanner form with values initialized to given spanner // */ // public SpannerForm(Spanner spanner) { // this.id = spanner.getId(); // this.name = spanner.getName(); // this.size = spanner.getSize(); // } // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.dontpanic.spanners.springmvc.forms.SpannerForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; import java.security.Principal;
package org.dontpanic.spanners.springmvc.controllers; /** * Controller for creating a new spanner * User: Stevie * Date: 20/10/13 */ @Controller public class AddSpannerController { public static final String CONTROLLER_URL = "/addSpanner"; public static final String VIEW_ADD_SPANNER = "editSpanner"; public static final String VIEW_SUCCESS = "redirect:/displaySpanners"; public static final String VIEW_VALIDATION_FAIL = "editSpanner"; public static final String MODEL_SPANNER = "spanner"; @Autowired private SpannersService spannersService; /** * Display that add spanner page */ @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage() { SpannerForm newSpanner = new SpannerForm(); return new ModelAndView(VIEW_ADD_SPANNER, MODEL_SPANNER, newSpanner); } /** * Accept a form submission from add spanner page */ @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VALIDATION_FAIL); } // Create a new spanner
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SpannerForm.java // public class SpannerForm { // // public static final String FIELD_NAME = "name"; // public static final String FIELD_SIZE = "size"; // // private Long id; // @Size(min=1, max=255) // private String name; // @Min(1) @Max(99) // private int size; // // public SpannerForm() { // } // // /** // * Create a spanner form with values initialized to given spanner // */ // public SpannerForm(Spanner spanner) { // this.id = spanner.getId(); // this.name = spanner.getName(); // this.size = spanner.getSize(); // } // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/AddSpannerController.java import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.dontpanic.spanners.springmvc.forms.SpannerForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; import java.security.Principal; package org.dontpanic.spanners.springmvc.controllers; /** * Controller for creating a new spanner * User: Stevie * Date: 20/10/13 */ @Controller public class AddSpannerController { public static final String CONTROLLER_URL = "/addSpanner"; public static final String VIEW_ADD_SPANNER = "editSpanner"; public static final String VIEW_SUCCESS = "redirect:/displaySpanners"; public static final String VIEW_VALIDATION_FAIL = "editSpanner"; public static final String MODEL_SPANNER = "spanner"; @Autowired private SpannersService spannersService; /** * Display that add spanner page */ @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage() { SpannerForm newSpanner = new SpannerForm(); return new ModelAndView(VIEW_ADD_SPANNER, MODEL_SPANNER, newSpanner); } /** * Accept a form submission from add spanner page */ @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VALIDATION_FAIL); } // Create a new spanner
Spanner spanner = new Spanner();
hotblac/spanners
spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannerBuilder.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // }
import org.dontpanic.spanners.springmvc.domain.Spanner;
package org.dontpanic.spanners.springmvc.stubs; /** * Builder for spanner test data * User: Stevie * Date: 05/11/14 */ public class SpannerBuilder { public static final Long DEFAULT_ID = 99l; public static final String DEFAULT_NAME = "Bertha"; public static final int DEFAULT_SIZE = 16; public static final String DEFAULT_OWNER = "Mr Smith"; private Long id = DEFAULT_ID; private String name = DEFAULT_NAME; private int size = DEFAULT_SIZE; private String owner = DEFAULT_OWNER; public static SpannerBuilder aSpanner() { return new SpannerBuilder(); } public SpannerBuilder withId(Long id) { this.id = id; return this; } public SpannerBuilder named(String name) { this.name = name; return this; } public SpannerBuilder withSize(int size) { this.size = size; return this; } public SpannerBuilder ownedBy(String owner) { this.owner = owner; return this; }
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannerBuilder.java import org.dontpanic.spanners.springmvc.domain.Spanner; package org.dontpanic.spanners.springmvc.stubs; /** * Builder for spanner test data * User: Stevie * Date: 05/11/14 */ public class SpannerBuilder { public static final Long DEFAULT_ID = 99l; public static final String DEFAULT_NAME = "Bertha"; public static final int DEFAULT_SIZE = 16; public static final String DEFAULT_OWNER = "Mr Smith"; private Long id = DEFAULT_ID; private String name = DEFAULT_NAME; private int size = DEFAULT_SIZE; private String owner = DEFAULT_OWNER; public static SpannerBuilder aSpanner() { return new SpannerBuilder(); } public SpannerBuilder withId(Long id) { this.id = id; return this; } public SpannerBuilder named(String name) { this.name = name; return this; } public SpannerBuilder withSize(int size) { this.size = size; return this; } public SpannerBuilder ownedBy(String owner) { this.owner = owner; return this; }
public Spanner build() {
hotblac/spanners
spanners-api/src/main/java/org/dontpanic/spanners/api/config/RestConfig.java
// Path: spanners-api/src/main/java/org/dontpanic/spanners/api/data/Spanner.java // @Entity // public class Spanner { // // @Id // @GeneratedValue(strategy= GenerationType.AUTO) // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // }
import org.dontpanic.spanners.api.data.Spanner; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;
package org.dontpanic.spanners.api.config; /** * Custom configuration for Spring Data REST * Created by stevie on 10/06/16. */ @Configuration @EnableDiscoveryClient public class RestConfig extends RepositoryRestConfigurerAdapter { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
// Path: spanners-api/src/main/java/org/dontpanic/spanners/api/data/Spanner.java // @Entity // public class Spanner { // // @Id // @GeneratedValue(strategy= GenerationType.AUTO) // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // Path: spanners-api/src/main/java/org/dontpanic/spanners/api/config/RestConfig.java import org.dontpanic.spanners.api.data.Spanner; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter; package org.dontpanic.spanners.api.config; /** * Custom configuration for Spring Data REST * Created by stevie on 10/06/16. */ @Configuration @EnableDiscoveryClient public class RestConfig extends RepositoryRestConfigurerAdapter { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.exposeIdsFor(Spanner.class);
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/DisplaySpannersController.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/exception/SpannerNotFoundException.java // public class SpannerNotFoundException extends Exception { // // private Long spannerId; // // /** // * New exception // * @param spannerId id of requested spanner // */ // public SpannerNotFoundException(Long spannerId) { // super("Spanner not found: " + spannerId); // this.spannerId = spannerId; // } // // public Long getSpannerId() { // return spannerId; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.time.LocalTime; import java.util.Collection; import java.util.function.Supplier;
package org.dontpanic.spanners.springmvc.controllers; /** * Controller for page that displays all spanners * User: Stevie * Date: 05/10/13 */ @Controller public class DisplaySpannersController { static final String CONTROLLER_URL = "/displaySpanners"; static final String VIEW_DISPLAY_SPANNERS = "displaySpanners"; static final String MODEL_ATTRIBUTE_SPANNERS = "spanners"; static final String MODEL_ATTRIBUTE_GREETING = "greeting"; static final String GREETING_MORNING = "Good morning"; static final String GREETING_AFTERNOON = "Good afternoon"; static final String GREETING_EVENING = "Good Evening"; private Supplier<LocalTime> currentTime = LocalTime::now;
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/exception/SpannerNotFoundException.java // public class SpannerNotFoundException extends Exception { // // private Long spannerId; // // /** // * New exception // * @param spannerId id of requested spanner // */ // public SpannerNotFoundException(Long spannerId) { // super("Spanner not found: " + spannerId); // this.spannerId = spannerId; // } // // public Long getSpannerId() { // return spannerId; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/DisplaySpannersController.java import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.time.LocalTime; import java.util.Collection; import java.util.function.Supplier; package org.dontpanic.spanners.springmvc.controllers; /** * Controller for page that displays all spanners * User: Stevie * Date: 05/10/13 */ @Controller public class DisplaySpannersController { static final String CONTROLLER_URL = "/displaySpanners"; static final String VIEW_DISPLAY_SPANNERS = "displaySpanners"; static final String MODEL_ATTRIBUTE_SPANNERS = "spanners"; static final String MODEL_ATTRIBUTE_GREETING = "greeting"; static final String GREETING_MORNING = "Good morning"; static final String GREETING_AFTERNOON = "Good afternoon"; static final String GREETING_EVENING = "Good Evening"; private Supplier<LocalTime> currentTime = LocalTime::now;
@Autowired private SpannersService spannersService;
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/DisplaySpannersController.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/exception/SpannerNotFoundException.java // public class SpannerNotFoundException extends Exception { // // private Long spannerId; // // /** // * New exception // * @param spannerId id of requested spanner // */ // public SpannerNotFoundException(Long spannerId) { // super("Spanner not found: " + spannerId); // this.spannerId = spannerId; // } // // public Long getSpannerId() { // return spannerId; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.time.LocalTime; import java.util.Collection; import java.util.function.Supplier;
package org.dontpanic.spanners.springmvc.controllers; /** * Controller for page that displays all spanners * User: Stevie * Date: 05/10/13 */ @Controller public class DisplaySpannersController { static final String CONTROLLER_URL = "/displaySpanners"; static final String VIEW_DISPLAY_SPANNERS = "displaySpanners"; static final String MODEL_ATTRIBUTE_SPANNERS = "spanners"; static final String MODEL_ATTRIBUTE_GREETING = "greeting"; static final String GREETING_MORNING = "Good morning"; static final String GREETING_AFTERNOON = "Good afternoon"; static final String GREETING_EVENING = "Good Evening"; private Supplier<LocalTime> currentTime = LocalTime::now; @Autowired private SpannersService spannersService; /** * Display all spanners */ @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { // Load the spanners from database
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/exception/SpannerNotFoundException.java // public class SpannerNotFoundException extends Exception { // // private Long spannerId; // // /** // * New exception // * @param spannerId id of requested spanner // */ // public SpannerNotFoundException(Long spannerId) { // super("Spanner not found: " + spannerId); // this.spannerId = spannerId; // } // // public Long getSpannerId() { // return spannerId; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/DisplaySpannersController.java import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.time.LocalTime; import java.util.Collection; import java.util.function.Supplier; package org.dontpanic.spanners.springmvc.controllers; /** * Controller for page that displays all spanners * User: Stevie * Date: 05/10/13 */ @Controller public class DisplaySpannersController { static final String CONTROLLER_URL = "/displaySpanners"; static final String VIEW_DISPLAY_SPANNERS = "displaySpanners"; static final String MODEL_ATTRIBUTE_SPANNERS = "spanners"; static final String MODEL_ATTRIBUTE_GREETING = "greeting"; static final String GREETING_MORNING = "Good morning"; static final String GREETING_AFTERNOON = "Good afternoon"; static final String GREETING_EVENING = "Good Evening"; private Supplier<LocalTime> currentTime = LocalTime::now; @Autowired private SpannersService spannersService; /** * Display all spanners */ @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { // Load the spanners from database
Collection<Spanner> spanners = spannersService.findAll();
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/DisplaySpannersController.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/exception/SpannerNotFoundException.java // public class SpannerNotFoundException extends Exception { // // private Long spannerId; // // /** // * New exception // * @param spannerId id of requested spanner // */ // public SpannerNotFoundException(Long spannerId) { // super("Spanner not found: " + spannerId); // this.spannerId = spannerId; // } // // public Long getSpannerId() { // return spannerId; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.time.LocalTime; import java.util.Collection; import java.util.function.Supplier;
package org.dontpanic.spanners.springmvc.controllers; /** * Controller for page that displays all spanners * User: Stevie * Date: 05/10/13 */ @Controller public class DisplaySpannersController { static final String CONTROLLER_URL = "/displaySpanners"; static final String VIEW_DISPLAY_SPANNERS = "displaySpanners"; static final String MODEL_ATTRIBUTE_SPANNERS = "spanners"; static final String MODEL_ATTRIBUTE_GREETING = "greeting"; static final String GREETING_MORNING = "Good morning"; static final String GREETING_AFTERNOON = "Good afternoon"; static final String GREETING_EVENING = "Good Evening"; private Supplier<LocalTime> currentTime = LocalTime::now; @Autowired private SpannersService spannersService; /** * Display all spanners */ @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { // Load the spanners from database Collection<Spanner> spanners = spannersService.findAll(); // Use greeting appropriate to time of day String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } /** * Delete a single spanner */ @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET)
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/exception/SpannerNotFoundException.java // public class SpannerNotFoundException extends Exception { // // private Long spannerId; // // /** // * New exception // * @param spannerId id of requested spanner // */ // public SpannerNotFoundException(Long spannerId) { // super("Spanner not found: " + spannerId); // this.spannerId = spannerId; // } // // public Long getSpannerId() { // return spannerId; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/DisplaySpannersController.java import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.time.LocalTime; import java.util.Collection; import java.util.function.Supplier; package org.dontpanic.spanners.springmvc.controllers; /** * Controller for page that displays all spanners * User: Stevie * Date: 05/10/13 */ @Controller public class DisplaySpannersController { static final String CONTROLLER_URL = "/displaySpanners"; static final String VIEW_DISPLAY_SPANNERS = "displaySpanners"; static final String MODEL_ATTRIBUTE_SPANNERS = "spanners"; static final String MODEL_ATTRIBUTE_GREETING = "greeting"; static final String GREETING_MORNING = "Good morning"; static final String GREETING_AFTERNOON = "Good afternoon"; static final String GREETING_EVENING = "Good Evening"; private Supplier<LocalTime> currentTime = LocalTime::now; @Autowired private SpannersService spannersService; /** * Display all spanners */ @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { // Load the spanners from database Collection<Spanner> spanners = spannersService.findAll(); // Use greeting appropriate to time of day String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } /** * Delete a single spanner */ @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET)
public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException {
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SpannerForm.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.Size;
package org.dontpanic.spanners.springmvc.forms; /** * A form that allows editing of spanner attributes * User: Stevie * Date: 22/10/13 */ public class SpannerForm { public static final String FIELD_NAME = "name"; public static final String FIELD_SIZE = "size"; private Long id; @Size(min=1, max=255) private String name; @Min(1) @Max(99) private int size; public SpannerForm() { } /** * Create a spanner form with values initialized to given spanner */
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SpannerForm.java import org.dontpanic.spanners.springmvc.domain.Spanner; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.Size; package org.dontpanic.spanners.springmvc.forms; /** * A form that allows editing of spanner attributes * User: Stevie * Date: 22/10/13 */ public class SpannerForm { public static final String FIELD_NAME = "name"; public static final String FIELD_SIZE = "size"; private Long id; @Size(min=1, max=255) private String name; @Min(1) @Max(99) private int size; public SpannerForm() { } /** * Create a spanner form with values initialized to given spanner */
public SpannerForm(Spanner spanner) {
hotblac/spanners
spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannersStubs.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull;
package org.dontpanic.spanners.springmvc.stubs; /** * Stubs for spanners * User: Stevie * Date: 13/10/13 */ public class SpannersStubs { public static final Long SPANNER_ID = 99l;
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannersStubs.java import org.dontpanic.spanners.springmvc.domain.Spanner; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; package org.dontpanic.spanners.springmvc.stubs; /** * Stubs for spanners * User: Stevie * Date: 13/10/13 */ public class SpannersStubs { public static final Long SPANNER_ID = 99l;
public static final Spanner SPANNER = stubSpanner(SPANNER_ID);
hotblac/spanners
spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/services/RestUserDetailsServiceTest.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/User.java // public class User implements UserDetails { // // private String username; // private String password; // private Boolean enabled; // // public User() { // } // // public User(String username, String password, Boolean enabled) { // this.username = username; // this.password = password; // this.enabled = enabled; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Boolean getEnabled() { // return enabled; // } // // public void setEnabled(Boolean enabled) { // this.enabled = enabled; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return enabled; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptySet(); // } // }
import org.dontpanic.spanners.springmvc.domain.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.client.ResponseCreator; import static org.junit.Assert.*; import static org.springframework.http.HttpMethod.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
package org.dontpanic.spanners.springmvc.services; /** * Unit tests for the Rest user details service * Created by stevie on 14/07/16. */ @RunWith(SpringRunner.class) @RestClientTest(RestUserDetailsService.class) public class RestUserDetailsServiceTest { private static final String USERNAME = "jbloggs"; private static final String PASSWORD = "password123"; private static final boolean ENABLED = true; private static final MediaType APPLICATION_HAL_JSON = MediaType.valueOf("application/hal+json;charset=UTF-8"); @Autowired private MockRestServiceServer server; @Autowired private RestUserDetailsService service; @Test public void testLoadUserByUsername() { server.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withHalJsonResponse("/user_jbloggs_GET.txt")); UserDetails userDetails = service.loadUserByUsername(USERNAME); assertNotNull(userDetails); } @Test public void testCreateUser() throws Exception { server.expect(requestTo("/")).andExpect(method(POST)) .andRespond(withStatus(HttpStatus.CREATED));
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/User.java // public class User implements UserDetails { // // private String username; // private String password; // private Boolean enabled; // // public User() { // } // // public User(String username, String password, Boolean enabled) { // this.username = username; // this.password = password; // this.enabled = enabled; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Boolean getEnabled() { // return enabled; // } // // public void setEnabled(Boolean enabled) { // this.enabled = enabled; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return enabled; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptySet(); // } // } // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/services/RestUserDetailsServiceTest.java import org.dontpanic.spanners.springmvc.domain.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.client.ResponseCreator; import static org.junit.Assert.*; import static org.springframework.http.HttpMethod.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; package org.dontpanic.spanners.springmvc.services; /** * Unit tests for the Rest user details service * Created by stevie on 14/07/16. */ @RunWith(SpringRunner.class) @RestClientTest(RestUserDetailsService.class) public class RestUserDetailsServiceTest { private static final String USERNAME = "jbloggs"; private static final String PASSWORD = "password123"; private static final boolean ENABLED = true; private static final MediaType APPLICATION_HAL_JSON = MediaType.valueOf("application/hal+json;charset=UTF-8"); @Autowired private MockRestServiceServer server; @Autowired private RestUserDetailsService service; @Test public void testLoadUserByUsername() { server.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withHalJsonResponse("/user_jbloggs_GET.txt")); UserDetails userDetails = service.loadUserByUsername(USERNAME); assertNotNull(userDetails); } @Test public void testCreateUser() throws Exception { server.expect(requestTo("/")).andExpect(method(POST)) .andRespond(withStatus(HttpStatus.CREATED));
UserDetails user = new User(USERNAME, PASSWORD, ENABLED);
hotblac/spanners
spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/controllers/SignupControllerTest.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SignupForm.java // public class SignupForm { // // private static final String NOT_BLANK_MESSAGE = "{notBlank.message}"; // // @NotBlank(message = NOT_BLANK_MESSAGE) // private String name; // @NotBlank(message = NOT_BLANK_MESSAGE) // private String password; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/rules/SystemOutResource.java // public class SystemOutResource extends ExternalResource { // // private PrintStream sysOut; // private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); // // @Override // protected void before() throws Throwable { // sysOut = System.out; // System.setOut(new PrintStream(outContent)); // } // // @Override // protected void after() { // System.setOut(sysOut); // } // // public String asString() { // return outContent.toString(); // } // }
import org.dontpanic.spanners.springmvc.forms.SignupForm; import org.dontpanic.spanners.springmvc.rules.SystemOutResource; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.validation.DirectFieldBindingResult; import org.springframework.validation.Errors; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasProperty; import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.*;
package org.dontpanic.spanners.springmvc.controllers; /** * Unit tests for the signup controller * Created by stevie on 11/08/16. */ @RunWith(MockitoJUnitRunner.class) public class SignupControllerTest { private static final String NAME = "smith"; private static final String PASSWORD = "password"; private static final String HASHED_PASSWORD = "XXXhashedpasswordXXX"; @Mock private UserDetailsManager userDetailsManager; @Mock private PasswordEncoder passwordEncoder; @InjectMocks private SignupController controller = new SignupController();
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SignupForm.java // public class SignupForm { // // private static final String NOT_BLANK_MESSAGE = "{notBlank.message}"; // // @NotBlank(message = NOT_BLANK_MESSAGE) // private String name; // @NotBlank(message = NOT_BLANK_MESSAGE) // private String password; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/rules/SystemOutResource.java // public class SystemOutResource extends ExternalResource { // // private PrintStream sysOut; // private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); // // @Override // protected void before() throws Throwable { // sysOut = System.out; // System.setOut(new PrintStream(outContent)); // } // // @Override // protected void after() { // System.setOut(sysOut); // } // // public String asString() { // return outContent.toString(); // } // } // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/controllers/SignupControllerTest.java import org.dontpanic.spanners.springmvc.forms.SignupForm; import org.dontpanic.spanners.springmvc.rules.SystemOutResource; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.validation.DirectFieldBindingResult; import org.springframework.validation.Errors; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasProperty; import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.*; package org.dontpanic.spanners.springmvc.controllers; /** * Unit tests for the signup controller * Created by stevie on 11/08/16. */ @RunWith(MockitoJUnitRunner.class) public class SignupControllerTest { private static final String NAME = "smith"; private static final String PASSWORD = "password"; private static final String HASHED_PASSWORD = "XXXhashedpasswordXXX"; @Mock private UserDetailsManager userDetailsManager; @Mock private PasswordEncoder passwordEncoder; @InjectMocks private SignupController controller = new SignupController();
@Rule public SystemOutResource sysOut = new SystemOutResource();
hotblac/spanners
spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/controllers/SignupControllerTest.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SignupForm.java // public class SignupForm { // // private static final String NOT_BLANK_MESSAGE = "{notBlank.message}"; // // @NotBlank(message = NOT_BLANK_MESSAGE) // private String name; // @NotBlank(message = NOT_BLANK_MESSAGE) // private String password; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/rules/SystemOutResource.java // public class SystemOutResource extends ExternalResource { // // private PrintStream sysOut; // private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); // // @Override // protected void before() throws Throwable { // sysOut = System.out; // System.setOut(new PrintStream(outContent)); // } // // @Override // protected void after() { // System.setOut(sysOut); // } // // public String asString() { // return outContent.toString(); // } // }
import org.dontpanic.spanners.springmvc.forms.SignupForm; import org.dontpanic.spanners.springmvc.rules.SystemOutResource; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.validation.DirectFieldBindingResult; import org.springframework.validation.Errors; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasProperty; import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.*;
package org.dontpanic.spanners.springmvc.controllers; /** * Unit tests for the signup controller * Created by stevie on 11/08/16. */ @RunWith(MockitoJUnitRunner.class) public class SignupControllerTest { private static final String NAME = "smith"; private static final String PASSWORD = "password"; private static final String HASHED_PASSWORD = "XXXhashedpasswordXXX"; @Mock private UserDetailsManager userDetailsManager; @Mock private PasswordEncoder passwordEncoder; @InjectMocks private SignupController controller = new SignupController(); @Rule public SystemOutResource sysOut = new SystemOutResource(); @Test public void testSuccessForward() {
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SignupForm.java // public class SignupForm { // // private static final String NOT_BLANK_MESSAGE = "{notBlank.message}"; // // @NotBlank(message = NOT_BLANK_MESSAGE) // private String name; // @NotBlank(message = NOT_BLANK_MESSAGE) // private String password; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/rules/SystemOutResource.java // public class SystemOutResource extends ExternalResource { // // private PrintStream sysOut; // private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); // // @Override // protected void before() throws Throwable { // sysOut = System.out; // System.setOut(new PrintStream(outContent)); // } // // @Override // protected void after() { // System.setOut(sysOut); // } // // public String asString() { // return outContent.toString(); // } // } // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/controllers/SignupControllerTest.java import org.dontpanic.spanners.springmvc.forms.SignupForm; import org.dontpanic.spanners.springmvc.rules.SystemOutResource; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.validation.DirectFieldBindingResult; import org.springframework.validation.Errors; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasProperty; import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.*; package org.dontpanic.spanners.springmvc.controllers; /** * Unit tests for the signup controller * Created by stevie on 11/08/16. */ @RunWith(MockitoJUnitRunner.class) public class SignupControllerTest { private static final String NAME = "smith"; private static final String PASSWORD = "password"; private static final String HASHED_PASSWORD = "XXXhashedpasswordXXX"; @Mock private UserDetailsManager userDetailsManager; @Mock private PasswordEncoder passwordEncoder; @InjectMocks private SignupController controller = new SignupController(); @Rule public SystemOutResource sysOut = new SystemOutResource(); @Test public void testSuccessForward() {
SignupForm form = populateForm(NAME, PASSWORD);
hotblac/spanners
spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/services/SpannersServiceTest.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannerAssert.java // public static void assertSpanner(String expectedName, int expectedSize, String expectedOwner, Spanner actual) { // assertNotNull("Spanner is null", actual); // assertEquals("spanner name", expectedName, actual.getName()); // assertEquals("spanner size", expectedSize, actual.getSize()); // assertEquals("spanner owner", expectedOwner, actual.getOwner()); // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannerBuilder.java // public static SpannerBuilder aSpanner() { // return new SpannerBuilder(); // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.client.ResponseCreator; import java.util.Collection; import static org.dontpanic.spanners.springmvc.stubs.SpannerAssert.assertSpanner; import static org.dontpanic.spanners.springmvc.stubs.SpannerBuilder.aSpanner; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.springframework.http.HttpMethod.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
package org.dontpanic.spanners.springmvc.services; /** * Test for Spanners REST service client * Created by stevie on 09/06/16. */ @RunWith(SpringRunner.class) @RestClientTest(SpannersService.class) public class SpannersServiceTest { private static final MediaType APPLICATION_HAL_JSON = MediaType.valueOf("application/hal+json;charset=UTF-8"); @Autowired private MockRestServiceServer server; @Autowired private SpannersService service; @Test public void testFindAll() throws Exception { server.expect(requestTo("/")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spannersGET.txt"));
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannerAssert.java // public static void assertSpanner(String expectedName, int expectedSize, String expectedOwner, Spanner actual) { // assertNotNull("Spanner is null", actual); // assertEquals("spanner name", expectedName, actual.getName()); // assertEquals("spanner size", expectedSize, actual.getSize()); // assertEquals("spanner owner", expectedOwner, actual.getOwner()); // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannerBuilder.java // public static SpannerBuilder aSpanner() { // return new SpannerBuilder(); // } // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/services/SpannersServiceTest.java import org.dontpanic.spanners.springmvc.domain.Spanner; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.client.ResponseCreator; import java.util.Collection; import static org.dontpanic.spanners.springmvc.stubs.SpannerAssert.assertSpanner; import static org.dontpanic.spanners.springmvc.stubs.SpannerBuilder.aSpanner; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.springframework.http.HttpMethod.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; package org.dontpanic.spanners.springmvc.services; /** * Test for Spanners REST service client * Created by stevie on 09/06/16. */ @RunWith(SpringRunner.class) @RestClientTest(SpannersService.class) public class SpannersServiceTest { private static final MediaType APPLICATION_HAL_JSON = MediaType.valueOf("application/hal+json;charset=UTF-8"); @Autowired private MockRestServiceServer server; @Autowired private SpannersService service; @Test public void testFindAll() throws Exception { server.expect(requestTo("/")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spannersGET.txt"));
Collection<Spanner> spanners = service.findAll();
hotblac/spanners
spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/services/SpannersServiceTest.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannerAssert.java // public static void assertSpanner(String expectedName, int expectedSize, String expectedOwner, Spanner actual) { // assertNotNull("Spanner is null", actual); // assertEquals("spanner name", expectedName, actual.getName()); // assertEquals("spanner size", expectedSize, actual.getSize()); // assertEquals("spanner owner", expectedOwner, actual.getOwner()); // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannerBuilder.java // public static SpannerBuilder aSpanner() { // return new SpannerBuilder(); // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.client.ResponseCreator; import java.util.Collection; import static org.dontpanic.spanners.springmvc.stubs.SpannerAssert.assertSpanner; import static org.dontpanic.spanners.springmvc.stubs.SpannerBuilder.aSpanner; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.springframework.http.HttpMethod.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
package org.dontpanic.spanners.springmvc.services; /** * Test for Spanners REST service client * Created by stevie on 09/06/16. */ @RunWith(SpringRunner.class) @RestClientTest(SpannersService.class) public class SpannersServiceTest { private static final MediaType APPLICATION_HAL_JSON = MediaType.valueOf("application/hal+json;charset=UTF-8"); @Autowired private MockRestServiceServer server; @Autowired private SpannersService service; @Test public void testFindAll() throws Exception { server.expect(requestTo("/")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spannersGET.txt")); Collection<Spanner> spanners = service.findAll(); assertThat(spanners, hasSize(2)); } @Test public void testFindOne() throws Exception { server.expect(requestTo("/1")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spanner1GET.txt")); Spanner spanner = service.findOne(1L);
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannerAssert.java // public static void assertSpanner(String expectedName, int expectedSize, String expectedOwner, Spanner actual) { // assertNotNull("Spanner is null", actual); // assertEquals("spanner name", expectedName, actual.getName()); // assertEquals("spanner size", expectedSize, actual.getSize()); // assertEquals("spanner owner", expectedOwner, actual.getOwner()); // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannerBuilder.java // public static SpannerBuilder aSpanner() { // return new SpannerBuilder(); // } // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/services/SpannersServiceTest.java import org.dontpanic.spanners.springmvc.domain.Spanner; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.client.ResponseCreator; import java.util.Collection; import static org.dontpanic.spanners.springmvc.stubs.SpannerAssert.assertSpanner; import static org.dontpanic.spanners.springmvc.stubs.SpannerBuilder.aSpanner; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.springframework.http.HttpMethod.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; package org.dontpanic.spanners.springmvc.services; /** * Test for Spanners REST service client * Created by stevie on 09/06/16. */ @RunWith(SpringRunner.class) @RestClientTest(SpannersService.class) public class SpannersServiceTest { private static final MediaType APPLICATION_HAL_JSON = MediaType.valueOf("application/hal+json;charset=UTF-8"); @Autowired private MockRestServiceServer server; @Autowired private SpannersService service; @Test public void testFindAll() throws Exception { server.expect(requestTo("/")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spannersGET.txt")); Collection<Spanner> spanners = service.findAll(); assertThat(spanners, hasSize(2)); } @Test public void testFindOne() throws Exception { server.expect(requestTo("/1")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spanner1GET.txt")); Spanner spanner = service.findOne(1L);
assertSpanner("Belinda", 10, "jones", spanner);
hotblac/spanners
spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/services/SpannersServiceTest.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannerAssert.java // public static void assertSpanner(String expectedName, int expectedSize, String expectedOwner, Spanner actual) { // assertNotNull("Spanner is null", actual); // assertEquals("spanner name", expectedName, actual.getName()); // assertEquals("spanner size", expectedSize, actual.getSize()); // assertEquals("spanner owner", expectedOwner, actual.getOwner()); // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannerBuilder.java // public static SpannerBuilder aSpanner() { // return new SpannerBuilder(); // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.client.ResponseCreator; import java.util.Collection; import static org.dontpanic.spanners.springmvc.stubs.SpannerAssert.assertSpanner; import static org.dontpanic.spanners.springmvc.stubs.SpannerBuilder.aSpanner; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.springframework.http.HttpMethod.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
package org.dontpanic.spanners.springmvc.services; /** * Test for Spanners REST service client * Created by stevie on 09/06/16. */ @RunWith(SpringRunner.class) @RestClientTest(SpannersService.class) public class SpannersServiceTest { private static final MediaType APPLICATION_HAL_JSON = MediaType.valueOf("application/hal+json;charset=UTF-8"); @Autowired private MockRestServiceServer server; @Autowired private SpannersService service; @Test public void testFindAll() throws Exception { server.expect(requestTo("/")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spannersGET.txt")); Collection<Spanner> spanners = service.findAll(); assertThat(spanners, hasSize(2)); } @Test public void testFindOne() throws Exception { server.expect(requestTo("/1")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spanner1GET.txt")); Spanner spanner = service.findOne(1L); assertSpanner("Belinda", 10, "jones", spanner); } @Test public void testDelete() throws Exception { server.expect(requestTo("/1")).andExpect(method(DELETE)) .andRespond(withStatus(HttpStatus.NO_CONTENT));
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannerAssert.java // public static void assertSpanner(String expectedName, int expectedSize, String expectedOwner, Spanner actual) { // assertNotNull("Spanner is null", actual); // assertEquals("spanner name", expectedName, actual.getName()); // assertEquals("spanner size", expectedSize, actual.getSize()); // assertEquals("spanner owner", expectedOwner, actual.getOwner()); // } // // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/stubs/SpannerBuilder.java // public static SpannerBuilder aSpanner() { // return new SpannerBuilder(); // } // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/services/SpannersServiceTest.java import org.dontpanic.spanners.springmvc.domain.Spanner; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.client.ResponseCreator; import java.util.Collection; import static org.dontpanic.spanners.springmvc.stubs.SpannerAssert.assertSpanner; import static org.dontpanic.spanners.springmvc.stubs.SpannerBuilder.aSpanner; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.springframework.http.HttpMethod.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; package org.dontpanic.spanners.springmvc.services; /** * Test for Spanners REST service client * Created by stevie on 09/06/16. */ @RunWith(SpringRunner.class) @RestClientTest(SpannersService.class) public class SpannersServiceTest { private static final MediaType APPLICATION_HAL_JSON = MediaType.valueOf("application/hal+json;charset=UTF-8"); @Autowired private MockRestServiceServer server; @Autowired private SpannersService service; @Test public void testFindAll() throws Exception { server.expect(requestTo("/")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spannersGET.txt")); Collection<Spanner> spanners = service.findAll(); assertThat(spanners, hasSize(2)); } @Test public void testFindOne() throws Exception { server.expect(requestTo("/1")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spanner1GET.txt")); Spanner spanner = service.findOne(1L); assertSpanner("Belinda", 10, "jones", spanner); } @Test public void testDelete() throws Exception { server.expect(requestTo("/1")).andExpect(method(DELETE)) .andRespond(withStatus(HttpStatus.NO_CONTENT));
Spanner susan = aSpanner().withId(1L).named("Susan").build();
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/SignupController.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/User.java // public class User implements UserDetails { // // private String username; // private String password; // private Boolean enabled; // // public User() { // } // // public User(String username, String password, Boolean enabled) { // this.username = username; // this.password = password; // this.enabled = enabled; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Boolean getEnabled() { // return enabled; // } // // public void setEnabled(Boolean enabled) { // this.enabled = enabled; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return enabled; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptySet(); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SignupForm.java // public class SignupForm { // // private static final String NOT_BLANK_MESSAGE = "{notBlank.message}"; // // @NotBlank(message = NOT_BLANK_MESSAGE) // private String name; // @NotBlank(message = NOT_BLANK_MESSAGE) // private String password; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import org.apache.log4j.Logger; import org.dontpanic.spanners.springmvc.domain.User; import org.dontpanic.spanners.springmvc.forms.SignupForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.stereotype.Controller; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.validation.Valid;
package org.dontpanic.spanners.springmvc.controllers; /** * Controller for the signup page. This page creates new user accounts. * Created by stevie on 29/12/15. */ @Controller public class SignupController { private Logger log = Logger.getLogger(SignupController.class); public static final String CONTROLLER_URL = "/signup"; public static final String VIEW_SUCCESS = "redirect:/"; private static final boolean ENABLED = true; /** * UserDetailsManager provided by Spring Security allows CRUD operations on user accounts */ @Autowired private UserDetailsManager userDetailsManager; @Autowired private PasswordEncoder passwordEncoder; @RequestMapping(value = CONTROLLER_URL)
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/User.java // public class User implements UserDetails { // // private String username; // private String password; // private Boolean enabled; // // public User() { // } // // public User(String username, String password, Boolean enabled) { // this.username = username; // this.password = password; // this.enabled = enabled; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Boolean getEnabled() { // return enabled; // } // // public void setEnabled(Boolean enabled) { // this.enabled = enabled; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return enabled; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptySet(); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SignupForm.java // public class SignupForm { // // private static final String NOT_BLANK_MESSAGE = "{notBlank.message}"; // // @NotBlank(message = NOT_BLANK_MESSAGE) // private String name; // @NotBlank(message = NOT_BLANK_MESSAGE) // private String password; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/SignupController.java import org.apache.log4j.Logger; import org.dontpanic.spanners.springmvc.domain.User; import org.dontpanic.spanners.springmvc.forms.SignupForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.stereotype.Controller; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.validation.Valid; package org.dontpanic.spanners.springmvc.controllers; /** * Controller for the signup page. This page creates new user accounts. * Created by stevie on 29/12/15. */ @Controller public class SignupController { private Logger log = Logger.getLogger(SignupController.class); public static final String CONTROLLER_URL = "/signup"; public static final String VIEW_SUCCESS = "redirect:/"; private static final boolean ENABLED = true; /** * UserDetailsManager provided by Spring Security allows CRUD operations on user accounts */ @Autowired private UserDetailsManager userDetailsManager; @Autowired private PasswordEncoder passwordEncoder; @RequestMapping(value = CONTROLLER_URL)
public SignupForm displayPage() {
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/SignupController.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/User.java // public class User implements UserDetails { // // private String username; // private String password; // private Boolean enabled; // // public User() { // } // // public User(String username, String password, Boolean enabled) { // this.username = username; // this.password = password; // this.enabled = enabled; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Boolean getEnabled() { // return enabled; // } // // public void setEnabled(Boolean enabled) { // this.enabled = enabled; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return enabled; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptySet(); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SignupForm.java // public class SignupForm { // // private static final String NOT_BLANK_MESSAGE = "{notBlank.message}"; // // @NotBlank(message = NOT_BLANK_MESSAGE) // private String name; // @NotBlank(message = NOT_BLANK_MESSAGE) // private String password; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import org.apache.log4j.Logger; import org.dontpanic.spanners.springmvc.domain.User; import org.dontpanic.spanners.springmvc.forms.SignupForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.stereotype.Controller; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.validation.Valid;
package org.dontpanic.spanners.springmvc.controllers; /** * Controller for the signup page. This page creates new user accounts. * Created by stevie on 29/12/15. */ @Controller public class SignupController { private Logger log = Logger.getLogger(SignupController.class); public static final String CONTROLLER_URL = "/signup"; public static final String VIEW_SUCCESS = "redirect:/"; private static final boolean ENABLED = true; /** * UserDetailsManager provided by Spring Security allows CRUD operations on user accounts */ @Autowired private UserDetailsManager userDetailsManager; @Autowired private PasswordEncoder passwordEncoder; @RequestMapping(value = CONTROLLER_URL) public SignupForm displayPage() { return new SignupForm(); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } // Hash the password String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); // Create the account
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/User.java // public class User implements UserDetails { // // private String username; // private String password; // private Boolean enabled; // // public User() { // } // // public User(String username, String password, Boolean enabled) { // this.username = username; // this.password = password; // this.enabled = enabled; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Boolean getEnabled() { // return enabled; // } // // public void setEnabled(Boolean enabled) { // this.enabled = enabled; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return enabled; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptySet(); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/forms/SignupForm.java // public class SignupForm { // // private static final String NOT_BLANK_MESSAGE = "{notBlank.message}"; // // @NotBlank(message = NOT_BLANK_MESSAGE) // private String name; // @NotBlank(message = NOT_BLANK_MESSAGE) // private String password; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/SignupController.java import org.apache.log4j.Logger; import org.dontpanic.spanners.springmvc.domain.User; import org.dontpanic.spanners.springmvc.forms.SignupForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.stereotype.Controller; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.validation.Valid; package org.dontpanic.spanners.springmvc.controllers; /** * Controller for the signup page. This page creates new user accounts. * Created by stevie on 29/12/15. */ @Controller public class SignupController { private Logger log = Logger.getLogger(SignupController.class); public static final String CONTROLLER_URL = "/signup"; public static final String VIEW_SUCCESS = "redirect:/"; private static final boolean ENABLED = true; /** * UserDetailsManager provided by Spring Security allows CRUD operations on user accounts */ @Autowired private UserDetailsManager userDetailsManager; @Autowired private PasswordEncoder passwordEncoder; @RequestMapping(value = CONTROLLER_URL) public SignupForm displayPage() { return new SignupForm(); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } // Hash the password String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); // Create the account
UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED);
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/DetailSpannerController.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/exception/SpannerNotFoundException.java // public class SpannerNotFoundException extends Exception { // // private Long spannerId; // // /** // * New exception // * @param spannerId id of requested spanner // */ // public SpannerNotFoundException(Long spannerId) { // super("Spanner not found: " + spannerId); // this.spannerId = spannerId; // } // // public Long getSpannerId() { // return spannerId; // } // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView;
package org.dontpanic.spanners.springmvc.controllers; /** * Displays detail of a single spanner * User: Stevie * Date: 13/10/13 */ @Controller public class DetailSpannerController { public static final String VIEW_DETAIL_SPANNER = "detailSpanner"; public static final String MODEL_SPANNER = "spanner";
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/exception/SpannerNotFoundException.java // public class SpannerNotFoundException extends Exception { // // private Long spannerId; // // /** // * New exception // * @param spannerId id of requested spanner // */ // public SpannerNotFoundException(Long spannerId) { // super("Spanner not found: " + spannerId); // this.spannerId = spannerId; // } // // public Long getSpannerId() { // return spannerId; // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/DetailSpannerController.java import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; package org.dontpanic.spanners.springmvc.controllers; /** * Displays detail of a single spanner * User: Stevie * Date: 13/10/13 */ @Controller public class DetailSpannerController { public static final String VIEW_DETAIL_SPANNER = "detailSpanner"; public static final String MODEL_SPANNER = "spanner";
@Autowired private SpannersService spannersService;
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/DetailSpannerController.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/exception/SpannerNotFoundException.java // public class SpannerNotFoundException extends Exception { // // private Long spannerId; // // /** // * New exception // * @param spannerId id of requested spanner // */ // public SpannerNotFoundException(Long spannerId) { // super("Spanner not found: " + spannerId); // this.spannerId = spannerId; // } // // public Long getSpannerId() { // return spannerId; // } // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView;
package org.dontpanic.spanners.springmvc.controllers; /** * Displays detail of a single spanner * User: Stevie * Date: 13/10/13 */ @Controller public class DetailSpannerController { public static final String VIEW_DETAIL_SPANNER = "detailSpanner"; public static final String MODEL_SPANNER = "spanner"; @Autowired private SpannersService spannersService; @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET)
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/exception/SpannerNotFoundException.java // public class SpannerNotFoundException extends Exception { // // private Long spannerId; // // /** // * New exception // * @param spannerId id of requested spanner // */ // public SpannerNotFoundException(Long spannerId) { // super("Spanner not found: " + spannerId); // this.spannerId = spannerId; // } // // public Long getSpannerId() { // return spannerId; // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/DetailSpannerController.java import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; package org.dontpanic.spanners.springmvc.controllers; /** * Displays detail of a single spanner * User: Stevie * Date: 13/10/13 */ @Controller public class DetailSpannerController { public static final String VIEW_DETAIL_SPANNER = "detailSpanner"; public static final String MODEL_SPANNER = "spanner"; @Autowired private SpannersService spannersService; @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET)
public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException {
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/DetailSpannerController.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/exception/SpannerNotFoundException.java // public class SpannerNotFoundException extends Exception { // // private Long spannerId; // // /** // * New exception // * @param spannerId id of requested spanner // */ // public SpannerNotFoundException(Long spannerId) { // super("Spanner not found: " + spannerId); // this.spannerId = spannerId; // } // // public Long getSpannerId() { // return spannerId; // } // }
import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView;
package org.dontpanic.spanners.springmvc.controllers; /** * Displays detail of a single spanner * User: Stevie * Date: 13/10/13 */ @Controller public class DetailSpannerController { public static final String VIEW_DETAIL_SPANNER = "detailSpanner"; public static final String MODEL_SPANNER = "spanner"; @Autowired private SpannersService spannersService; @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { // Fetch the spanner
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/Spanner.java // public class Spanner { // // private Long id; // private String name; // private int size; // private String owner; // // 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; // } // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/SpannersService.java // @Service // public class SpannersService { // // private RestTemplate restTemplate; // // public SpannersService(RestTemplateBuilder builder, // @Value("${app.service.url.spanners}") String rootUri) { // restTemplate = builder.messageConverters(halAwareMessageConverter()) // .rootUri(rootUri).build(); // } // // // private HttpMessageConverter halAwareMessageConverter() { // ObjectMapper mapper = new ObjectMapper(); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.registerModule(new Jackson2HalModule()); // // return new MappingJackson2HttpMessageConverter(mapper); // } // // // public Collection<Spanner> findAll() { // ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, // new ParameterizedTypeReference<PagedResources<Spanner>>(){}); // PagedResources<Spanner> pages = response.getBody(); // return pages.getContent(); // // } // // // public Spanner findOne(Long id) { // return restTemplate.getForObject("/{0}", Spanner.class, id); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void delete(Spanner spanner) { // restTemplate.delete("/{0}", spanner.getId()); // } // // // public void create(Spanner spanner) { // restTemplate.postForObject("/", spanner, Spanner.class); // } // // // @PreAuthorize("hasPermission(#spanner, 'owner')") // public void update(Spanner spanner) { // restTemplate.put("/{0}", spanner, spanner.getId()); // } // } // // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/exception/SpannerNotFoundException.java // public class SpannerNotFoundException extends Exception { // // private Long spannerId; // // /** // * New exception // * @param spannerId id of requested spanner // */ // public SpannerNotFoundException(Long spannerId) { // super("Spanner not found: " + spannerId); // this.spannerId = spannerId; // } // // public Long getSpannerId() { // return spannerId; // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/DetailSpannerController.java import org.dontpanic.spanners.springmvc.domain.Spanner; import org.dontpanic.spanners.springmvc.services.SpannersService; import org.dontpanic.spanners.springmvc.exception.SpannerNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; package org.dontpanic.spanners.springmvc.controllers; /** * Displays detail of a single spanner * User: Stevie * Date: 13/10/13 */ @Controller public class DetailSpannerController { public static final String VIEW_DETAIL_SPANNER = "detailSpanner"; public static final String MODEL_SPANNER = "spanner"; @Autowired private SpannersService spannersService; @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { // Fetch the spanner
Spanner spanner = spannersService.findOne(id);
hotblac/spanners
spanners-api/src/test/java/org/dontpanic/spanners/api/data/SpannerRepositoryTest.java
// Path: spanners-api/src/test/java/org/dontpanic/spanners/api/stubs/SpannerBuilder.java // public static SpannerBuilder aTestSpanner() { // return new SpannerBuilder(); // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.dontpanic.spanners.api.stubs.SpannerBuilder.aTestSpanner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull;
package org.dontpanic.spanners.api.data; /** * Tests for the Spring Boot managed SpannerRepository * Created by stevie on 04/06/16. */ @RunWith(SpringRunner.class) @SpringBootTest public class SpannerRepositoryTest { @Autowired private SpannerRepository repository; @Test public void testCreate() { // Create the new spanner
// Path: spanners-api/src/test/java/org/dontpanic/spanners/api/stubs/SpannerBuilder.java // public static SpannerBuilder aTestSpanner() { // return new SpannerBuilder(); // } // Path: spanners-api/src/test/java/org/dontpanic/spanners/api/data/SpannerRepositoryTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.dontpanic.spanners.api.stubs.SpannerBuilder.aTestSpanner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; package org.dontpanic.spanners.api.data; /** * Tests for the Spring Boot managed SpannerRepository * Created by stevie on 04/06/16. */ @RunWith(SpringRunner.class) @SpringBootTest public class SpannerRepositoryTest { @Autowired private SpannerRepository repository; @Test public void testCreate() { // Create the new spanner
Spanner savedSpanner = aTestSpanner().build();
hotblac/spanners
spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/RestUserDetailsService.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/User.java // public class User implements UserDetails { // // private String username; // private String password; // private Boolean enabled; // // public User() { // } // // public User(String username, String password, Boolean enabled) { // this.username = username; // this.password = password; // this.enabled = enabled; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Boolean getEnabled() { // return enabled; // } // // public void setEnabled(Boolean enabled) { // this.enabled = enabled; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return enabled; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptySet(); // } // }
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.dontpanic.spanners.springmvc.domain.User; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.hateoas.hal.Jackson2HalModule; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate;
package org.dontpanic.spanners.springmvc.services; /** * Retrieve user details from a REST service * Created by stevie on 14/07/16. */ @Service public class RestUserDetailsService implements UserDetailsManager { private RestTemplate restTemplate; public RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri) { restTemplate = builder.messageConverters(halAwareMessageConverter()) .rootUri(rootUri).build(); } private HttpMessageConverter halAwareMessageConverter() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.registerModule(new Jackson2HalModule()); return new MappingJackson2HttpMessageConverter(mapper); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/domain/User.java // public class User implements UserDetails { // // private String username; // private String password; // private Boolean enabled; // // public User() { // } // // public User(String username, String password, Boolean enabled) { // this.username = username; // this.password = password; // this.enabled = enabled; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Boolean getEnabled() { // return enabled; // } // // public void setEnabled(Boolean enabled) { // this.enabled = enabled; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return enabled; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptySet(); // } // } // Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/services/RestUserDetailsService.java import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.dontpanic.spanners.springmvc.domain.User; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.hateoas.hal.Jackson2HalModule; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; package org.dontpanic.spanners.springmvc.services; /** * Retrieve user details from a REST service * Created by stevie on 14/07/16. */ @Service public class RestUserDetailsService implements UserDetailsManager { private RestTemplate restTemplate; public RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri) { restTemplate = builder.messageConverters(halAwareMessageConverter()) .rootUri(rootUri).build(); } private HttpMessageConverter halAwareMessageConverter() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.registerModule(new Jackson2HalModule()); return new MappingJackson2HttpMessageConverter(mapper); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return restTemplate.getForObject("/{0}", User.class, username);
hotblac/spanners
spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/controllers/HomeControllerTest.java
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/HomeController.java // public static final String VIEW_NOT_SIGNED_IN = "index";
import org.junit.Test; import static org.dontpanic.spanners.springmvc.controllers.HomeController.VIEW_NOT_SIGNED_IN; import static org.junit.Assert.assertEquals;
package org.dontpanic.spanners.springmvc.controllers; /** * Test for home page * User: Stevie * Date: 05/10/13 */ public class HomeControllerTest { private HomeController controller = new HomeController(); @Test public void testHomePage() { // Call the controller String response = controller.index();
// Path: spanners-mvc/src/main/java/org/dontpanic/spanners/springmvc/controllers/HomeController.java // public static final String VIEW_NOT_SIGNED_IN = "index"; // Path: spanners-mvc/src/test/java/org/dontpanic/spanners/springmvc/controllers/HomeControllerTest.java import org.junit.Test; import static org.dontpanic.spanners.springmvc.controllers.HomeController.VIEW_NOT_SIGNED_IN; import static org.junit.Assert.assertEquals; package org.dontpanic.spanners.springmvc.controllers; /** * Test for home page * User: Stevie * Date: 05/10/13 */ public class HomeControllerTest { private HomeController controller = new HomeController(); @Test public void testHomePage() { // Call the controller String response = controller.index();
assertEquals("view name", VIEW_NOT_SIGNED_IN, response);
hotblac/spanners
spanners-users/src/main/java/org/dontpanic/spanners/users/config/RestConfig.java
// Path: spanners-users/src/main/java/org/dontpanic/spanners/users/data/User.java // @Entity // public class User { // // @Id // private String username; // private String password; // private Boolean enabled; // // public User() { // } // // public User(String username, String password, Boolean enabled) { // this.username = username; // this.password = password; // this.enabled = enabled; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Boolean getEnabled() { // return enabled; // } // // public void setEnabled(Boolean enabled) { // this.enabled = enabled; // } // }
import org.dontpanic.spanners.users.data.User; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;
package org.dontpanic.spanners.users.config; /** * Custom configuration for Spring Data REST * Created by stevie on 27/08/16. */ @Configuration @EnableDiscoveryClient public class RestConfig extends RepositoryRestConfigurerAdapter { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
// Path: spanners-users/src/main/java/org/dontpanic/spanners/users/data/User.java // @Entity // public class User { // // @Id // private String username; // private String password; // private Boolean enabled; // // public User() { // } // // public User(String username, String password, Boolean enabled) { // this.username = username; // this.password = password; // this.enabled = enabled; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Boolean getEnabled() { // return enabled; // } // // public void setEnabled(Boolean enabled) { // this.enabled = enabled; // } // } // Path: spanners-users/src/main/java/org/dontpanic/spanners/users/config/RestConfig.java import org.dontpanic.spanners.users.data.User; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter; package org.dontpanic.spanners.users.config; /** * Custom configuration for Spring Data REST * Created by stevie on 27/08/16. */ @Configuration @EnableDiscoveryClient public class RestConfig extends RepositoryRestConfigurerAdapter { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.exposeIdsFor(User.class);
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/entities/TreeTest.java
// Path: src/main/java/myessentials/entities/api/Tree.java // public class Tree<T extends TreeNode> { // private T root; // // public Tree(T root) { // this.root = root; // } // // public T getRoot() { // return root; // } // } // // Path: src/main/java/myessentials/entities/api/TreeNode.java // public class TreeNode<T extends TreeNode> { // // protected T parent; // protected List<T> children = new ArrayList<T>(); // // public TreeNode() { // this(null); // } // // public TreeNode(T parent) { // this.parent = parent; // } // // public T getParent() { // return parent; // } // // public void addChild(T child) { // children.add(child); // child.parent = this; // } // // // public List<T> getChildren() { // return children; // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // }
import junit.framework.Assert; import myessentials.entities.api.Tree; import myessentials.entities.api.TreeNode; import myessentials.test.MECTest; import org.junit.Test;
package myessentials.test.entities; public class TreeTest extends MECTest { @Test public void shouldInitTreeWithRoot() {
// Path: src/main/java/myessentials/entities/api/Tree.java // public class Tree<T extends TreeNode> { // private T root; // // public Tree(T root) { // this.root = root; // } // // public T getRoot() { // return root; // } // } // // Path: src/main/java/myessentials/entities/api/TreeNode.java // public class TreeNode<T extends TreeNode> { // // protected T parent; // protected List<T> children = new ArrayList<T>(); // // public TreeNode() { // this(null); // } // // public TreeNode(T parent) { // this.parent = parent; // } // // public T getParent() { // return parent; // } // // public void addChild(T child) { // children.add(child); // child.parent = this; // } // // // public List<T> getChildren() { // return children; // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // Path: src/test/java/myessentials/test/entities/TreeTest.java import junit.framework.Assert; import myessentials.entities.api.Tree; import myessentials.entities.api.TreeNode; import myessentials.test.MECTest; import org.junit.Test; package myessentials.test.entities; public class TreeTest extends MECTest { @Test public void shouldInitTreeWithRoot() {
TreeNode node = new TreeNode();
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/entities/TreeTest.java
// Path: src/main/java/myessentials/entities/api/Tree.java // public class Tree<T extends TreeNode> { // private T root; // // public Tree(T root) { // this.root = root; // } // // public T getRoot() { // return root; // } // } // // Path: src/main/java/myessentials/entities/api/TreeNode.java // public class TreeNode<T extends TreeNode> { // // protected T parent; // protected List<T> children = new ArrayList<T>(); // // public TreeNode() { // this(null); // } // // public TreeNode(T parent) { // this.parent = parent; // } // // public T getParent() { // return parent; // } // // public void addChild(T child) { // children.add(child); // child.parent = this; // } // // // public List<T> getChildren() { // return children; // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // }
import junit.framework.Assert; import myessentials.entities.api.Tree; import myessentials.entities.api.TreeNode; import myessentials.test.MECTest; import org.junit.Test;
package myessentials.test.entities; public class TreeTest extends MECTest { @Test public void shouldInitTreeWithRoot() { TreeNode node = new TreeNode();
// Path: src/main/java/myessentials/entities/api/Tree.java // public class Tree<T extends TreeNode> { // private T root; // // public Tree(T root) { // this.root = root; // } // // public T getRoot() { // return root; // } // } // // Path: src/main/java/myessentials/entities/api/TreeNode.java // public class TreeNode<T extends TreeNode> { // // protected T parent; // protected List<T> children = new ArrayList<T>(); // // public TreeNode() { // this(null); // } // // public TreeNode(T parent) { // this.parent = parent; // } // // public T getParent() { // return parent; // } // // public void addChild(T child) { // children.add(child); // child.parent = this; // } // // // public List<T> getChildren() { // return children; // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // Path: src/test/java/myessentials/test/entities/TreeTest.java import junit.framework.Assert; import myessentials.entities.api.Tree; import myessentials.entities.api.TreeNode; import myessentials.test.MECTest; import org.junit.Test; package myessentials.test.entities; public class TreeTest extends MECTest { @Test public void shouldInitTreeWithRoot() { TreeNode node = new TreeNode();
Tree tree = new Tree(node);
MyEssentials/MyEssentials-Core
src/main/java/myessentials/json/api/JsonConfig.java
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // }
import com.google.gson.Gson; import myessentials.MyEssentialsCore; import org.apache.commons.lang3.exception.ExceptionUtils; import java.io.*; import java.lang.reflect.Type; import java.util.List;
package myessentials.json.api; /** * An abstract class for all JSON configs. * Instantiating the gson and gsonType is needed. * Methods are usually overriden but called inside their overriden method. */ public abstract class JsonConfig<T, L extends List<T>> { /** * The path to the file used. */ protected final String path, name; protected Gson gson; protected Type gsonType; public JsonConfig(String path, String name) { this.path = path; this.name = name; } protected abstract L newList(); public void init() { init(newList()); } /** * Initializes everything. */ public void init(L items) { File file = new File(path); File parent = file.getParentFile(); if (!parent.exists() && !parent.mkdirs()) { throw new IllegalStateException("Couldn't create dir: " + parent); } if (!file.exists() || file.isDirectory()) { create(items); } else { read(); } } /** * Creates the file if it doesn't exist with the initial given items */ public void create(L initialItems) { try { Writer writer = new FileWriter(path); gson.toJson(initialItems, gsonType, writer); writer.close();
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // } // Path: src/main/java/myessentials/json/api/JsonConfig.java import com.google.gson.Gson; import myessentials.MyEssentialsCore; import org.apache.commons.lang3.exception.ExceptionUtils; import java.io.*; import java.lang.reflect.Type; import java.util.List; package myessentials.json.api; /** * An abstract class for all JSON configs. * Instantiating the gson and gsonType is needed. * Methods are usually overriden but called inside their overriden method. */ public abstract class JsonConfig<T, L extends List<T>> { /** * The path to the file used. */ protected final String path, name; protected Gson gson; protected Type gsonType; public JsonConfig(String path, String name) { this.path = path; this.name = name; } protected abstract L newList(); public void init() { init(newList()); } /** * Initializes everything. */ public void init(L items) { File file = new File(path); File parent = file.getParentFile(); if (!parent.exists() && !parent.mkdirs()) { throw new IllegalStateException("Couldn't create dir: " + parent); } if (!file.exists() || file.isDirectory()) { create(items); } else { read(); } } /** * Creates the file if it doesn't exist with the initial given items */ public void create(L initialItems) { try { Writer writer = new FileWriter(path); gson.toJson(initialItems, gsonType, writer); writer.close();
MyEssentialsCore.instance.LOG.info("Created new " + name + " file successfully!");
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/entities/sign/SignTest.java
// Path: src/main/java/myessentials/entities/api/BlockPos.java // public class BlockPos implements IChatFormat { // private final int dim; // private final int x; // private final int y; // private final int z; // // public BlockPos(int x, int y, int z, int dim) { // this.x = x; // this.y = y; // this.z = z; // this.dim = dim; // } // // public int getDim() { // return dim; // } // // public int getX() { // return x; // } // // public int getY() { // return y; // } // // public int getZ() { // return z; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public boolean equals(Object other) { // if(other instanceof BlockPos) { // BlockPos otherBP = (BlockPos) other; // return otherBP.dim == dim && otherBP.x == x && otherBP.y == y && otherBP.z == z; // } // return super.equals(other); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.blockpos", x, y, z, dim); // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // }
import junit.framework.Assert; import metest.api.TestPlayer; import myessentials.entities.api.BlockPos; import myessentials.test.MECTest; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import org.junit.Before; import org.junit.Test;
package myessentials.test.entities.sign; public class SignTest extends MECTest { private EntityPlayerMP player; @Before public void init() { player = new TestPlayer(server, "Sign Tester"); server.worldServerForDimension(0).setBlock(20, 199, 20, Blocks.stone); } @Test public void shouldCreateSign() { FakeSign sign = new FakeSign(0);
// Path: src/main/java/myessentials/entities/api/BlockPos.java // public class BlockPos implements IChatFormat { // private final int dim; // private final int x; // private final int y; // private final int z; // // public BlockPos(int x, int y, int z, int dim) { // this.x = x; // this.y = y; // this.z = z; // this.dim = dim; // } // // public int getDim() { // return dim; // } // // public int getX() { // return x; // } // // public int getY() { // return y; // } // // public int getZ() { // return z; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public boolean equals(Object other) { // if(other instanceof BlockPos) { // BlockPos otherBP = (BlockPos) other; // return otherBP.dim == dim && otherBP.x == x && otherBP.y == y && otherBP.z == z; // } // return super.equals(other); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.blockpos", x, y, z, dim); // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // Path: src/test/java/myessentials/test/entities/sign/SignTest.java import junit.framework.Assert; import metest.api.TestPlayer; import myessentials.entities.api.BlockPos; import myessentials.test.MECTest; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import org.junit.Before; import org.junit.Test; package myessentials.test.entities.sign; public class SignTest extends MECTest { private EntityPlayerMP player; @Before public void init() { player = new TestPlayer(server, "Sign Tester"); server.worldServerForDimension(0).setBlock(20, 199, 20, Blocks.stone); } @Test public void shouldCreateSign() { FakeSign sign = new FakeSign(0);
sign.createSignBlock(player, new BlockPos(20, 200, 20, 0), 0);
MyEssentials/MyEssentials-Core
src/main/java/myessentials/utils/WorldUtils.java
// Path: src/main/java/myessentials/entities/api/ChunkPos.java // public class ChunkPos implements IChatFormat { // private final int dim; // private final int x; // private final int z; // // public ChunkPos(int dim, int x, int z) { // this.dim = dim; // this.x = x; // this.z = z; // } // // public int getX() { // return x; // } // // public int getZ() { // return z; // } // // public int getDim() { // return dim; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.chunkpos", x, z, dim); // } // // public NBTTagCompound toNBTTagCompound() { // NBTTagCompound tag = new NBTTagCompound(); // tag.setInteger("x", x); // tag.setInteger("z", z); // return tag; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof ChunkPos) { // ChunkPos other = (ChunkPos) obj; // return other.x == x && other.z == z && other.dim == dim; // } else { // return super.equals(obj); // } // } // }
import myessentials.entities.api.ChunkPos; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; import java.util.ArrayList; import java.util.List;
package myessentials.utils; /** * All utilities that are exclusively for in world objects go here. */ public class WorldUtils { private WorldUtils() { } /** * Transforms a box made out of actual coordinates to a list of all the chunks that this box is in */
// Path: src/main/java/myessentials/entities/api/ChunkPos.java // public class ChunkPos implements IChatFormat { // private final int dim; // private final int x; // private final int z; // // public ChunkPos(int dim, int x, int z) { // this.dim = dim; // this.x = x; // this.z = z; // } // // public int getX() { // return x; // } // // public int getZ() { // return z; // } // // public int getDim() { // return dim; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.chunkpos", x, z, dim); // } // // public NBTTagCompound toNBTTagCompound() { // NBTTagCompound tag = new NBTTagCompound(); // tag.setInteger("x", x); // tag.setInteger("z", z); // return tag; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof ChunkPos) { // ChunkPos other = (ChunkPos) obj; // return other.x == x && other.z == z && other.dim == dim; // } else { // return super.equals(obj); // } // } // } // Path: src/main/java/myessentials/utils/WorldUtils.java import myessentials.entities.api.ChunkPos; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; import java.util.ArrayList; import java.util.List; package myessentials.utils; /** * All utilities that are exclusively for in world objects go here. */ public class WorldUtils { private WorldUtils() { } /** * Transforms a box made out of actual coordinates to a list of all the chunks that this box is in */
public static List<ChunkPos> getChunksInBox(int dim, int minX, int minZ, int maxX, int maxZ) {
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/entities/EntityPosTest.java
// Path: src/main/java/myessentials/entities/api/EntityPos.java // public class EntityPos implements IChatFormat { // private final int dim; // private final double x; // private final double y; // private final double z; // // public EntityPos(double x, double y, double z, int dim) { // this.x = x; // this.y = y; // this.z = z; // this.dim = dim; // } // // public int getDim() { // return dim; // } // // public double getX() { // return x; // } // // public double getY() { // return y; // } // // public double getZ() { // return z; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.entitypos", x, y, z, dim); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof EntityPos) { // EntityPos other = (EntityPos) obj; // return other.x == x && other.y == y && other.z == z && other.dim == dim; // } else { // return super.equals(obj); // } // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // }
import junit.framework.Assert; import myessentials.entities.api.EntityPos; import myessentials.test.MECTest; import org.junit.Test;
package myessentials.test.entities; public class EntityPosTest extends MECTest { @Test public void blockPosEquality() {
// Path: src/main/java/myessentials/entities/api/EntityPos.java // public class EntityPos implements IChatFormat { // private final int dim; // private final double x; // private final double y; // private final double z; // // public EntityPos(double x, double y, double z, int dim) { // this.x = x; // this.y = y; // this.z = z; // this.dim = dim; // } // // public int getDim() { // return dim; // } // // public double getX() { // return x; // } // // public double getY() { // return y; // } // // public double getZ() { // return z; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.entitypos", x, y, z, dim); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof EntityPos) { // EntityPos other = (EntityPos) obj; // return other.x == x && other.y == y && other.z == z && other.dim == dim; // } else { // return super.equals(obj); // } // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // Path: src/test/java/myessentials/test/entities/EntityPosTest.java import junit.framework.Assert; import myessentials.entities.api.EntityPos; import myessentials.test.MECTest; import org.junit.Test; package myessentials.test.entities; public class EntityPosTest extends MECTest { @Test public void blockPosEquality() {
EntityPos ep1 = new EntityPos(1.2D, 1.2D, 1.3D, 0);
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/config/ConfigTest.java
// Path: src/main/java/myessentials/config/api/ConfigProperty.java // public class ConfigProperty<T> { // // private T value; // // public final String name; // public final String category; // public final String comment; // // // public ConfigProperty(String name, String category, String comment, T defaultValue) { // this.name = name; // this.category = category; // this.comment = comment; // this.value = defaultValue; // } // // /** // * Sets the value inside the property // */ // public void set(T value) { // this.value = value; // } // // /** // * Returns the value retained inside the property // */ // public T get() { // return value; // } // // public boolean isClassType(Class clazz) { // return value.getClass().isAssignableFrom(clazz); // } // // public Property.Type getType() { // return CONFIG_TYPES.get(value.getClass()); // } // // // private static final Map<Class<?>, Property.Type> CONFIG_TYPES = ImmutableMap.<Class<?>, Property.Type> builder().put(Integer.class, Property.Type.INTEGER) // .put(int.class, Property.Type.INTEGER).put(Integer[].class, Property.Type.INTEGER) // .put(int[].class, Property.Type.INTEGER).put(Double.class, Property.Type.DOUBLE) // .put(double.class, Property.Type.DOUBLE).put(Double[].class, Property.Type.DOUBLE) // .put(double[].class, Property.Type.DOUBLE).put(Float.class, Property.Type.DOUBLE) // .put(float.class, Property.Type.DOUBLE).put(Float[].class, Property.Type.DOUBLE) // .put(float[].class, Property.Type.DOUBLE).put(Boolean.class, Property.Type.BOOLEAN) // .put(boolean.class, Property.Type.BOOLEAN).put(Boolean[].class, Property.Type.BOOLEAN) // .put(boolean[].class, Property.Type.BOOLEAN).put(String.class, Property.Type.STRING) // .put(String[].class, Property.Type.STRING).build(); // // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // }
import junit.framework.Assert; import myessentials.config.api.ConfigProperty; import myessentials.test.MECTest; import org.junit.Before; import org.junit.Test; import java.io.File;
package myessentials.test.config; //@RunWith(MinecraftRunner.class) public class ConfigTest extends MECTest { private FakeConfig config; @Before public void initConfig() { // REF: Move this to METEST when it's needed File configDir = configFile.getParentFile(); File testDir = new File(configDir, "/tests"); if(!testDir.exists() || !testDir.isDirectory()) { testDir.mkdir(); } File testConfigFile = new File(testDir, "/TestConfig.cfg"); config = new FakeConfig(); config.init(testConfigFile, "MyEssentials-Core"); } @Test public void shouldAddProperty() {
// Path: src/main/java/myessentials/config/api/ConfigProperty.java // public class ConfigProperty<T> { // // private T value; // // public final String name; // public final String category; // public final String comment; // // // public ConfigProperty(String name, String category, String comment, T defaultValue) { // this.name = name; // this.category = category; // this.comment = comment; // this.value = defaultValue; // } // // /** // * Sets the value inside the property // */ // public void set(T value) { // this.value = value; // } // // /** // * Returns the value retained inside the property // */ // public T get() { // return value; // } // // public boolean isClassType(Class clazz) { // return value.getClass().isAssignableFrom(clazz); // } // // public Property.Type getType() { // return CONFIG_TYPES.get(value.getClass()); // } // // // private static final Map<Class<?>, Property.Type> CONFIG_TYPES = ImmutableMap.<Class<?>, Property.Type> builder().put(Integer.class, Property.Type.INTEGER) // .put(int.class, Property.Type.INTEGER).put(Integer[].class, Property.Type.INTEGER) // .put(int[].class, Property.Type.INTEGER).put(Double.class, Property.Type.DOUBLE) // .put(double.class, Property.Type.DOUBLE).put(Double[].class, Property.Type.DOUBLE) // .put(double[].class, Property.Type.DOUBLE).put(Float.class, Property.Type.DOUBLE) // .put(float.class, Property.Type.DOUBLE).put(Float[].class, Property.Type.DOUBLE) // .put(float[].class, Property.Type.DOUBLE).put(Boolean.class, Property.Type.BOOLEAN) // .put(boolean.class, Property.Type.BOOLEAN).put(Boolean[].class, Property.Type.BOOLEAN) // .put(boolean[].class, Property.Type.BOOLEAN).put(String.class, Property.Type.STRING) // .put(String[].class, Property.Type.STRING).build(); // // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // Path: src/test/java/myessentials/test/config/ConfigTest.java import junit.framework.Assert; import myessentials.config.api.ConfigProperty; import myessentials.test.MECTest; import org.junit.Before; import org.junit.Test; import java.io.File; package myessentials.test.config; //@RunWith(MinecraftRunner.class) public class ConfigTest extends MECTest { private FakeConfig config; @Before public void initConfig() { // REF: Move this to METEST when it's needed File configDir = configFile.getParentFile(); File testDir = new File(configDir, "/tests"); if(!testDir.exists() || !testDir.isDirectory()) { testDir.mkdir(); } File testConfigFile = new File(testDir, "/TestConfig.cfg"); config = new FakeConfig(); config.init(testConfigFile, "MyEssentials-Core"); } @Test public void shouldAddProperty() {
ConfigProperty<String> prop = new ConfigProperty<String>(
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/entities/tool/FakeTool.java
// Path: src/main/java/myessentials/entities/api/BlockPos.java // public class BlockPos implements IChatFormat { // private final int dim; // private final int x; // private final int y; // private final int z; // // public BlockPos(int x, int y, int z, int dim) { // this.x = x; // this.y = y; // this.z = z; // this.dim = dim; // } // // public int getDim() { // return dim; // } // // public int getX() { // return x; // } // // public int getY() { // return y; // } // // public int getZ() { // return z; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public boolean equals(Object other) { // if(other instanceof BlockPos) { // BlockPos otherBP = (BlockPos) other; // return otherBP.dim == dim && otherBP.x == x && otherBP.y == y && otherBP.z == z; // } // return super.equals(other); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.blockpos", x, y, z, dim); // } // } // // Path: src/main/java/myessentials/entities/api/tool/Tool.java // public abstract class Tool { // // /** // * Every tool starts with this string. Allows easy checks for invalid tools. // */ // public static final String IDENTIFIER = EnumChatFormatting.BLUE.toString(); // // protected EntityPlayer owner; // // /** // * This is used as an identifier to find the itemstack in the player's inventory. // */ // protected String toolName; // // protected Tool(EntityPlayer owner, String toolName) { // this.owner = owner; // this.toolName = IDENTIFIER + toolName; // } // // public abstract void onItemUse(BlockPos bp, int face); // // protected abstract String[] getDescription(); // // public void onShiftRightClick() { // } // // public ItemStack getItemStack() { // return PlayerUtils.getItemStackFromPlayer(owner, Items.wooden_hoe, toolName); // } // // public void giveItemStack() { // ItemStack itemStack = new ItemStack(Items.wooden_hoe); // itemStack.setStackDisplayName(toolName); // NBTTagList lore = new NBTTagList(); // for(String s : getDescription()) { // lore.appendTag(new NBTTagString(s)); // } // itemStack.getTagCompound().getCompoundTag("display").setTag("Lore", lore); // PlayerUtils.giveItemStackToPlayer(owner, itemStack); // //owner.sendMessage(MyTown.instance.LOCAL.getLocalization("mytown.notification.tool.gained")); // } // // protected void updateDescription() { // NBTTagList lore = getItemStack().getTagCompound().getCompoundTag("display").getTagList("Lore", 8); // NBTTagList newLore = new NBTTagList(); // String[] newDescription = getDescription(); // for(int i = 0; i < lore.tagCount(); i++) { // newLore.appendTag(new NBTTagString(newDescription[i])); // } // getItemStack().getTagCompound().getCompoundTag("display").setTag("Lore", newLore); // } // }
import myessentials.entities.api.BlockPos; import myessentials.entities.api.tool.Tool; import net.minecraft.entity.player.EntityPlayer;
package myessentials.test.entities.tool; public class FakeTool extends Tool { public int amountOfClicks = 0; protected FakeTool(EntityPlayer owner) { super(owner, "FakestTool"); } // REF: Change the name of method to something different since it can be confused with the onItemUse method in items @Override
// Path: src/main/java/myessentials/entities/api/BlockPos.java // public class BlockPos implements IChatFormat { // private final int dim; // private final int x; // private final int y; // private final int z; // // public BlockPos(int x, int y, int z, int dim) { // this.x = x; // this.y = y; // this.z = z; // this.dim = dim; // } // // public int getDim() { // return dim; // } // // public int getX() { // return x; // } // // public int getY() { // return y; // } // // public int getZ() { // return z; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public boolean equals(Object other) { // if(other instanceof BlockPos) { // BlockPos otherBP = (BlockPos) other; // return otherBP.dim == dim && otherBP.x == x && otherBP.y == y && otherBP.z == z; // } // return super.equals(other); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.blockpos", x, y, z, dim); // } // } // // Path: src/main/java/myessentials/entities/api/tool/Tool.java // public abstract class Tool { // // /** // * Every tool starts with this string. Allows easy checks for invalid tools. // */ // public static final String IDENTIFIER = EnumChatFormatting.BLUE.toString(); // // protected EntityPlayer owner; // // /** // * This is used as an identifier to find the itemstack in the player's inventory. // */ // protected String toolName; // // protected Tool(EntityPlayer owner, String toolName) { // this.owner = owner; // this.toolName = IDENTIFIER + toolName; // } // // public abstract void onItemUse(BlockPos bp, int face); // // protected abstract String[] getDescription(); // // public void onShiftRightClick() { // } // // public ItemStack getItemStack() { // return PlayerUtils.getItemStackFromPlayer(owner, Items.wooden_hoe, toolName); // } // // public void giveItemStack() { // ItemStack itemStack = new ItemStack(Items.wooden_hoe); // itemStack.setStackDisplayName(toolName); // NBTTagList lore = new NBTTagList(); // for(String s : getDescription()) { // lore.appendTag(new NBTTagString(s)); // } // itemStack.getTagCompound().getCompoundTag("display").setTag("Lore", lore); // PlayerUtils.giveItemStackToPlayer(owner, itemStack); // //owner.sendMessage(MyTown.instance.LOCAL.getLocalization("mytown.notification.tool.gained")); // } // // protected void updateDescription() { // NBTTagList lore = getItemStack().getTagCompound().getCompoundTag("display").getTagList("Lore", 8); // NBTTagList newLore = new NBTTagList(); // String[] newDescription = getDescription(); // for(int i = 0; i < lore.tagCount(); i++) { // newLore.appendTag(new NBTTagString(newDescription[i])); // } // getItemStack().getTagCompound().getCompoundTag("display").setTag("Lore", newLore); // } // } // Path: src/test/java/myessentials/test/entities/tool/FakeTool.java import myessentials.entities.api.BlockPos; import myessentials.entities.api.tool.Tool; import net.minecraft.entity.player.EntityPlayer; package myessentials.test.entities.tool; public class FakeTool extends Tool { public int amountOfClicks = 0; protected FakeTool(EntityPlayer owner) { super(owner, "FakestTool"); } // REF: Change the name of method to something different since it can be confused with the onItemUse method in items @Override
public void onItemUse(BlockPos bp, int face) {
MyEssentials/MyEssentials-Core
src/main/java/myessentials/exception/FormattedException.java
// Path: src/main/java/myessentials/localization/api/LocalManager.java // public class LocalManager { // // private static Map<String, Local> localizations = new HashMap<String, Local>(); // // /** // * Registers a localization file to be used globally // * The key string should be the first part of any localization key that is found in the file // */ // public static void register(Local local, String key) { // localizations.put(key, local); // } // // /** // * Finds the localized version that the key is pointing at and sends it to the ICommandSender // */ // public static void send(ICommandSender sender, String localizationKey, Object... args) { // sender.addChatMessage(get(localizationKey, args)); // } // // public static ChatComponentFormatted get(String localizationKey, Object... args) { // Local local = localizations.get(localizationKey.split("\\.")[0]); // return local.getLocalization(localizationKey, args); // } // }
import myessentials.localization.api.LocalManager; import net.minecraft.util.IChatComponent;
package myessentials.exception; public abstract class FormattedException extends RuntimeException { public final IChatComponent message; public FormattedException(String localizationKey, Object... args) {
// Path: src/main/java/myessentials/localization/api/LocalManager.java // public class LocalManager { // // private static Map<String, Local> localizations = new HashMap<String, Local>(); // // /** // * Registers a localization file to be used globally // * The key string should be the first part of any localization key that is found in the file // */ // public static void register(Local local, String key) { // localizations.put(key, local); // } // // /** // * Finds the localized version that the key is pointing at and sends it to the ICommandSender // */ // public static void send(ICommandSender sender, String localizationKey, Object... args) { // sender.addChatMessage(get(localizationKey, args)); // } // // public static ChatComponentFormatted get(String localizationKey, Object... args) { // Local local = localizations.get(localizationKey.split("\\.")[0]); // return local.getLocalization(localizationKey, args); // } // } // Path: src/main/java/myessentials/exception/FormattedException.java import myessentials.localization.api.LocalManager; import net.minecraft.util.IChatComponent; package myessentials.exception; public abstract class FormattedException extends RuntimeException { public final IChatComponent message; public FormattedException(String localizationKey, Object... args) {
message = LocalManager.get(localizationKey, args);
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/economy/EconomyForgeEssentialsTest.java
// Path: src/main/java/myessentials/economy/api/Economy.java // public class Economy { // public static final String CURRENCY_VAULT = "$Vault"; // public static final String CURRENCY_FORGE_ESSENTIALS = "$ForgeEssentials"; // public static final String CURRENCY_CUSTOM = "$Custom:"; // // private String costItemName; // private Class<? extends IEconManager> econManagerClass; // // public Economy(String costItemName) { // this.costItemName = costItemName; // if(costItemName.equals(CURRENCY_VAULT)) { // if (ClassUtils.isBukkitLoaded()) { // econManagerClass = BukkitCompat.initEconomy(); // } // if(econManagerClass == null) // throw new EconomyException("Failed to initialize Vault economy!"); // } else if(costItemName.equals(CURRENCY_FORGE_ESSENTIALS)) { // if(Loader.isModLoaded("ForgeEssentials")) // econManagerClass = ForgeessentialsEconomy.class; // if(econManagerClass == null) // throw new EconomyException("Failed to initialize ForgeEssentials economy!"); // } else if(costItemName.startsWith(CURRENCY_CUSTOM)) { // try{ // econManagerClass = Class.forName(costItemName.substring(CURRENCY_CUSTOM.length())).asSubclass(IEconManager.class); // } // catch (Exception e){ // throw new EconomyException("Failed to initialize custom economy!", e); // } // } // } // // public IEconManager economyManagerForUUID(UUID uuid) { // if (econManagerClass == null) { // return null; // } // try { // IEconManager manager = econManagerClass.newInstance(); // manager.setPlayer(uuid); // return manager; // } catch(Exception ex) { // MyEssentialsCore.instance.LOG.info("Failed to create IEconManager", ex); // } // // return null; // Hopefully this doesn't break things... // } // // /** // * Takes the amount of money specified. // * Returns false if player doesn't have the money necessary // */ // public boolean takeMoneyFromPlayer(EntityPlayer player, int amount) { // if(costItemName.equals(CURRENCY_FORGE_ESSENTIALS) || costItemName.equals(CURRENCY_VAULT) || costItemName.startsWith(CURRENCY_CUSTOM)) { // IEconManager eco = economyManagerForUUID(player.getUniqueID()); // if (eco == null) // return false; // int wallet = eco.getWallet(); // if (wallet >= amount) { // eco.removeFromWallet(amount); // return true; // } // return false; // } else { // return PlayerUtils.takeItemFromPlayer(player, costItemName, amount); // } // } // // /** // * Takes the amount of money specified. // * Returns false if player doesn't have the money necessary // */ // public void giveMoneyToPlayer(EntityPlayer player, int amount) { // if (costItemName.equals(CURRENCY_FORGE_ESSENTIALS) || costItemName.equals(CURRENCY_VAULT) || costItemName.startsWith(CURRENCY_CUSTOM)) { // IEconManager eco = economyManagerForUUID(player.getUniqueID()); // if (eco == null) // return; // eco.addToWallet(amount); // } else { // PlayerUtils.giveItemToPlayer(player, costItemName, amount); // } // } // // /** // * Gets the currency string currently used. // */ // public String getCurrency(int amount) { // if(costItemName.equals(CURRENCY_FORGE_ESSENTIALS) || costItemName.equals(CURRENCY_VAULT) || costItemName.startsWith(CURRENCY_CUSTOM)) { // if (econManagerClass == null) { // return null; // } // try { // IEconManager manager = econManagerClass.newInstance(); // return manager.currency(amount); // } catch(Exception ex) { // MyEssentialsCore.instance.LOG.info("Failed to create IEconManager", ex); // } // return "$"; // // } else { // return ItemUtils.itemStackFromName(costItemName).getDisplayName() + (amount == 1 ? "" : "s"); // } // } // } // // Path: src/main/java/myessentials/economy/api/IEconManager.java // public interface IEconManager { // // void setPlayer(UUID uuid); // // /** // * Add a set amount to a target's Wallet // */ // void addToWallet(int amountToAdd); // // /** // * Get the amount of money the player has // */ // int getWallet(); // // /** // * Remove a set amount from a target's Wallet // * returns true if it succeded, false if it didn't // */ // boolean removeFromWallet(int amountToSubtract); // // /** // * Set the target's Wallet to the specified amount // */ // void setWallet(int setAmount, EntityPlayer player); // // /** // * Gets the singular or plural term of the currency used // */ // String currency(int amount); // // /** // * Gets a combo of getWallet + currency // */ // String getMoneyString(); // // /** // * Saves all wallets to disk // * (for users still on the server when it's stopping) // */ // void save(); // // Map<String, Integer> getItemTables(); // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // }
import metest.api.TestPlayer; import myessentials.economy.api.Economy; import myessentials.economy.api.IEconManager; import myessentials.test.MECTest; import net.minecraft.entity.player.EntityPlayerMP; import org.junit.Assert; import org.junit.Before; import org.junit.Test;
package myessentials.test.economy; public class EconomyForgeEssentialsTest extends MECTest { private EntityPlayerMP player;
// Path: src/main/java/myessentials/economy/api/Economy.java // public class Economy { // public static final String CURRENCY_VAULT = "$Vault"; // public static final String CURRENCY_FORGE_ESSENTIALS = "$ForgeEssentials"; // public static final String CURRENCY_CUSTOM = "$Custom:"; // // private String costItemName; // private Class<? extends IEconManager> econManagerClass; // // public Economy(String costItemName) { // this.costItemName = costItemName; // if(costItemName.equals(CURRENCY_VAULT)) { // if (ClassUtils.isBukkitLoaded()) { // econManagerClass = BukkitCompat.initEconomy(); // } // if(econManagerClass == null) // throw new EconomyException("Failed to initialize Vault economy!"); // } else if(costItemName.equals(CURRENCY_FORGE_ESSENTIALS)) { // if(Loader.isModLoaded("ForgeEssentials")) // econManagerClass = ForgeessentialsEconomy.class; // if(econManagerClass == null) // throw new EconomyException("Failed to initialize ForgeEssentials economy!"); // } else if(costItemName.startsWith(CURRENCY_CUSTOM)) { // try{ // econManagerClass = Class.forName(costItemName.substring(CURRENCY_CUSTOM.length())).asSubclass(IEconManager.class); // } // catch (Exception e){ // throw new EconomyException("Failed to initialize custom economy!", e); // } // } // } // // public IEconManager economyManagerForUUID(UUID uuid) { // if (econManagerClass == null) { // return null; // } // try { // IEconManager manager = econManagerClass.newInstance(); // manager.setPlayer(uuid); // return manager; // } catch(Exception ex) { // MyEssentialsCore.instance.LOG.info("Failed to create IEconManager", ex); // } // // return null; // Hopefully this doesn't break things... // } // // /** // * Takes the amount of money specified. // * Returns false if player doesn't have the money necessary // */ // public boolean takeMoneyFromPlayer(EntityPlayer player, int amount) { // if(costItemName.equals(CURRENCY_FORGE_ESSENTIALS) || costItemName.equals(CURRENCY_VAULT) || costItemName.startsWith(CURRENCY_CUSTOM)) { // IEconManager eco = economyManagerForUUID(player.getUniqueID()); // if (eco == null) // return false; // int wallet = eco.getWallet(); // if (wallet >= amount) { // eco.removeFromWallet(amount); // return true; // } // return false; // } else { // return PlayerUtils.takeItemFromPlayer(player, costItemName, amount); // } // } // // /** // * Takes the amount of money specified. // * Returns false if player doesn't have the money necessary // */ // public void giveMoneyToPlayer(EntityPlayer player, int amount) { // if (costItemName.equals(CURRENCY_FORGE_ESSENTIALS) || costItemName.equals(CURRENCY_VAULT) || costItemName.startsWith(CURRENCY_CUSTOM)) { // IEconManager eco = economyManagerForUUID(player.getUniqueID()); // if (eco == null) // return; // eco.addToWallet(amount); // } else { // PlayerUtils.giveItemToPlayer(player, costItemName, amount); // } // } // // /** // * Gets the currency string currently used. // */ // public String getCurrency(int amount) { // if(costItemName.equals(CURRENCY_FORGE_ESSENTIALS) || costItemName.equals(CURRENCY_VAULT) || costItemName.startsWith(CURRENCY_CUSTOM)) { // if (econManagerClass == null) { // return null; // } // try { // IEconManager manager = econManagerClass.newInstance(); // return manager.currency(amount); // } catch(Exception ex) { // MyEssentialsCore.instance.LOG.info("Failed to create IEconManager", ex); // } // return "$"; // // } else { // return ItemUtils.itemStackFromName(costItemName).getDisplayName() + (amount == 1 ? "" : "s"); // } // } // } // // Path: src/main/java/myessentials/economy/api/IEconManager.java // public interface IEconManager { // // void setPlayer(UUID uuid); // // /** // * Add a set amount to a target's Wallet // */ // void addToWallet(int amountToAdd); // // /** // * Get the amount of money the player has // */ // int getWallet(); // // /** // * Remove a set amount from a target's Wallet // * returns true if it succeded, false if it didn't // */ // boolean removeFromWallet(int amountToSubtract); // // /** // * Set the target's Wallet to the specified amount // */ // void setWallet(int setAmount, EntityPlayer player); // // /** // * Gets the singular or plural term of the currency used // */ // String currency(int amount); // // /** // * Gets a combo of getWallet + currency // */ // String getMoneyString(); // // /** // * Saves all wallets to disk // * (for users still on the server when it's stopping) // */ // void save(); // // Map<String, Integer> getItemTables(); // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // Path: src/test/java/myessentials/test/economy/EconomyForgeEssentialsTest.java import metest.api.TestPlayer; import myessentials.economy.api.Economy; import myessentials.economy.api.IEconManager; import myessentials.test.MECTest; import net.minecraft.entity.player.EntityPlayerMP; import org.junit.Assert; import org.junit.Before; import org.junit.Test; package myessentials.test.economy; public class EconomyForgeEssentialsTest extends MECTest { private EntityPlayerMP player;
private Economy economy;
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/economy/EconomyForgeEssentialsTest.java
// Path: src/main/java/myessentials/economy/api/Economy.java // public class Economy { // public static final String CURRENCY_VAULT = "$Vault"; // public static final String CURRENCY_FORGE_ESSENTIALS = "$ForgeEssentials"; // public static final String CURRENCY_CUSTOM = "$Custom:"; // // private String costItemName; // private Class<? extends IEconManager> econManagerClass; // // public Economy(String costItemName) { // this.costItemName = costItemName; // if(costItemName.equals(CURRENCY_VAULT)) { // if (ClassUtils.isBukkitLoaded()) { // econManagerClass = BukkitCompat.initEconomy(); // } // if(econManagerClass == null) // throw new EconomyException("Failed to initialize Vault economy!"); // } else if(costItemName.equals(CURRENCY_FORGE_ESSENTIALS)) { // if(Loader.isModLoaded("ForgeEssentials")) // econManagerClass = ForgeessentialsEconomy.class; // if(econManagerClass == null) // throw new EconomyException("Failed to initialize ForgeEssentials economy!"); // } else if(costItemName.startsWith(CURRENCY_CUSTOM)) { // try{ // econManagerClass = Class.forName(costItemName.substring(CURRENCY_CUSTOM.length())).asSubclass(IEconManager.class); // } // catch (Exception e){ // throw new EconomyException("Failed to initialize custom economy!", e); // } // } // } // // public IEconManager economyManagerForUUID(UUID uuid) { // if (econManagerClass == null) { // return null; // } // try { // IEconManager manager = econManagerClass.newInstance(); // manager.setPlayer(uuid); // return manager; // } catch(Exception ex) { // MyEssentialsCore.instance.LOG.info("Failed to create IEconManager", ex); // } // // return null; // Hopefully this doesn't break things... // } // // /** // * Takes the amount of money specified. // * Returns false if player doesn't have the money necessary // */ // public boolean takeMoneyFromPlayer(EntityPlayer player, int amount) { // if(costItemName.equals(CURRENCY_FORGE_ESSENTIALS) || costItemName.equals(CURRENCY_VAULT) || costItemName.startsWith(CURRENCY_CUSTOM)) { // IEconManager eco = economyManagerForUUID(player.getUniqueID()); // if (eco == null) // return false; // int wallet = eco.getWallet(); // if (wallet >= amount) { // eco.removeFromWallet(amount); // return true; // } // return false; // } else { // return PlayerUtils.takeItemFromPlayer(player, costItemName, amount); // } // } // // /** // * Takes the amount of money specified. // * Returns false if player doesn't have the money necessary // */ // public void giveMoneyToPlayer(EntityPlayer player, int amount) { // if (costItemName.equals(CURRENCY_FORGE_ESSENTIALS) || costItemName.equals(CURRENCY_VAULT) || costItemName.startsWith(CURRENCY_CUSTOM)) { // IEconManager eco = economyManagerForUUID(player.getUniqueID()); // if (eco == null) // return; // eco.addToWallet(amount); // } else { // PlayerUtils.giveItemToPlayer(player, costItemName, amount); // } // } // // /** // * Gets the currency string currently used. // */ // public String getCurrency(int amount) { // if(costItemName.equals(CURRENCY_FORGE_ESSENTIALS) || costItemName.equals(CURRENCY_VAULT) || costItemName.startsWith(CURRENCY_CUSTOM)) { // if (econManagerClass == null) { // return null; // } // try { // IEconManager manager = econManagerClass.newInstance(); // return manager.currency(amount); // } catch(Exception ex) { // MyEssentialsCore.instance.LOG.info("Failed to create IEconManager", ex); // } // return "$"; // // } else { // return ItemUtils.itemStackFromName(costItemName).getDisplayName() + (amount == 1 ? "" : "s"); // } // } // } // // Path: src/main/java/myessentials/economy/api/IEconManager.java // public interface IEconManager { // // void setPlayer(UUID uuid); // // /** // * Add a set amount to a target's Wallet // */ // void addToWallet(int amountToAdd); // // /** // * Get the amount of money the player has // */ // int getWallet(); // // /** // * Remove a set amount from a target's Wallet // * returns true if it succeded, false if it didn't // */ // boolean removeFromWallet(int amountToSubtract); // // /** // * Set the target's Wallet to the specified amount // */ // void setWallet(int setAmount, EntityPlayer player); // // /** // * Gets the singular or plural term of the currency used // */ // String currency(int amount); // // /** // * Gets a combo of getWallet + currency // */ // String getMoneyString(); // // /** // * Saves all wallets to disk // * (for users still on the server when it's stopping) // */ // void save(); // // Map<String, Integer> getItemTables(); // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // }
import metest.api.TestPlayer; import myessentials.economy.api.Economy; import myessentials.economy.api.IEconManager; import myessentials.test.MECTest; import net.minecraft.entity.player.EntityPlayerMP; import org.junit.Assert; import org.junit.Before; import org.junit.Test;
package myessentials.test.economy; public class EconomyForgeEssentialsTest extends MECTest { private EntityPlayerMP player; private Economy economy;
// Path: src/main/java/myessentials/economy/api/Economy.java // public class Economy { // public static final String CURRENCY_VAULT = "$Vault"; // public static final String CURRENCY_FORGE_ESSENTIALS = "$ForgeEssentials"; // public static final String CURRENCY_CUSTOM = "$Custom:"; // // private String costItemName; // private Class<? extends IEconManager> econManagerClass; // // public Economy(String costItemName) { // this.costItemName = costItemName; // if(costItemName.equals(CURRENCY_VAULT)) { // if (ClassUtils.isBukkitLoaded()) { // econManagerClass = BukkitCompat.initEconomy(); // } // if(econManagerClass == null) // throw new EconomyException("Failed to initialize Vault economy!"); // } else if(costItemName.equals(CURRENCY_FORGE_ESSENTIALS)) { // if(Loader.isModLoaded("ForgeEssentials")) // econManagerClass = ForgeessentialsEconomy.class; // if(econManagerClass == null) // throw new EconomyException("Failed to initialize ForgeEssentials economy!"); // } else if(costItemName.startsWith(CURRENCY_CUSTOM)) { // try{ // econManagerClass = Class.forName(costItemName.substring(CURRENCY_CUSTOM.length())).asSubclass(IEconManager.class); // } // catch (Exception e){ // throw new EconomyException("Failed to initialize custom economy!", e); // } // } // } // // public IEconManager economyManagerForUUID(UUID uuid) { // if (econManagerClass == null) { // return null; // } // try { // IEconManager manager = econManagerClass.newInstance(); // manager.setPlayer(uuid); // return manager; // } catch(Exception ex) { // MyEssentialsCore.instance.LOG.info("Failed to create IEconManager", ex); // } // // return null; // Hopefully this doesn't break things... // } // // /** // * Takes the amount of money specified. // * Returns false if player doesn't have the money necessary // */ // public boolean takeMoneyFromPlayer(EntityPlayer player, int amount) { // if(costItemName.equals(CURRENCY_FORGE_ESSENTIALS) || costItemName.equals(CURRENCY_VAULT) || costItemName.startsWith(CURRENCY_CUSTOM)) { // IEconManager eco = economyManagerForUUID(player.getUniqueID()); // if (eco == null) // return false; // int wallet = eco.getWallet(); // if (wallet >= amount) { // eco.removeFromWallet(amount); // return true; // } // return false; // } else { // return PlayerUtils.takeItemFromPlayer(player, costItemName, amount); // } // } // // /** // * Takes the amount of money specified. // * Returns false if player doesn't have the money necessary // */ // public void giveMoneyToPlayer(EntityPlayer player, int amount) { // if (costItemName.equals(CURRENCY_FORGE_ESSENTIALS) || costItemName.equals(CURRENCY_VAULT) || costItemName.startsWith(CURRENCY_CUSTOM)) { // IEconManager eco = economyManagerForUUID(player.getUniqueID()); // if (eco == null) // return; // eco.addToWallet(amount); // } else { // PlayerUtils.giveItemToPlayer(player, costItemName, amount); // } // } // // /** // * Gets the currency string currently used. // */ // public String getCurrency(int amount) { // if(costItemName.equals(CURRENCY_FORGE_ESSENTIALS) || costItemName.equals(CURRENCY_VAULT) || costItemName.startsWith(CURRENCY_CUSTOM)) { // if (econManagerClass == null) { // return null; // } // try { // IEconManager manager = econManagerClass.newInstance(); // return manager.currency(amount); // } catch(Exception ex) { // MyEssentialsCore.instance.LOG.info("Failed to create IEconManager", ex); // } // return "$"; // // } else { // return ItemUtils.itemStackFromName(costItemName).getDisplayName() + (amount == 1 ? "" : "s"); // } // } // } // // Path: src/main/java/myessentials/economy/api/IEconManager.java // public interface IEconManager { // // void setPlayer(UUID uuid); // // /** // * Add a set amount to a target's Wallet // */ // void addToWallet(int amountToAdd); // // /** // * Get the amount of money the player has // */ // int getWallet(); // // /** // * Remove a set amount from a target's Wallet // * returns true if it succeded, false if it didn't // */ // boolean removeFromWallet(int amountToSubtract); // // /** // * Set the target's Wallet to the specified amount // */ // void setWallet(int setAmount, EntityPlayer player); // // /** // * Gets the singular or plural term of the currency used // */ // String currency(int amount); // // /** // * Gets a combo of getWallet + currency // */ // String getMoneyString(); // // /** // * Saves all wallets to disk // * (for users still on the server when it's stopping) // */ // void save(); // // Map<String, Integer> getItemTables(); // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // Path: src/test/java/myessentials/test/economy/EconomyForgeEssentialsTest.java import metest.api.TestPlayer; import myessentials.economy.api.Economy; import myessentials.economy.api.IEconManager; import myessentials.test.MECTest; import net.minecraft.entity.player.EntityPlayerMP; import org.junit.Assert; import org.junit.Before; import org.junit.Test; package myessentials.test.economy; public class EconomyForgeEssentialsTest extends MECTest { private EntityPlayerMP player; private Economy economy;
private IEconManager manager;
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/entities/VolumeTest.java
// Path: src/main/java/myessentials/entities/api/Volume.java // public class Volume implements IChatFormat { // // private final int minX, minY, minZ; // private final int maxX, maxY, maxZ; // // public Volume(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { // this.minX = minX; // this.minY = minY; // this.minZ = minZ; // this.maxX = maxX; // this.maxY = maxY; // this.maxZ = maxZ; // } // // public int getMinX() { // return minX; // } // // public int getMinY() { // return minY; // } // // public int getMinZ() { // return minZ; // } // // public int getMaxX() { // return maxX; // } // // public int getMaxY() { // return maxY; // } // // public int getMaxZ() { // return maxZ; // } // // public Volume translate(ForgeDirection direction) { // Volume volume = this; // switch (direction) { // case DOWN: // volume = new Volume(volume.getMinX(), -volume.getMaxZ(), volume.getMinY(), volume.getMaxX(), volume.getMinZ(), volume.getMaxY()); // break; // case UP: // volume = new Volume(volume.getMinX(), volume.getMinZ(), volume.getMinY(), volume.getMaxX(), volume.getMaxZ(), volume.getMaxY()); // break; // case NORTH: // volume = new Volume(volume.getMinX(), volume.getMinY(), - volume.getMaxZ(), volume.getMaxX(), volume.getMaxY(), volume.getMinZ()); // break; // case WEST: // volume = new Volume(- volume.getMaxZ(), volume.getMinY(), volume.getMinX(), volume.getMinZ(), volume.getMaxY(), volume.getMaxX()); // break; // case EAST: // volume = new Volume(volume.getMinZ(), volume.getMinY(), volume.getMinX(), volume.getMaxZ(), volume.getMaxY(), volume.getMaxX()); // break; // case SOUTH: // // The translation on South is already the correct one. // break; // case UNKNOWN: // break; // } // return volume; // } // // public Volume intersect(Volume other) { // if (other.getMaxX() >= minX && other.getMinX() <= maxX && // other.getMaxY() >= minY && other.getMinY() <= maxY && // other.getMaxZ() >= minZ && other.getMinZ() <= maxZ) { // // int x1, y1, z1, x2, y2, z2; // // x1 = (minX < other.getMinX()) ? other.getMinX() : minX; // y1 = (minY < other.getMinY()) ? other.getMinY() : minY; // z1 = (minZ < other.getMinZ()) ? other.getMinZ() : minZ; // x2 = (maxX > other.getMaxX()) ? other.getMaxX() : maxX; // y2 = (maxY > other.getMaxY()) ? other.getMaxY() : maxY; // z2= (maxZ > other.getMaxZ()) ? other.getMaxZ() : maxZ; // // return new Volume(x1, y1, z1, x2, y2, z2); // } // return null; // } // // public int getVolumeAmount() { // return (maxX - minX + 1) * (maxY - minY + 1) * (maxZ - minZ + 1); // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof Volume) { // Volume other = (Volume)obj; // return other.minX == minX && other.minY == minY && other.minZ == minZ && other.maxX == maxX && other.maxY == maxY && other.maxZ == maxZ; // } // return super.equals(obj); // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.volume", minX, minY, minZ, maxX, maxY, maxZ); // } // // public static class Serializer extends SerializerTemplate<Volume> { // // @Override // public void register(GsonBuilder builder) { // builder.registerTypeAdapter(Volume.class, this); // } // // @Override // public JsonElement serialize(Volume volume, Type typeOfSrc, JsonSerializationContext context) { // JsonArray json = new JsonArray(); // json.add(new JsonPrimitive(volume.getMinX())); // json.add(new JsonPrimitive(volume.getMinY())); // json.add(new JsonPrimitive(volume.getMinZ())); // json.add(new JsonPrimitive(volume.getMaxX())); // json.add(new JsonPrimitive(volume.getMaxY())); // json.add(new JsonPrimitive(volume.getMaxZ())); // return json; // } // // @Override // public Volume deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // JsonArray jsonArray = json.getAsJsonArray(); // return new Volume(jsonArray.get(0).getAsInt(), jsonArray.get(1).getAsInt(), jsonArray.get(2).getAsInt(), // jsonArray.get(3).getAsInt(), jsonArray.get(4).getAsInt(), jsonArray.get(5).getAsInt()); // } // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // }
import junit.framework.Assert; import myessentials.entities.api.Volume; import myessentials.test.MECTest; import org.junit.Test;
package myessentials.test.entities; public class VolumeTest extends MECTest { @Test public void volumeEquality() {
// Path: src/main/java/myessentials/entities/api/Volume.java // public class Volume implements IChatFormat { // // private final int minX, minY, minZ; // private final int maxX, maxY, maxZ; // // public Volume(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { // this.minX = minX; // this.minY = minY; // this.minZ = minZ; // this.maxX = maxX; // this.maxY = maxY; // this.maxZ = maxZ; // } // // public int getMinX() { // return minX; // } // // public int getMinY() { // return minY; // } // // public int getMinZ() { // return minZ; // } // // public int getMaxX() { // return maxX; // } // // public int getMaxY() { // return maxY; // } // // public int getMaxZ() { // return maxZ; // } // // public Volume translate(ForgeDirection direction) { // Volume volume = this; // switch (direction) { // case DOWN: // volume = new Volume(volume.getMinX(), -volume.getMaxZ(), volume.getMinY(), volume.getMaxX(), volume.getMinZ(), volume.getMaxY()); // break; // case UP: // volume = new Volume(volume.getMinX(), volume.getMinZ(), volume.getMinY(), volume.getMaxX(), volume.getMaxZ(), volume.getMaxY()); // break; // case NORTH: // volume = new Volume(volume.getMinX(), volume.getMinY(), - volume.getMaxZ(), volume.getMaxX(), volume.getMaxY(), volume.getMinZ()); // break; // case WEST: // volume = new Volume(- volume.getMaxZ(), volume.getMinY(), volume.getMinX(), volume.getMinZ(), volume.getMaxY(), volume.getMaxX()); // break; // case EAST: // volume = new Volume(volume.getMinZ(), volume.getMinY(), volume.getMinX(), volume.getMaxZ(), volume.getMaxY(), volume.getMaxX()); // break; // case SOUTH: // // The translation on South is already the correct one. // break; // case UNKNOWN: // break; // } // return volume; // } // // public Volume intersect(Volume other) { // if (other.getMaxX() >= minX && other.getMinX() <= maxX && // other.getMaxY() >= minY && other.getMinY() <= maxY && // other.getMaxZ() >= minZ && other.getMinZ() <= maxZ) { // // int x1, y1, z1, x2, y2, z2; // // x1 = (minX < other.getMinX()) ? other.getMinX() : minX; // y1 = (minY < other.getMinY()) ? other.getMinY() : minY; // z1 = (minZ < other.getMinZ()) ? other.getMinZ() : minZ; // x2 = (maxX > other.getMaxX()) ? other.getMaxX() : maxX; // y2 = (maxY > other.getMaxY()) ? other.getMaxY() : maxY; // z2= (maxZ > other.getMaxZ()) ? other.getMaxZ() : maxZ; // // return new Volume(x1, y1, z1, x2, y2, z2); // } // return null; // } // // public int getVolumeAmount() { // return (maxX - minX + 1) * (maxY - minY + 1) * (maxZ - minZ + 1); // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof Volume) { // Volume other = (Volume)obj; // return other.minX == minX && other.minY == minY && other.minZ == minZ && other.maxX == maxX && other.maxY == maxY && other.maxZ == maxZ; // } // return super.equals(obj); // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.volume", minX, minY, minZ, maxX, maxY, maxZ); // } // // public static class Serializer extends SerializerTemplate<Volume> { // // @Override // public void register(GsonBuilder builder) { // builder.registerTypeAdapter(Volume.class, this); // } // // @Override // public JsonElement serialize(Volume volume, Type typeOfSrc, JsonSerializationContext context) { // JsonArray json = new JsonArray(); // json.add(new JsonPrimitive(volume.getMinX())); // json.add(new JsonPrimitive(volume.getMinY())); // json.add(new JsonPrimitive(volume.getMinZ())); // json.add(new JsonPrimitive(volume.getMaxX())); // json.add(new JsonPrimitive(volume.getMaxY())); // json.add(new JsonPrimitive(volume.getMaxZ())); // return json; // } // // @Override // public Volume deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // JsonArray jsonArray = json.getAsJsonArray(); // return new Volume(jsonArray.get(0).getAsInt(), jsonArray.get(1).getAsInt(), jsonArray.get(2).getAsInt(), // jsonArray.get(3).getAsInt(), jsonArray.get(4).getAsInt(), jsonArray.get(5).getAsInt()); // } // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // Path: src/test/java/myessentials/test/entities/VolumeTest.java import junit.framework.Assert; import myessentials.entities.api.Volume; import myessentials.test.MECTest; import org.junit.Test; package myessentials.test.entities; public class VolumeTest extends MECTest { @Test public void volumeEquality() {
Volume v1 = new Volume(0, 0, 0, 2, 2, 2);
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/json/FakeSerializableParentObject.java
// Path: src/main/java/myessentials/json/api/SerializerTemplate.java // public abstract class SerializerTemplate<T> implements JsonSerializer<T>, JsonDeserializer<T> { // // public GsonBuilder createBuilder() { // GsonBuilder builder = new GsonBuilder(); // register(builder); // return builder; // } // // public abstract void register(GsonBuilder builder); // }
import com.google.gson.*; import myessentials.json.api.SerializerTemplate; import java.lang.reflect.Type;
package myessentials.test.json; public class FakeSerializableParentObject { public FakeSerializableObject obj; public int z = 0;
// Path: src/main/java/myessentials/json/api/SerializerTemplate.java // public abstract class SerializerTemplate<T> implements JsonSerializer<T>, JsonDeserializer<T> { // // public GsonBuilder createBuilder() { // GsonBuilder builder = new GsonBuilder(); // register(builder); // return builder; // } // // public abstract void register(GsonBuilder builder); // } // Path: src/test/java/myessentials/test/json/FakeSerializableParentObject.java import com.google.gson.*; import myessentials.json.api.SerializerTemplate; import java.lang.reflect.Type; package myessentials.test.json; public class FakeSerializableParentObject { public FakeSerializableObject obj; public int z = 0;
public static class Serializer extends SerializerTemplate<FakeSerializableParentObject> {
MyEssentials/MyEssentials-Core
src/main/java/myessentials/config/api/ConfigTemplate.java
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // }
import myessentials.MyEssentialsCore; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import org.apache.commons.lang3.exception.ExceptionUtils; import java.io.File; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List;
} } /** * Loads the config file from the hard drive */ public void reload() { config.load(); for (ConfigProperty property : properties) { ConfigCategory category = config.getCategory(property.category); Property forgeProp; if (!category.containsKey(property.name)) { forgeProp = new Property(property.name, property.get().toString(), property.getType()); forgeProp.comment = property.comment; category.put(property.name, forgeProp); } else { forgeProp = category.get(property.name); forgeProp.comment = property.comment; } setProperty(property, forgeProp); } config.save(); } private void bind() { for (Field field : getClass().getDeclaredFields()) { if (field.getType().isAssignableFrom(ConfigProperty.class)) { try { properties.add((ConfigProperty)field.get(this)); } catch (IllegalAccessException ex) {
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // } // Path: src/main/java/myessentials/config/api/ConfigTemplate.java import myessentials.MyEssentialsCore; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import org.apache.commons.lang3.exception.ExceptionUtils; import java.io.File; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; } } /** * Loads the config file from the hard drive */ public void reload() { config.load(); for (ConfigProperty property : properties) { ConfigCategory category = config.getCategory(property.category); Property forgeProp; if (!category.containsKey(property.name)) { forgeProp = new Property(property.name, property.get().toString(), property.getType()); forgeProp.comment = property.comment; category.put(property.name, forgeProp); } else { forgeProp = category.get(property.name); forgeProp.comment = property.comment; } setProperty(property, forgeProp); } config.save(); } private void bind() { for (Field field : getClass().getDeclaredFields()) { if (field.getType().isAssignableFrom(ConfigProperty.class)) { try { properties.add((ConfigProperty)field.get(this)); } catch (IllegalAccessException ex) {
MyEssentialsCore.instance.LOG.error("Failed to access " + field.getName() + " while binding to config " + config.getConfigFile().getName());
MyEssentials/MyEssentials-Core
src/main/java/myessentials/Config.java
// Path: src/main/java/myessentials/config/api/ConfigProperty.java // public class ConfigProperty<T> { // // private T value; // // public final String name; // public final String category; // public final String comment; // // // public ConfigProperty(String name, String category, String comment, T defaultValue) { // this.name = name; // this.category = category; // this.comment = comment; // this.value = defaultValue; // } // // /** // * Sets the value inside the property // */ // public void set(T value) { // this.value = value; // } // // /** // * Returns the value retained inside the property // */ // public T get() { // return value; // } // // public boolean isClassType(Class clazz) { // return value.getClass().isAssignableFrom(clazz); // } // // public Property.Type getType() { // return CONFIG_TYPES.get(value.getClass()); // } // // // private static final Map<Class<?>, Property.Type> CONFIG_TYPES = ImmutableMap.<Class<?>, Property.Type> builder().put(Integer.class, Property.Type.INTEGER) // .put(int.class, Property.Type.INTEGER).put(Integer[].class, Property.Type.INTEGER) // .put(int[].class, Property.Type.INTEGER).put(Double.class, Property.Type.DOUBLE) // .put(double.class, Property.Type.DOUBLE).put(Double[].class, Property.Type.DOUBLE) // .put(double[].class, Property.Type.DOUBLE).put(Float.class, Property.Type.DOUBLE) // .put(float.class, Property.Type.DOUBLE).put(Float[].class, Property.Type.DOUBLE) // .put(float[].class, Property.Type.DOUBLE).put(Boolean.class, Property.Type.BOOLEAN) // .put(boolean.class, Property.Type.BOOLEAN).put(Boolean[].class, Property.Type.BOOLEAN) // .put(boolean[].class, Property.Type.BOOLEAN).put(String.class, Property.Type.STRING) // .put(String[].class, Property.Type.STRING).build(); // // } // // Path: src/main/java/myessentials/config/api/ConfigTemplate.java // public abstract class ConfigTemplate { // // protected String modID; // protected Configuration config; // protected List<ConfigProperty> properties = new ArrayList<ConfigProperty>(); // // public void init(String forgeConfigPath, String modID) { // init(new File(forgeConfigPath), modID); // } // // public void init(File forgeConfigFile, String modID) { // init(new Configuration(forgeConfigFile), modID); // } // // public void init(Configuration forgeConfig, String modID) { // this.config = forgeConfig; // this.modID = modID; // bind(); // reload(); // } // // public Configuration getForgeConfig() { // return this.config; // } // // public String getModID() { // return this.modID; // } // // /** // * Adds a ConfigProperty instance which can then be loaded/saved in the config. // */ // public void addBinding(ConfigProperty property) { // addBinding(property, false); // } // // /** // * Adds a ConfigProperty instance which can then be loaded/saved in the config. // * It will automatically reload if specified. // */ // public void addBinding(ConfigProperty property, boolean reload) { // this.properties.add(property); // if (reload) { // reload(); // } // } // // /** // * Loads the config file from the hard drive // */ // public void reload() { // config.load(); // for (ConfigProperty property : properties) { // ConfigCategory category = config.getCategory(property.category); // Property forgeProp; // if (!category.containsKey(property.name)) { // forgeProp = new Property(property.name, property.get().toString(), property.getType()); // forgeProp.comment = property.comment; // category.put(property.name, forgeProp); // } else { // forgeProp = category.get(property.name); // forgeProp.comment = property.comment; // } // setProperty(property, forgeProp); // } // config.save(); // } // // private void bind() { // for (Field field : getClass().getDeclaredFields()) { // if (field.getType().isAssignableFrom(ConfigProperty.class)) { // try { // properties.add((ConfigProperty)field.get(this)); // } catch (IllegalAccessException ex) { // MyEssentialsCore.instance.LOG.error("Failed to access " + field.getName() + " while binding to config " + config.getConfigFile().getName()); // MyEssentialsCore.instance.LOG.error(ExceptionUtils.getStackTrace(ex)); // } // } // } // } // // @SuppressWarnings("unchecked") // private void setProperty(ConfigProperty property, Property forgeProp) { // try { // if (property.isClassType(Integer.class)) { // property.set(forgeProp.getInt()); // } else if (property.isClassType(Double.class)) { // property.set(forgeProp.getDouble()); // } else if (property.isClassType(Boolean.class)) { // property.set(forgeProp.getBoolean()); // } else if (property.isClassType(String.class)) { // property.set(forgeProp.getString()); // } else if (property.isClassType(Integer[].class)) { // property.set(forgeProp.getIntList()); // } else if (property.isClassType(Double[].class)) { // property.set(forgeProp.getDoubleList()); // } else if (property.isClassType(Boolean[].class)) { // property.set(forgeProp.getBooleanList()); // } else if (property.isClassType(String[].class)) { // property.set(forgeProp.getStringList()); // } // } catch (RuntimeException ex) { // MyEssentialsCore.instance.LOG.error("Config value of " + property.name + " in category " + property.category + " was not of the proper type!"); // MyEssentialsCore.instance.LOG.error(ExceptionUtils.getStackTrace(ex)); // throw ex; // } // } // }
import myessentials.config.api.ConfigProperty; import myessentials.config.api.ConfigTemplate;
package myessentials; public class Config extends ConfigTemplate { public static final Config instance = new Config();
// Path: src/main/java/myessentials/config/api/ConfigProperty.java // public class ConfigProperty<T> { // // private T value; // // public final String name; // public final String category; // public final String comment; // // // public ConfigProperty(String name, String category, String comment, T defaultValue) { // this.name = name; // this.category = category; // this.comment = comment; // this.value = defaultValue; // } // // /** // * Sets the value inside the property // */ // public void set(T value) { // this.value = value; // } // // /** // * Returns the value retained inside the property // */ // public T get() { // return value; // } // // public boolean isClassType(Class clazz) { // return value.getClass().isAssignableFrom(clazz); // } // // public Property.Type getType() { // return CONFIG_TYPES.get(value.getClass()); // } // // // private static final Map<Class<?>, Property.Type> CONFIG_TYPES = ImmutableMap.<Class<?>, Property.Type> builder().put(Integer.class, Property.Type.INTEGER) // .put(int.class, Property.Type.INTEGER).put(Integer[].class, Property.Type.INTEGER) // .put(int[].class, Property.Type.INTEGER).put(Double.class, Property.Type.DOUBLE) // .put(double.class, Property.Type.DOUBLE).put(Double[].class, Property.Type.DOUBLE) // .put(double[].class, Property.Type.DOUBLE).put(Float.class, Property.Type.DOUBLE) // .put(float.class, Property.Type.DOUBLE).put(Float[].class, Property.Type.DOUBLE) // .put(float[].class, Property.Type.DOUBLE).put(Boolean.class, Property.Type.BOOLEAN) // .put(boolean.class, Property.Type.BOOLEAN).put(Boolean[].class, Property.Type.BOOLEAN) // .put(boolean[].class, Property.Type.BOOLEAN).put(String.class, Property.Type.STRING) // .put(String[].class, Property.Type.STRING).build(); // // } // // Path: src/main/java/myessentials/config/api/ConfigTemplate.java // public abstract class ConfigTemplate { // // protected String modID; // protected Configuration config; // protected List<ConfigProperty> properties = new ArrayList<ConfigProperty>(); // // public void init(String forgeConfigPath, String modID) { // init(new File(forgeConfigPath), modID); // } // // public void init(File forgeConfigFile, String modID) { // init(new Configuration(forgeConfigFile), modID); // } // // public void init(Configuration forgeConfig, String modID) { // this.config = forgeConfig; // this.modID = modID; // bind(); // reload(); // } // // public Configuration getForgeConfig() { // return this.config; // } // // public String getModID() { // return this.modID; // } // // /** // * Adds a ConfigProperty instance which can then be loaded/saved in the config. // */ // public void addBinding(ConfigProperty property) { // addBinding(property, false); // } // // /** // * Adds a ConfigProperty instance which can then be loaded/saved in the config. // * It will automatically reload if specified. // */ // public void addBinding(ConfigProperty property, boolean reload) { // this.properties.add(property); // if (reload) { // reload(); // } // } // // /** // * Loads the config file from the hard drive // */ // public void reload() { // config.load(); // for (ConfigProperty property : properties) { // ConfigCategory category = config.getCategory(property.category); // Property forgeProp; // if (!category.containsKey(property.name)) { // forgeProp = new Property(property.name, property.get().toString(), property.getType()); // forgeProp.comment = property.comment; // category.put(property.name, forgeProp); // } else { // forgeProp = category.get(property.name); // forgeProp.comment = property.comment; // } // setProperty(property, forgeProp); // } // config.save(); // } // // private void bind() { // for (Field field : getClass().getDeclaredFields()) { // if (field.getType().isAssignableFrom(ConfigProperty.class)) { // try { // properties.add((ConfigProperty)field.get(this)); // } catch (IllegalAccessException ex) { // MyEssentialsCore.instance.LOG.error("Failed to access " + field.getName() + " while binding to config " + config.getConfigFile().getName()); // MyEssentialsCore.instance.LOG.error(ExceptionUtils.getStackTrace(ex)); // } // } // } // } // // @SuppressWarnings("unchecked") // private void setProperty(ConfigProperty property, Property forgeProp) { // try { // if (property.isClassType(Integer.class)) { // property.set(forgeProp.getInt()); // } else if (property.isClassType(Double.class)) { // property.set(forgeProp.getDouble()); // } else if (property.isClassType(Boolean.class)) { // property.set(forgeProp.getBoolean()); // } else if (property.isClassType(String.class)) { // property.set(forgeProp.getString()); // } else if (property.isClassType(Integer[].class)) { // property.set(forgeProp.getIntList()); // } else if (property.isClassType(Double[].class)) { // property.set(forgeProp.getDoubleList()); // } else if (property.isClassType(Boolean[].class)) { // property.set(forgeProp.getBooleanList()); // } else if (property.isClassType(String[].class)) { // property.set(forgeProp.getStringList()); // } // } catch (RuntimeException ex) { // MyEssentialsCore.instance.LOG.error("Config value of " + property.name + " in category " + property.category + " was not of the proper type!"); // MyEssentialsCore.instance.LOG.error(ExceptionUtils.getStackTrace(ex)); // throw ex; // } // } // } // Path: src/main/java/myessentials/Config.java import myessentials.config.api.ConfigProperty; import myessentials.config.api.ConfigTemplate; package myessentials; public class Config extends ConfigTemplate { public static final Config instance = new Config();
public ConfigProperty<Boolean> maintenanceMode = new ConfigProperty<Boolean>(
MyEssentials/MyEssentials-Core
src/main/java/myessentials/chat/api/ChatComponentFormatted.java
// Path: src/main/java/myessentials/exception/FormatException.java // public class FormatException extends RuntimeException { // // public FormatException(String message) { // super(message); // } // // } // // Path: src/main/java/myessentials/utils/ColorUtils.java // public class ColorUtils { // // public static final ChatStyle stylePlayer = new ChatStyle().setColor(EnumChatFormatting.WHITE); // public static final ChatStyle styleOwner = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleTown = new ChatStyle().setColor(EnumChatFormatting.GOLD); // public static final ChatStyle styleSelectedTown = new ChatStyle().setColor(EnumChatFormatting.GREEN); // public static final ChatStyle styleInfoText = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleConfigurableFlag = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleUnconfigurableFlag = new ChatStyle().setColor(EnumChatFormatting.DARK_GRAY); // public static final ChatStyle styleValueFalse = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleValueRegular = new ChatStyle().setColor(EnumChatFormatting.GREEN); // public static final ChatStyle styleDescription = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleCoords = new ChatStyle().setColor(EnumChatFormatting.BLUE); // public static final ChatStyle styleComma = new ChatStyle().setColor(EnumChatFormatting.WHITE); // public static final ChatStyle styleEmpty = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleAdmin = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleGroupType = new ChatStyle().setColor(EnumChatFormatting.BLUE); // public static final ChatStyle styleGroupText = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleGroupParents = new ChatStyle().setColor(EnumChatFormatting.WHITE); // public static final ChatStyle styleGroup = new ChatStyle().setColor(EnumChatFormatting.BLUE); // // public static final Map<Character, EnumChatFormatting> colorMap = new HashMap<Character, EnumChatFormatting>(); // static { // ColorUtils.colorMap.put('0', EnumChatFormatting.BLACK); // ColorUtils.colorMap.put('1', EnumChatFormatting.DARK_BLUE); // ColorUtils.colorMap.put('2', EnumChatFormatting.DARK_GREEN); // ColorUtils.colorMap.put('3', EnumChatFormatting.DARK_AQUA); // ColorUtils.colorMap.put('4', EnumChatFormatting.DARK_RED); // ColorUtils.colorMap.put('5', EnumChatFormatting.DARK_PURPLE); // ColorUtils.colorMap.put('6', EnumChatFormatting.GOLD); // ColorUtils.colorMap.put('7', EnumChatFormatting.GRAY); // ColorUtils.colorMap.put('8', EnumChatFormatting.DARK_GRAY); // ColorUtils.colorMap.put('9', EnumChatFormatting.BLUE); // ColorUtils.colorMap.put('a', EnumChatFormatting.GREEN); // ColorUtils.colorMap.put('b', EnumChatFormatting.AQUA); // ColorUtils.colorMap.put('c', EnumChatFormatting.RED); // ColorUtils.colorMap.put('d', EnumChatFormatting.LIGHT_PURPLE); // ColorUtils.colorMap.put('e', EnumChatFormatting.YELLOW); // ColorUtils.colorMap.put('f', EnumChatFormatting.WHITE); // } // }
import myessentials.exception.FormatException; import myessentials.utils.ColorUtils; import net.minecraft.event.HoverEvent; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatStyle; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher;
return message; } private void addComponent(Iterator args) { // TODO: Instead of %s use other identifiers for lists of elements or container (maybe) Object currArg = args.next(); if (currArg instanceof IChatFormat) { buffer.appendSibling(((IChatFormat) currArg).toChatMessage()); } else if (currArg instanceof IChatComponent) { buffer.appendSibling((IChatComponent) currArg); } else if (currArg instanceof ChatComponentContainer) { resetBuffer(); for (IChatComponent message : (ChatComponentContainer) currArg) { this.appendSibling(message); } } } private void processComponent(String componentString, Iterator args) { String[] parts = componentString.split("\\|", 2); if (parts.length == 2) { if (parts[0].contains("N")) { resetBuffer(); } buffer.appendSibling(createComponent(parts, args)); } else if (parts.length == 1 && parts[0].equals("%s")){ addComponent(args); } else {
// Path: src/main/java/myessentials/exception/FormatException.java // public class FormatException extends RuntimeException { // // public FormatException(String message) { // super(message); // } // // } // // Path: src/main/java/myessentials/utils/ColorUtils.java // public class ColorUtils { // // public static final ChatStyle stylePlayer = new ChatStyle().setColor(EnumChatFormatting.WHITE); // public static final ChatStyle styleOwner = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleTown = new ChatStyle().setColor(EnumChatFormatting.GOLD); // public static final ChatStyle styleSelectedTown = new ChatStyle().setColor(EnumChatFormatting.GREEN); // public static final ChatStyle styleInfoText = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleConfigurableFlag = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleUnconfigurableFlag = new ChatStyle().setColor(EnumChatFormatting.DARK_GRAY); // public static final ChatStyle styleValueFalse = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleValueRegular = new ChatStyle().setColor(EnumChatFormatting.GREEN); // public static final ChatStyle styleDescription = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleCoords = new ChatStyle().setColor(EnumChatFormatting.BLUE); // public static final ChatStyle styleComma = new ChatStyle().setColor(EnumChatFormatting.WHITE); // public static final ChatStyle styleEmpty = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleAdmin = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleGroupType = new ChatStyle().setColor(EnumChatFormatting.BLUE); // public static final ChatStyle styleGroupText = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleGroupParents = new ChatStyle().setColor(EnumChatFormatting.WHITE); // public static final ChatStyle styleGroup = new ChatStyle().setColor(EnumChatFormatting.BLUE); // // public static final Map<Character, EnumChatFormatting> colorMap = new HashMap<Character, EnumChatFormatting>(); // static { // ColorUtils.colorMap.put('0', EnumChatFormatting.BLACK); // ColorUtils.colorMap.put('1', EnumChatFormatting.DARK_BLUE); // ColorUtils.colorMap.put('2', EnumChatFormatting.DARK_GREEN); // ColorUtils.colorMap.put('3', EnumChatFormatting.DARK_AQUA); // ColorUtils.colorMap.put('4', EnumChatFormatting.DARK_RED); // ColorUtils.colorMap.put('5', EnumChatFormatting.DARK_PURPLE); // ColorUtils.colorMap.put('6', EnumChatFormatting.GOLD); // ColorUtils.colorMap.put('7', EnumChatFormatting.GRAY); // ColorUtils.colorMap.put('8', EnumChatFormatting.DARK_GRAY); // ColorUtils.colorMap.put('9', EnumChatFormatting.BLUE); // ColorUtils.colorMap.put('a', EnumChatFormatting.GREEN); // ColorUtils.colorMap.put('b', EnumChatFormatting.AQUA); // ColorUtils.colorMap.put('c', EnumChatFormatting.RED); // ColorUtils.colorMap.put('d', EnumChatFormatting.LIGHT_PURPLE); // ColorUtils.colorMap.put('e', EnumChatFormatting.YELLOW); // ColorUtils.colorMap.put('f', EnumChatFormatting.WHITE); // } // } // Path: src/main/java/myessentials/chat/api/ChatComponentFormatted.java import myessentials.exception.FormatException; import myessentials.utils.ColorUtils; import net.minecraft.event.HoverEvent; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatStyle; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; return message; } private void addComponent(Iterator args) { // TODO: Instead of %s use other identifiers for lists of elements or container (maybe) Object currArg = args.next(); if (currArg instanceof IChatFormat) { buffer.appendSibling(((IChatFormat) currArg).toChatMessage()); } else if (currArg instanceof IChatComponent) { buffer.appendSibling((IChatComponent) currArg); } else if (currArg instanceof ChatComponentContainer) { resetBuffer(); for (IChatComponent message : (ChatComponentContainer) currArg) { this.appendSibling(message); } } } private void processComponent(String componentString, Iterator args) { String[] parts = componentString.split("\\|", 2); if (parts.length == 2) { if (parts[0].contains("N")) { resetBuffer(); } buffer.appendSibling(createComponent(parts, args)); } else if (parts.length == 1 && parts[0].equals("%s")){ addComponent(args); } else {
throw new FormatException("Format " + componentString + " is not valid. Valid format: {modifiers|text}");
MyEssentials/MyEssentials-Core
src/main/java/myessentials/chat/api/ChatComponentFormatted.java
// Path: src/main/java/myessentials/exception/FormatException.java // public class FormatException extends RuntimeException { // // public FormatException(String message) { // super(message); // } // // } // // Path: src/main/java/myessentials/utils/ColorUtils.java // public class ColorUtils { // // public static final ChatStyle stylePlayer = new ChatStyle().setColor(EnumChatFormatting.WHITE); // public static final ChatStyle styleOwner = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleTown = new ChatStyle().setColor(EnumChatFormatting.GOLD); // public static final ChatStyle styleSelectedTown = new ChatStyle().setColor(EnumChatFormatting.GREEN); // public static final ChatStyle styleInfoText = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleConfigurableFlag = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleUnconfigurableFlag = new ChatStyle().setColor(EnumChatFormatting.DARK_GRAY); // public static final ChatStyle styleValueFalse = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleValueRegular = new ChatStyle().setColor(EnumChatFormatting.GREEN); // public static final ChatStyle styleDescription = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleCoords = new ChatStyle().setColor(EnumChatFormatting.BLUE); // public static final ChatStyle styleComma = new ChatStyle().setColor(EnumChatFormatting.WHITE); // public static final ChatStyle styleEmpty = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleAdmin = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleGroupType = new ChatStyle().setColor(EnumChatFormatting.BLUE); // public static final ChatStyle styleGroupText = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleGroupParents = new ChatStyle().setColor(EnumChatFormatting.WHITE); // public static final ChatStyle styleGroup = new ChatStyle().setColor(EnumChatFormatting.BLUE); // // public static final Map<Character, EnumChatFormatting> colorMap = new HashMap<Character, EnumChatFormatting>(); // static { // ColorUtils.colorMap.put('0', EnumChatFormatting.BLACK); // ColorUtils.colorMap.put('1', EnumChatFormatting.DARK_BLUE); // ColorUtils.colorMap.put('2', EnumChatFormatting.DARK_GREEN); // ColorUtils.colorMap.put('3', EnumChatFormatting.DARK_AQUA); // ColorUtils.colorMap.put('4', EnumChatFormatting.DARK_RED); // ColorUtils.colorMap.put('5', EnumChatFormatting.DARK_PURPLE); // ColorUtils.colorMap.put('6', EnumChatFormatting.GOLD); // ColorUtils.colorMap.put('7', EnumChatFormatting.GRAY); // ColorUtils.colorMap.put('8', EnumChatFormatting.DARK_GRAY); // ColorUtils.colorMap.put('9', EnumChatFormatting.BLUE); // ColorUtils.colorMap.put('a', EnumChatFormatting.GREEN); // ColorUtils.colorMap.put('b', EnumChatFormatting.AQUA); // ColorUtils.colorMap.put('c', EnumChatFormatting.RED); // ColorUtils.colorMap.put('d', EnumChatFormatting.LIGHT_PURPLE); // ColorUtils.colorMap.put('e', EnumChatFormatting.YELLOW); // ColorUtils.colorMap.put('f', EnumChatFormatting.WHITE); // } // }
import myessentials.exception.FormatException; import myessentials.utils.ColorUtils; import net.minecraft.event.HoverEvent; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatStyle; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher;
addComponent(args); } else { throw new FormatException("Format " + componentString + " is not valid. Valid format: {modifiers|text}"); } } /** * Converts the modifiers String to a ChatStyle * {modifiers| some text} * ^^^^^^^^ ^^^^^^^^^ * STYLE for THIS TEXT */ private ChatStyle getStyle(String modifiers) { ChatStyle chatStyle = new ChatStyle(); for (char c : modifiers.toCharArray()) { applyModifier(chatStyle, c); } return chatStyle; } /** * Applies modifier to the style * Returns whether or not the modifier was valid */ private boolean applyModifier(ChatStyle chatStyle, char modifier) { if (modifier >= '0' && modifier <= '9' || modifier >= 'a' && modifier <= 'f') {
// Path: src/main/java/myessentials/exception/FormatException.java // public class FormatException extends RuntimeException { // // public FormatException(String message) { // super(message); // } // // } // // Path: src/main/java/myessentials/utils/ColorUtils.java // public class ColorUtils { // // public static final ChatStyle stylePlayer = new ChatStyle().setColor(EnumChatFormatting.WHITE); // public static final ChatStyle styleOwner = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleTown = new ChatStyle().setColor(EnumChatFormatting.GOLD); // public static final ChatStyle styleSelectedTown = new ChatStyle().setColor(EnumChatFormatting.GREEN); // public static final ChatStyle styleInfoText = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleConfigurableFlag = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleUnconfigurableFlag = new ChatStyle().setColor(EnumChatFormatting.DARK_GRAY); // public static final ChatStyle styleValueFalse = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleValueRegular = new ChatStyle().setColor(EnumChatFormatting.GREEN); // public static final ChatStyle styleDescription = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleCoords = new ChatStyle().setColor(EnumChatFormatting.BLUE); // public static final ChatStyle styleComma = new ChatStyle().setColor(EnumChatFormatting.WHITE); // public static final ChatStyle styleEmpty = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleAdmin = new ChatStyle().setColor(EnumChatFormatting.RED); // public static final ChatStyle styleGroupType = new ChatStyle().setColor(EnumChatFormatting.BLUE); // public static final ChatStyle styleGroupText = new ChatStyle().setColor(EnumChatFormatting.GRAY); // public static final ChatStyle styleGroupParents = new ChatStyle().setColor(EnumChatFormatting.WHITE); // public static final ChatStyle styleGroup = new ChatStyle().setColor(EnumChatFormatting.BLUE); // // public static final Map<Character, EnumChatFormatting> colorMap = new HashMap<Character, EnumChatFormatting>(); // static { // ColorUtils.colorMap.put('0', EnumChatFormatting.BLACK); // ColorUtils.colorMap.put('1', EnumChatFormatting.DARK_BLUE); // ColorUtils.colorMap.put('2', EnumChatFormatting.DARK_GREEN); // ColorUtils.colorMap.put('3', EnumChatFormatting.DARK_AQUA); // ColorUtils.colorMap.put('4', EnumChatFormatting.DARK_RED); // ColorUtils.colorMap.put('5', EnumChatFormatting.DARK_PURPLE); // ColorUtils.colorMap.put('6', EnumChatFormatting.GOLD); // ColorUtils.colorMap.put('7', EnumChatFormatting.GRAY); // ColorUtils.colorMap.put('8', EnumChatFormatting.DARK_GRAY); // ColorUtils.colorMap.put('9', EnumChatFormatting.BLUE); // ColorUtils.colorMap.put('a', EnumChatFormatting.GREEN); // ColorUtils.colorMap.put('b', EnumChatFormatting.AQUA); // ColorUtils.colorMap.put('c', EnumChatFormatting.RED); // ColorUtils.colorMap.put('d', EnumChatFormatting.LIGHT_PURPLE); // ColorUtils.colorMap.put('e', EnumChatFormatting.YELLOW); // ColorUtils.colorMap.put('f', EnumChatFormatting.WHITE); // } // } // Path: src/main/java/myessentials/chat/api/ChatComponentFormatted.java import myessentials.exception.FormatException; import myessentials.utils.ColorUtils; import net.minecraft.event.HoverEvent; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatStyle; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; addComponent(args); } else { throw new FormatException("Format " + componentString + " is not valid. Valid format: {modifiers|text}"); } } /** * Converts the modifiers String to a ChatStyle * {modifiers| some text} * ^^^^^^^^ ^^^^^^^^^ * STYLE for THIS TEXT */ private ChatStyle getStyle(String modifiers) { ChatStyle chatStyle = new ChatStyle(); for (char c : modifiers.toCharArray()) { applyModifier(chatStyle, c); } return chatStyle; } /** * Applies modifier to the style * Returns whether or not the modifier was valid */ private boolean applyModifier(ChatStyle chatStyle, char modifier) { if (modifier >= '0' && modifier <= '9' || modifier >= 'a' && modifier <= 'f') {
chatStyle.setColor(ColorUtils.colorMap.get(modifier));
MyEssentials/MyEssentials-Core
src/main/java/myessentials/entities/api/tool/Tool.java
// Path: src/main/java/myessentials/entities/api/BlockPos.java // public class BlockPos implements IChatFormat { // private final int dim; // private final int x; // private final int y; // private final int z; // // public BlockPos(int x, int y, int z, int dim) { // this.x = x; // this.y = y; // this.z = z; // this.dim = dim; // } // // public int getDim() { // return dim; // } // // public int getX() { // return x; // } // // public int getY() { // return y; // } // // public int getZ() { // return z; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public boolean equals(Object other) { // if(other instanceof BlockPos) { // BlockPos otherBP = (BlockPos) other; // return otherBP.dim == dim && otherBP.x == x && otherBP.y == y && otherBP.z == z; // } // return super.equals(other); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.blockpos", x, y, z, dim); // } // }
import myessentials.entities.api.BlockPos; import myessentials.utils.PlayerUtils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraft.util.EnumChatFormatting;
package myessentials.entities.api.tool; /** * A wrapper class for an instance of an itemstack which executes only on the server-side. */ public abstract class Tool { /** * Every tool starts with this string. Allows easy checks for invalid tools. */ public static final String IDENTIFIER = EnumChatFormatting.BLUE.toString(); protected EntityPlayer owner; /** * This is used as an identifier to find the itemstack in the player's inventory. */ protected String toolName; protected Tool(EntityPlayer owner, String toolName) { this.owner = owner; this.toolName = IDENTIFIER + toolName; }
// Path: src/main/java/myessentials/entities/api/BlockPos.java // public class BlockPos implements IChatFormat { // private final int dim; // private final int x; // private final int y; // private final int z; // // public BlockPos(int x, int y, int z, int dim) { // this.x = x; // this.y = y; // this.z = z; // this.dim = dim; // } // // public int getDim() { // return dim; // } // // public int getX() { // return x; // } // // public int getY() { // return y; // } // // public int getZ() { // return z; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public boolean equals(Object other) { // if(other instanceof BlockPos) { // BlockPos otherBP = (BlockPos) other; // return otherBP.dim == dim && otherBP.x == x && otherBP.y == y && otherBP.z == z; // } // return super.equals(other); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.blockpos", x, y, z, dim); // } // } // Path: src/main/java/myessentials/entities/api/tool/Tool.java import myessentials.entities.api.BlockPos; import myessentials.utils.PlayerUtils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraft.util.EnumChatFormatting; package myessentials.entities.api.tool; /** * A wrapper class for an instance of an itemstack which executes only on the server-side. */ public abstract class Tool { /** * Every tool starts with this string. Allows easy checks for invalid tools. */ public static final String IDENTIFIER = EnumChatFormatting.BLUE.toString(); protected EntityPlayer owner; /** * This is used as an identifier to find the itemstack in the player's inventory. */ protected String toolName; protected Tool(EntityPlayer owner, String toolName) { this.owner = owner; this.toolName = IDENTIFIER + toolName; }
public abstract void onItemUse(BlockPos bp, int face);
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/datasource/DatasourceTest.java
// Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // // Path: src/test/java/myessentials/test/TestConfig.java // public class TestConfig extends ConfigTemplate { // public static TestConfig instance = new TestConfig(); // }
import junit.framework.Assert; import myessentials.test.MECTest; import myessentials.test.TestConfig; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Set;
package myessentials.test.datasource; //@RunWith(MinecraftRunner.class) public class DatasourceTest extends MECTest { public static List<String> blockNames = new ArrayList<String>(); private FakeDatasource datasource; @Before public void shouldInitDatasource() {
// Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // // Path: src/test/java/myessentials/test/TestConfig.java // public class TestConfig extends ConfigTemplate { // public static TestConfig instance = new TestConfig(); // } // Path: src/test/java/myessentials/test/datasource/DatasourceTest.java import junit.framework.Assert; import myessentials.test.MECTest; import myessentials.test.TestConfig; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Set; package myessentials.test.datasource; //@RunWith(MinecraftRunner.class) public class DatasourceTest extends MECTest { public static List<String> blockNames = new ArrayList<String>(); private FakeDatasource datasource; @Before public void shouldInitDatasource() {
datasource = new FakeDatasource(LOG, TestConfig.instance, new FakeSchema());
MyEssentials/MyEssentials-Core
src/main/java/myessentials/datasource/api/Schema.java
// Path: src/main/java/myessentials/datasource/api/bridge/BridgeSQL.java // public abstract class BridgeSQL extends Bridge { // // public String prefix = ""; // public String[] userProperties = {}; // // public BridgeSQL() { // } // // protected Properties properties = new Properties(); // protected String dsn = ""; // protected Connection conn = null; // protected String autoIncrement; // // protected abstract void initConnection(); // // protected abstract void initProperties(); // // public Connection getConnection() { // return this.conn; // } // // public String getAutoIncrement() { // return this.autoIncrement; // } // }
import myessentials.datasource.api.bridge.BridgeSQL; import java.util.ArrayList; import java.util.List;
package myessentials.datasource.api; /** * Retains information about the changes that have occured in the database to support backwards compatibility. * Extend this and add to it all the DBUpdates you want. * This has been isolated because of the amount of lines the updates can have. */ public abstract class Schema { protected List<DBUpdate> updates = new ArrayList<DBUpdate>();
// Path: src/main/java/myessentials/datasource/api/bridge/BridgeSQL.java // public abstract class BridgeSQL extends Bridge { // // public String prefix = ""; // public String[] userProperties = {}; // // public BridgeSQL() { // } // // protected Properties properties = new Properties(); // protected String dsn = ""; // protected Connection conn = null; // protected String autoIncrement; // // protected abstract void initConnection(); // // protected abstract void initProperties(); // // public Connection getConnection() { // return this.conn; // } // // public String getAutoIncrement() { // return this.autoIncrement; // } // } // Path: src/main/java/myessentials/datasource/api/Schema.java import myessentials.datasource.api.bridge.BridgeSQL; import java.util.ArrayList; import java.util.List; package myessentials.datasource.api; /** * Retains information about the changes that have occured in the database to support backwards compatibility. * Extend this and add to it all the DBUpdates you want. * This has been isolated because of the amount of lines the updates can have. */ public abstract class Schema { protected List<DBUpdate> updates = new ArrayList<DBUpdate>();
public abstract void initializeUpdates(BridgeSQL bridge);
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/entities/sign/FakeSign.java
// Path: src/main/java/myessentials/entities/api/sign/Sign.java // public abstract class Sign { // // public static final String IDENTIFIER = EnumChatFormatting.DARK_BLUE.toString(); // // public final SignType signType; // // protected NBTBase data; // // protected BlockPos bp; // // protected Sign(SignType signType) { // this.signType = signType; // } // // public abstract void onRightClick(EntityPlayer player); // // protected abstract String[] getText(); // // public void onShiftRightClick(EntityPlayer player) { // } // // public TileEntitySign createSignBlock(EntityPlayer player, BlockPos bp, int face) { // World world = MinecraftServer.getServer().worldServerForDimension(bp.getDim()); // ForgeDirection direction = ForgeDirection.getOrientation(face); // if(direction == ForgeDirection.DOWN || face == 1) { // int i1 = MathHelper.floor_double((double) ((player.rotationYaw + 180.0F) * 16.0F / 360.0F) + 0.5D) & 15; // world.setBlock(bp.getX(), bp.getY(), bp.getZ(), Blocks.standing_sign, i1, 3); // } else { // world.setBlock(bp.getX(), bp.getY(), bp.getZ(), Blocks.wall_sign, face, 3); // } // // TileEntitySign te = (TileEntitySign) world.getTileEntity(bp.getX(), bp.getY(), bp.getZ()); // String[] text = Arrays.copyOf(getText(), 4); // text[0] = IDENTIFIER + text[0]; // normalizeText(text); // // for(int i = 0; i < 4; i++) { // te.signText[i] = text[i] == null ? "" : text[i]; // } // // NBTTagCompound rootTag = new NBTTagCompound(); // rootTag.setString("Type", signType.getTypeID()); // if(data != null) // rootTag.setTag("Value", data); // SignClassTransformer.setMyEssentialsDataValue(te, rootTag); // // return te; // } // // public TileEntitySign getTileEntity() { // World world = MinecraftServer.getServer().worldServerForDimension(bp.getDim()); // TileEntity te = world.getTileEntity(bp.getX(), bp.getY(), bp.getZ());; // return te instanceof TileEntitySign ? (TileEntitySign) te : null; // } // // private void normalizeText(String[] text) { // for(int i = 0; i < 4; i++) { // if(text[i].length() > 15) { // text[i] = text[i].substring(0, 15); // } // } // } // // public void deleteSignBlock() { // World world = MinecraftServer.getServer().worldServerForDimension(bp.getDim()); // world.removeTileEntity(bp.getX(), bp.getY(), bp.getZ()); // world.setBlock(bp.getX(), bp.getY(), bp.getZ(), Blocks.air); // } // // public static class Container extends ArrayList<Sign> { // @Override // public boolean add(Sign sign) { // return super.add(sign); // } // // public Sign get(BlockPos bp) { // for(Sign sign : this) { // if(bp.equals(sign.bp)) { // return sign; // } // } // return null; // } // // public boolean contains(BlockPos bp) { // for(Sign sign : this) { // if(bp.equals(sign.bp)) { // return true; // } // } // return false; // } // // public boolean remove(BlockPos bp) { // for(Iterator<Sign> it = iterator(); it.hasNext(); ) { // Sign sign = it.next(); // if(bp.equals(sign.bp)) { // it.remove(); // return true; // } // } // return false; // } // } // } // // Path: src/main/java/myessentials/entities/api/sign/SignType.java // public abstract class SignType { // /** // * The unique ID for this type. // * @return The ID following the syntax: "modId:signType" // */ // public abstract String getTypeID(); // // /** // * Loads a sign data of this type. // * @param tileEntity The tile entity that is being loaded // * @param signData The data stored on the sign // * @return The loaded sign // */ // public abstract Sign loadData(TileEntitySign tileEntity, NBTBase signData); // // /** // * Register this type on the {@link SignManager}, all types must be registered to be recognized. // */ // public void register() { // SignManager.instance.signTypes.put(getTypeID(), this); // } // // public abstract boolean isTileValid(TileEntitySign te); // }
import myessentials.entities.api.sign.Sign; import myessentials.entities.api.sign.SignType; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntitySign;
package myessentials.test.entities.sign; public class FakeSign extends Sign { public int amountOfClicks = 0; protected FakeSign(int amountOfClicks) { super(FakeSignType.instance); this.amountOfClicks = amountOfClicks; } @Override public void onRightClick(EntityPlayer player) { this.amountOfClicks++; } @Override public void onShiftRightClick(EntityPlayer player) { this.amountOfClicks += 2; } @Override protected String[] getText() { return new String[] { "", "", "", amountOfClicks + "" }; } // REF: Having to create your own SignType does not seem desirable
// Path: src/main/java/myessentials/entities/api/sign/Sign.java // public abstract class Sign { // // public static final String IDENTIFIER = EnumChatFormatting.DARK_BLUE.toString(); // // public final SignType signType; // // protected NBTBase data; // // protected BlockPos bp; // // protected Sign(SignType signType) { // this.signType = signType; // } // // public abstract void onRightClick(EntityPlayer player); // // protected abstract String[] getText(); // // public void onShiftRightClick(EntityPlayer player) { // } // // public TileEntitySign createSignBlock(EntityPlayer player, BlockPos bp, int face) { // World world = MinecraftServer.getServer().worldServerForDimension(bp.getDim()); // ForgeDirection direction = ForgeDirection.getOrientation(face); // if(direction == ForgeDirection.DOWN || face == 1) { // int i1 = MathHelper.floor_double((double) ((player.rotationYaw + 180.0F) * 16.0F / 360.0F) + 0.5D) & 15; // world.setBlock(bp.getX(), bp.getY(), bp.getZ(), Blocks.standing_sign, i1, 3); // } else { // world.setBlock(bp.getX(), bp.getY(), bp.getZ(), Blocks.wall_sign, face, 3); // } // // TileEntitySign te = (TileEntitySign) world.getTileEntity(bp.getX(), bp.getY(), bp.getZ()); // String[] text = Arrays.copyOf(getText(), 4); // text[0] = IDENTIFIER + text[0]; // normalizeText(text); // // for(int i = 0; i < 4; i++) { // te.signText[i] = text[i] == null ? "" : text[i]; // } // // NBTTagCompound rootTag = new NBTTagCompound(); // rootTag.setString("Type", signType.getTypeID()); // if(data != null) // rootTag.setTag("Value", data); // SignClassTransformer.setMyEssentialsDataValue(te, rootTag); // // return te; // } // // public TileEntitySign getTileEntity() { // World world = MinecraftServer.getServer().worldServerForDimension(bp.getDim()); // TileEntity te = world.getTileEntity(bp.getX(), bp.getY(), bp.getZ());; // return te instanceof TileEntitySign ? (TileEntitySign) te : null; // } // // private void normalizeText(String[] text) { // for(int i = 0; i < 4; i++) { // if(text[i].length() > 15) { // text[i] = text[i].substring(0, 15); // } // } // } // // public void deleteSignBlock() { // World world = MinecraftServer.getServer().worldServerForDimension(bp.getDim()); // world.removeTileEntity(bp.getX(), bp.getY(), bp.getZ()); // world.setBlock(bp.getX(), bp.getY(), bp.getZ(), Blocks.air); // } // // public static class Container extends ArrayList<Sign> { // @Override // public boolean add(Sign sign) { // return super.add(sign); // } // // public Sign get(BlockPos bp) { // for(Sign sign : this) { // if(bp.equals(sign.bp)) { // return sign; // } // } // return null; // } // // public boolean contains(BlockPos bp) { // for(Sign sign : this) { // if(bp.equals(sign.bp)) { // return true; // } // } // return false; // } // // public boolean remove(BlockPos bp) { // for(Iterator<Sign> it = iterator(); it.hasNext(); ) { // Sign sign = it.next(); // if(bp.equals(sign.bp)) { // it.remove(); // return true; // } // } // return false; // } // } // } // // Path: src/main/java/myessentials/entities/api/sign/SignType.java // public abstract class SignType { // /** // * The unique ID for this type. // * @return The ID following the syntax: "modId:signType" // */ // public abstract String getTypeID(); // // /** // * Loads a sign data of this type. // * @param tileEntity The tile entity that is being loaded // * @param signData The data stored on the sign // * @return The loaded sign // */ // public abstract Sign loadData(TileEntitySign tileEntity, NBTBase signData); // // /** // * Register this type on the {@link SignManager}, all types must be registered to be recognized. // */ // public void register() { // SignManager.instance.signTypes.put(getTypeID(), this); // } // // public abstract boolean isTileValid(TileEntitySign te); // } // Path: src/test/java/myessentials/test/entities/sign/FakeSign.java import myessentials.entities.api.sign.Sign; import myessentials.entities.api.sign.SignType; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntitySign; package myessentials.test.entities.sign; public class FakeSign extends Sign { public int amountOfClicks = 0; protected FakeSign(int amountOfClicks) { super(FakeSignType.instance); this.amountOfClicks = amountOfClicks; } @Override public void onRightClick(EntityPlayer player) { this.amountOfClicks++; } @Override public void onShiftRightClick(EntityPlayer player) { this.amountOfClicks += 2; } @Override protected String[] getText() { return new String[] { "", "", "", amountOfClicks + "" }; } // REF: Having to create your own SignType does not seem desirable
public static class FakeSignType extends SignType {
MyEssentials/MyEssentials-Core
src/main/java/myessentials/entities/api/sign/Sign.java
// Path: src/main/java/myessentials/entities/api/BlockPos.java // public class BlockPos implements IChatFormat { // private final int dim; // private final int x; // private final int y; // private final int z; // // public BlockPos(int x, int y, int z, int dim) { // this.x = x; // this.y = y; // this.z = z; // this.dim = dim; // } // // public int getDim() { // return dim; // } // // public int getX() { // return x; // } // // public int getY() { // return y; // } // // public int getZ() { // return z; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public boolean equals(Object other) { // if(other instanceof BlockPos) { // BlockPos otherBP = (BlockPos) other; // return otherBP.dim == dim && otherBP.x == x && otherBP.y == y && otherBP.z == z; // } // return super.equals(other); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.blockpos", x, y, z, dim); // } // }
import myessentials.classtransformers.SignClassTransformer; import myessentials.entities.api.BlockPos; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntitySign; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator;
package myessentials.entities.api.sign; /** * A simple wrapper class of a sign block for the server side. */ public abstract class Sign { public static final String IDENTIFIER = EnumChatFormatting.DARK_BLUE.toString(); public final SignType signType; protected NBTBase data;
// Path: src/main/java/myessentials/entities/api/BlockPos.java // public class BlockPos implements IChatFormat { // private final int dim; // private final int x; // private final int y; // private final int z; // // public BlockPos(int x, int y, int z, int dim) { // this.x = x; // this.y = y; // this.z = z; // this.dim = dim; // } // // public int getDim() { // return dim; // } // // public int getX() { // return x; // } // // public int getY() { // return y; // } // // public int getZ() { // return z; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public boolean equals(Object other) { // if(other instanceof BlockPos) { // BlockPos otherBP = (BlockPos) other; // return otherBP.dim == dim && otherBP.x == x && otherBP.y == y && otherBP.z == z; // } // return super.equals(other); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.blockpos", x, y, z, dim); // } // } // Path: src/main/java/myessentials/entities/api/sign/Sign.java import myessentials.classtransformers.SignClassTransformer; import myessentials.entities.api.BlockPos; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntitySign; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; package myessentials.entities.api.sign; /** * A simple wrapper class of a sign block for the server side. */ public abstract class Sign { public static final String IDENTIFIER = EnumChatFormatting.DARK_BLUE.toString(); public final SignType signType; protected NBTBase data;
protected BlockPos bp;
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/json/FakeSerializableObject.java
// Path: src/main/java/myessentials/json/api/SerializerTemplate.java // public abstract class SerializerTemplate<T> implements JsonSerializer<T>, JsonDeserializer<T> { // // public GsonBuilder createBuilder() { // GsonBuilder builder = new GsonBuilder(); // register(builder); // return builder; // } // // public abstract void register(GsonBuilder builder); // }
import com.google.gson.*; import myessentials.json.api.SerializerTemplate; import java.lang.reflect.Type;
package myessentials.test.json; public class FakeSerializableObject { public int x = 0; public int y = 0;
// Path: src/main/java/myessentials/json/api/SerializerTemplate.java // public abstract class SerializerTemplate<T> implements JsonSerializer<T>, JsonDeserializer<T> { // // public GsonBuilder createBuilder() { // GsonBuilder builder = new GsonBuilder(); // register(builder); // return builder; // } // // public abstract void register(GsonBuilder builder); // } // Path: src/test/java/myessentials/test/json/FakeSerializableObject.java import com.google.gson.*; import myessentials.json.api.SerializerTemplate; import java.lang.reflect.Type; package myessentials.test.json; public class FakeSerializableObject { public int x = 0; public int y = 0;
public static class Serializer extends SerializerTemplate<FakeSerializableObject> {
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/entities/ChunkPosTest.java
// Path: src/main/java/myessentials/entities/api/ChunkPos.java // public class ChunkPos implements IChatFormat { // private final int dim; // private final int x; // private final int z; // // public ChunkPos(int dim, int x, int z) { // this.dim = dim; // this.x = x; // this.z = z; // } // // public int getX() { // return x; // } // // public int getZ() { // return z; // } // // public int getDim() { // return dim; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.chunkpos", x, z, dim); // } // // public NBTTagCompound toNBTTagCompound() { // NBTTagCompound tag = new NBTTagCompound(); // tag.setInteger("x", x); // tag.setInteger("z", z); // return tag; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof ChunkPos) { // ChunkPos other = (ChunkPos) obj; // return other.x == x && other.z == z && other.dim == dim; // } else { // return super.equals(obj); // } // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // }
import junit.framework.Assert; import myessentials.entities.api.ChunkPos; import myessentials.test.MECTest; import org.junit.Test;
package myessentials.test.entities; public class ChunkPosTest extends MECTest { @Test public void chunkPosEquality() {
// Path: src/main/java/myessentials/entities/api/ChunkPos.java // public class ChunkPos implements IChatFormat { // private final int dim; // private final int x; // private final int z; // // public ChunkPos(int dim, int x, int z) { // this.dim = dim; // this.x = x; // this.z = z; // } // // public int getX() { // return x; // } // // public int getZ() { // return z; // } // // public int getDim() { // return dim; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.chunkpos", x, z, dim); // } // // public NBTTagCompound toNBTTagCompound() { // NBTTagCompound tag = new NBTTagCompound(); // tag.setInteger("x", x); // tag.setInteger("z", z); // return tag; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof ChunkPos) { // ChunkPos other = (ChunkPos) obj; // return other.x == x && other.z == z && other.dim == dim; // } else { // return super.equals(obj); // } // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // Path: src/test/java/myessentials/test/entities/ChunkPosTest.java import junit.framework.Assert; import myessentials.entities.api.ChunkPos; import myessentials.test.MECTest; import org.junit.Test; package myessentials.test.entities; public class ChunkPosTest extends MECTest { @Test public void chunkPosEquality() {
ChunkPos cp1 = new ChunkPos(1, 1, 0);
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/entities/BlockPosTest.java
// Path: src/main/java/myessentials/entities/api/BlockPos.java // public class BlockPos implements IChatFormat { // private final int dim; // private final int x; // private final int y; // private final int z; // // public BlockPos(int x, int y, int z, int dim) { // this.x = x; // this.y = y; // this.z = z; // this.dim = dim; // } // // public int getDim() { // return dim; // } // // public int getX() { // return x; // } // // public int getY() { // return y; // } // // public int getZ() { // return z; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public boolean equals(Object other) { // if(other instanceof BlockPos) { // BlockPos otherBP = (BlockPos) other; // return otherBP.dim == dim && otherBP.x == x && otherBP.y == y && otherBP.z == z; // } // return super.equals(other); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.blockpos", x, y, z, dim); // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // }
import junit.framework.Assert; import myessentials.entities.api.BlockPos; import myessentials.test.MECTest; import org.junit.Test;
package myessentials.test.entities; public class BlockPosTest extends MECTest { @Test public void blockPosEquality() {
// Path: src/main/java/myessentials/entities/api/BlockPos.java // public class BlockPos implements IChatFormat { // private final int dim; // private final int x; // private final int y; // private final int z; // // public BlockPos(int x, int y, int z, int dim) { // this.x = x; // this.y = y; // this.z = z; // this.dim = dim; // } // // public int getDim() { // return dim; // } // // public int getX() { // return x; // } // // public int getY() { // return y; // } // // public int getZ() { // return z; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public boolean equals(Object other) { // if(other instanceof BlockPos) { // BlockPos otherBP = (BlockPos) other; // return otherBP.dim == dim && otherBP.x == x && otherBP.y == y && otherBP.z == z; // } // return super.equals(other); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.blockpos", x, y, z, dim); // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // Path: src/test/java/myessentials/test/entities/BlockPosTest.java import junit.framework.Assert; import myessentials.entities.api.BlockPos; import myessentials.test.MECTest; import org.junit.Test; package myessentials.test.entities; public class BlockPosTest extends MECTest { @Test public void blockPosEquality() {
BlockPos bp1 = new BlockPos(1, 1, 1, 0);
MyEssentials/MyEssentials-Core
src/main/java/myessentials/entities/api/BlockPos.java
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // } // // Path: src/main/java/myessentials/chat/api/IChatFormat.java // public interface IChatFormat { // // IChatComponent toChatMessage(); // // }
import myessentials.MyEssentialsCore; import myessentials.chat.api.IChatFormat; import net.minecraft.util.IChatComponent;
} public int getX() { return x; } public int getY() { return y; } public int getZ() { return z; } @Override public String toString() { return toChatMessage().getUnformattedText(); } @Override public boolean equals(Object other) { if(other instanceof BlockPos) { BlockPos otherBP = (BlockPos) other; return otherBP.dim == dim && otherBP.x == x && otherBP.y == y && otherBP.z == z; } return super.equals(other); } @Override public IChatComponent toChatMessage() {
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // } // // Path: src/main/java/myessentials/chat/api/IChatFormat.java // public interface IChatFormat { // // IChatComponent toChatMessage(); // // } // Path: src/main/java/myessentials/entities/api/BlockPos.java import myessentials.MyEssentialsCore; import myessentials.chat.api.IChatFormat; import net.minecraft.util.IChatComponent; } public int getX() { return x; } public int getY() { return y; } public int getZ() { return z; } @Override public String toString() { return toChatMessage().getUnformattedText(); } @Override public boolean equals(Object other) { if(other instanceof BlockPos) { BlockPos otherBP = (BlockPos) other; return otherBP.dim == dim && otherBP.x == x && otherBP.y == y && otherBP.z == z; } return super.equals(other); } @Override public IChatComponent toChatMessage() {
return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.blockpos", x, y, z, dim);
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/datasource/FakeSchema.java
// Path: src/main/java/myessentials/datasource/api/Schema.java // public abstract class Schema { // // protected List<DBUpdate> updates = new ArrayList<DBUpdate>(); // // public abstract void initializeUpdates(BridgeSQL bridge); // // public class DBUpdate { // /** // * Formatted mm.dd.yyyy.e where e increments by 1 for every update released on the same date // */ // public final String id; // public final String desc; // public final String statement; // // public DBUpdate(String id, String desc, String statement) { // this.id = id; // this.desc = desc; // this.statement = statement; // } // } // } // // Path: src/main/java/myessentials/datasource/api/bridge/BridgeSQL.java // public abstract class BridgeSQL extends Bridge { // // public String prefix = ""; // public String[] userProperties = {}; // // public BridgeSQL() { // } // // protected Properties properties = new Properties(); // protected String dsn = ""; // protected Connection conn = null; // protected String autoIncrement; // // protected abstract void initConnection(); // // protected abstract void initProperties(); // // public Connection getConnection() { // return this.conn; // } // // public String getAutoIncrement() { // return this.autoIncrement; // } // }
import myessentials.datasource.api.Schema; import myessentials.datasource.api.bridge.BridgeSQL;
package myessentials.test.datasource; public class FakeSchema extends Schema { @Override
// Path: src/main/java/myessentials/datasource/api/Schema.java // public abstract class Schema { // // protected List<DBUpdate> updates = new ArrayList<DBUpdate>(); // // public abstract void initializeUpdates(BridgeSQL bridge); // // public class DBUpdate { // /** // * Formatted mm.dd.yyyy.e where e increments by 1 for every update released on the same date // */ // public final String id; // public final String desc; // public final String statement; // // public DBUpdate(String id, String desc, String statement) { // this.id = id; // this.desc = desc; // this.statement = statement; // } // } // } // // Path: src/main/java/myessentials/datasource/api/bridge/BridgeSQL.java // public abstract class BridgeSQL extends Bridge { // // public String prefix = ""; // public String[] userProperties = {}; // // public BridgeSQL() { // } // // protected Properties properties = new Properties(); // protected String dsn = ""; // protected Connection conn = null; // protected String autoIncrement; // // protected abstract void initConnection(); // // protected abstract void initProperties(); // // public Connection getConnection() { // return this.conn; // } // // public String getAutoIncrement() { // return this.autoIncrement; // } // } // Path: src/test/java/myessentials/test/datasource/FakeSchema.java import myessentials.datasource.api.Schema; import myessentials.datasource.api.bridge.BridgeSQL; package myessentials.test.datasource; public class FakeSchema extends Schema { @Override
public void initializeUpdates(BridgeSQL bridge) {
MyEssentials/MyEssentials-Core
src/main/java/myessentials/utils/ChatUtils.java
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // }
import myessentials.MyEssentialsCore; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatStyle; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; import java.util.HashMap; import java.util.Map;
package myessentials.utils; /** * Useful methods for Chat */ public class ChatUtils { private ChatUtils() { } /** * Maps chat formatting by it's code */ private static final Map<Character, EnumChatFormatting> formattingMap = new HashMap<Character, EnumChatFormatting>(22); static { for(EnumChatFormatting formatting: EnumChatFormatting.values()) { formattingMap.put(formatting.getFormattingCode(), formatting); } } public static void sendChat(ICommandSender sender, IChatComponent message) { sender.addChatMessage(message); } public static void sendChat2(ICommandSender sender, String message, Object... args) { } /** * Sends msg to sender.<br /> * This method will split the message at newline chars (\n) and send each line as a separate message. */ public static void sendChat(ICommandSender sender, String msg, Object... args) { if (sender == null) return; String[] lines; if(args == null) { lines = msg.split("\\\\n"); } else { lines = String.format(msg, args).split("\\\\n"); } try { for (String line : lines) { sender.addChatMessage(chatComponentFromLegacyText(line)); } } catch (Exception ex) {
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // } // Path: src/main/java/myessentials/utils/ChatUtils.java import myessentials.MyEssentialsCore; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatStyle; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; import java.util.HashMap; import java.util.Map; package myessentials.utils; /** * Useful methods for Chat */ public class ChatUtils { private ChatUtils() { } /** * Maps chat formatting by it's code */ private static final Map<Character, EnumChatFormatting> formattingMap = new HashMap<Character, EnumChatFormatting>(22); static { for(EnumChatFormatting formatting: EnumChatFormatting.values()) { formattingMap.put(formatting.getFormattingCode(), formatting); } } public static void sendChat(ICommandSender sender, IChatComponent message) { sender.addChatMessage(message); } public static void sendChat2(ICommandSender sender, String message, Object... args) { } /** * Sends msg to sender.<br /> * This method will split the message at newline chars (\n) and send each line as a separate message. */ public static void sendChat(ICommandSender sender, String msg, Object... args) { if (sender == null) return; String[] lines; if(args == null) { lines = msg.split("\\\\n"); } else { lines = String.format(msg, args).split("\\\\n"); } try { for (String line : lines) { sender.addChatMessage(chatComponentFromLegacyText(line)); } } catch (Exception ex) {
MyEssentialsCore.instance.LOG.error("Failed to send chat message! Message: {}", msg);
MyEssentials/MyEssentials-Core
src/main/java/myessentials/economy/core/vault/BukkitCompat.java
// Path: src/main/java/myessentials/economy/api/IEconManager.java // public interface IEconManager { // // void setPlayer(UUID uuid); // // /** // * Add a set amount to a target's Wallet // */ // void addToWallet(int amountToAdd); // // /** // * Get the amount of money the player has // */ // int getWallet(); // // /** // * Remove a set amount from a target's Wallet // * returns true if it succeded, false if it didn't // */ // boolean removeFromWallet(int amountToSubtract); // // /** // * Set the target's Wallet to the specified amount // */ // void setWallet(int setAmount, EntityPlayer player); // // /** // * Gets the singular or plural term of the currency used // */ // String currency(int amount); // // /** // * Gets a combo of getWallet + currency // */ // String getMoneyString(); // // /** // * Saves all wallets to disk // * (for users still on the server when it's stopping) // */ // void save(); // // Map<String, Integer> getItemTables(); // }
import myessentials.economy.api.IEconManager; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.Server; import org.bukkit.plugin.RegisteredServiceProvider;
package myessentials.economy.core.vault; /** * Everything related to Bukkit, putting this in a separate class since it will crash if server doesn't have bukkit. */ public class BukkitCompat { private BukkitCompat() { }
// Path: src/main/java/myessentials/economy/api/IEconManager.java // public interface IEconManager { // // void setPlayer(UUID uuid); // // /** // * Add a set amount to a target's Wallet // */ // void addToWallet(int amountToAdd); // // /** // * Get the amount of money the player has // */ // int getWallet(); // // /** // * Remove a set amount from a target's Wallet // * returns true if it succeded, false if it didn't // */ // boolean removeFromWallet(int amountToSubtract); // // /** // * Set the target's Wallet to the specified amount // */ // void setWallet(int setAmount, EntityPlayer player); // // /** // * Gets the singular or plural term of the currency used // */ // String currency(int amount); // // /** // * Gets a combo of getWallet + currency // */ // String getMoneyString(); // // /** // * Saves all wallets to disk // * (for users still on the server when it's stopping) // */ // void save(); // // Map<String, Integer> getItemTables(); // } // Path: src/main/java/myessentials/economy/core/vault/BukkitCompat.java import myessentials.economy.api.IEconManager; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.Server; import org.bukkit.plugin.RegisteredServiceProvider; package myessentials.economy.core.vault; /** * Everything related to Bukkit, putting this in a separate class since it will crash if server doesn't have bukkit. */ public class BukkitCompat { private BukkitCompat() { }
public static Class<? extends IEconManager> initEconomy() {
MyEssentials/MyEssentials-Core
src/main/java/myessentials/chat/api/ChatManager.java
// Path: src/main/java/myessentials/localization/api/LocalManager.java // public class LocalManager { // // private static Map<String, Local> localizations = new HashMap<String, Local>(); // // /** // * Registers a localization file to be used globally // * The key string should be the first part of any localization key that is found in the file // */ // public static void register(Local local, String key) { // localizations.put(key, local); // } // // /** // * Finds the localized version that the key is pointing at and sends it to the ICommandSender // */ // public static void send(ICommandSender sender, String localizationKey, Object... args) { // sender.addChatMessage(get(localizationKey, args)); // } // // public static ChatComponentFormatted get(String localizationKey, Object... args) { // Local local = localizations.get(localizationKey.split("\\.")[0]); // return local.getLocalization(localizationKey, args); // } // }
import myessentials.localization.api.LocalManager; import net.minecraft.command.ICommandSender; import net.minecraft.util.IChatComponent; import net.minecraft.entity.player.EntityPlayerMP; import java.util.List;
package myessentials.chat.api; public class ChatManager { /** * Global method for sending localized messages */ public static void send(ICommandSender sender, String localizationKey, Object... args) {
// Path: src/main/java/myessentials/localization/api/LocalManager.java // public class LocalManager { // // private static Map<String, Local> localizations = new HashMap<String, Local>(); // // /** // * Registers a localization file to be used globally // * The key string should be the first part of any localization key that is found in the file // */ // public static void register(Local local, String key) { // localizations.put(key, local); // } // // /** // * Finds the localized version that the key is pointing at and sends it to the ICommandSender // */ // public static void send(ICommandSender sender, String localizationKey, Object... args) { // sender.addChatMessage(get(localizationKey, args)); // } // // public static ChatComponentFormatted get(String localizationKey, Object... args) { // Local local = localizations.get(localizationKey.split("\\.")[0]); // return local.getLocalization(localizationKey, args); // } // } // Path: src/main/java/myessentials/chat/api/ChatManager.java import myessentials.localization.api.LocalManager; import net.minecraft.command.ICommandSender; import net.minecraft.util.IChatComponent; import net.minecraft.entity.player.EntityPlayerMP; import java.util.List; package myessentials.chat.api; public class ChatManager { /** * Global method for sending localized messages */ public static void send(ICommandSender sender, String localizationKey, Object... args) {
send(sender, LocalManager.get(localizationKey, args));
MyEssentials/MyEssentials-Core
src/main/java/myessentials/entities/api/EntityPos.java
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // } // // Path: src/main/java/myessentials/chat/api/IChatFormat.java // public interface IChatFormat { // // IChatComponent toChatMessage(); // // }
import myessentials.MyEssentialsCore; import myessentials.chat.api.IChatFormat; import net.minecraft.util.IChatComponent;
package myessentials.entities.api; /** * Helper class for storing position of an entity */ public class EntityPos implements IChatFormat { private final int dim; private final double x; private final double y; private final double z; public EntityPos(double x, double y, double z, int dim) { this.x = x; this.y = y; this.z = z; this.dim = dim; } public int getDim() { return dim; } public double getX() { return x; } public double getY() { return y; } public double getZ() { return z; } @Override public String toString() { return toChatMessage().getUnformattedText(); } @Override public IChatComponent toChatMessage() {
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // } // // Path: src/main/java/myessentials/chat/api/IChatFormat.java // public interface IChatFormat { // // IChatComponent toChatMessage(); // // } // Path: src/main/java/myessentials/entities/api/EntityPos.java import myessentials.MyEssentialsCore; import myessentials.chat.api.IChatFormat; import net.minecraft.util.IChatComponent; package myessentials.entities.api; /** * Helper class for storing position of an entity */ public class EntityPos implements IChatFormat { private final int dim; private final double x; private final double y; private final double z; public EntityPos(double x, double y, double z, int dim) { this.x = x; this.y = y; this.z = z; this.dim = dim; } public int getDim() { return dim; } public double getX() { return x; } public double getY() { return y; } public double getZ() { return z; } @Override public String toString() { return toChatMessage().getUnformattedText(); } @Override public IChatComponent toChatMessage() {
return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.entitypos", x, y, z, dim);
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/chat/ChatComponentMultiPageTest.java
// Path: src/main/java/myessentials/chat/api/ChatComponentMultiPage.java // public class ChatComponentMultiPage extends ChatComponentContainer { // // private int maxComponentsPerPage = 10; // // public ChatComponentMultiPage(int maxComponentsPerPage) { // this.maxComponentsPerPage = maxComponentsPerPage; // } // // public void sendPage(ICommandSender sender, int page) { // getHeader(page).send(sender); // getPage(page).send(sender); // } // // public ChatComponentContainer getHeader(int page) { // ChatComponentContainer header = new ChatComponentContainer(); // header.add(new ChatComponentFormatted("{9| - MEC MultiPage Message - Page %s/%s}", page, getNumberOfPages())); // // return header; // } // // public ChatComponentContainer getPage(int page) { // ChatComponentContainer result = new ChatComponentContainer(); // result.addAll(this.subList(maxComponentsPerPage * (page - 1), maxComponentsPerPage * page > size() ? size() : maxComponentsPerPage * page)); // return result; // } // // public int getNumberOfPages() { // return (int) Math.ceil((float)size() / (float)maxComponentsPerPage); // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // }
import junit.framework.Assert; import myessentials.chat.api.ChatComponentMultiPage; import myessentials.test.MECTest; import net.minecraft.util.ChatComponentText; import org.junit.Test;
package myessentials.test.chat; public class ChatComponentMultiPageTest extends MECTest { @Test public void shouldCreateComponentProperly() {
// Path: src/main/java/myessentials/chat/api/ChatComponentMultiPage.java // public class ChatComponentMultiPage extends ChatComponentContainer { // // private int maxComponentsPerPage = 10; // // public ChatComponentMultiPage(int maxComponentsPerPage) { // this.maxComponentsPerPage = maxComponentsPerPage; // } // // public void sendPage(ICommandSender sender, int page) { // getHeader(page).send(sender); // getPage(page).send(sender); // } // // public ChatComponentContainer getHeader(int page) { // ChatComponentContainer header = new ChatComponentContainer(); // header.add(new ChatComponentFormatted("{9| - MEC MultiPage Message - Page %s/%s}", page, getNumberOfPages())); // // return header; // } // // public ChatComponentContainer getPage(int page) { // ChatComponentContainer result = new ChatComponentContainer(); // result.addAll(this.subList(maxComponentsPerPage * (page - 1), maxComponentsPerPage * page > size() ? size() : maxComponentsPerPage * page)); // return result; // } // // public int getNumberOfPages() { // return (int) Math.ceil((float)size() / (float)maxComponentsPerPage); // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // Path: src/test/java/myessentials/test/chat/ChatComponentMultiPageTest.java import junit.framework.Assert; import myessentials.chat.api.ChatComponentMultiPage; import myessentials.test.MECTest; import net.minecraft.util.ChatComponentText; import org.junit.Test; package myessentials.test.chat; public class ChatComponentMultiPageTest extends MECTest { @Test public void shouldCreateComponentProperly() {
ChatComponentMultiPage message = new ChatComponentMultiPage(4);
MyEssentials/MyEssentials-Core
src/main/java/myessentials/entities/api/Volume.java
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // } // // Path: src/main/java/myessentials/chat/api/IChatFormat.java // public interface IChatFormat { // // IChatComponent toChatMessage(); // // } // // Path: src/main/java/myessentials/json/api/SerializerTemplate.java // public abstract class SerializerTemplate<T> implements JsonSerializer<T>, JsonDeserializer<T> { // // public GsonBuilder createBuilder() { // GsonBuilder builder = new GsonBuilder(); // register(builder); // return builder; // } // // public abstract void register(GsonBuilder builder); // }
import com.google.gson.*; import myessentials.MyEssentialsCore; import myessentials.chat.api.IChatFormat; import myessentials.json.api.SerializerTemplate; import net.minecraft.util.IChatComponent; import net.minecraftforge.common.util.ForgeDirection; import java.lang.reflect.Type;
z1 = (minZ < other.getMinZ()) ? other.getMinZ() : minZ; x2 = (maxX > other.getMaxX()) ? other.getMaxX() : maxX; y2 = (maxY > other.getMaxY()) ? other.getMaxY() : maxY; z2= (maxZ > other.getMaxZ()) ? other.getMaxZ() : maxZ; return new Volume(x1, y1, z1, x2, y2, z2); } return null; } public int getVolumeAmount() { return (maxX - minX + 1) * (maxY - minY + 1) * (maxZ - minZ + 1); } @Override public boolean equals(Object obj) { if(obj instanceof Volume) { Volume other = (Volume)obj; return other.minX == minX && other.minY == minY && other.minZ == minZ && other.maxX == maxX && other.maxY == maxY && other.maxZ == maxZ; } return super.equals(obj); } @Override public String toString() { return toChatMessage().getUnformattedText(); } @Override public IChatComponent toChatMessage() {
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // } // // Path: src/main/java/myessentials/chat/api/IChatFormat.java // public interface IChatFormat { // // IChatComponent toChatMessage(); // // } // // Path: src/main/java/myessentials/json/api/SerializerTemplate.java // public abstract class SerializerTemplate<T> implements JsonSerializer<T>, JsonDeserializer<T> { // // public GsonBuilder createBuilder() { // GsonBuilder builder = new GsonBuilder(); // register(builder); // return builder; // } // // public abstract void register(GsonBuilder builder); // } // Path: src/main/java/myessentials/entities/api/Volume.java import com.google.gson.*; import myessentials.MyEssentialsCore; import myessentials.chat.api.IChatFormat; import myessentials.json.api.SerializerTemplate; import net.minecraft.util.IChatComponent; import net.minecraftforge.common.util.ForgeDirection; import java.lang.reflect.Type; z1 = (minZ < other.getMinZ()) ? other.getMinZ() : minZ; x2 = (maxX > other.getMaxX()) ? other.getMaxX() : maxX; y2 = (maxY > other.getMaxY()) ? other.getMaxY() : maxY; z2= (maxZ > other.getMaxZ()) ? other.getMaxZ() : maxZ; return new Volume(x1, y1, z1, x2, y2, z2); } return null; } public int getVolumeAmount() { return (maxX - minX + 1) * (maxY - minY + 1) * (maxZ - minZ + 1); } @Override public boolean equals(Object obj) { if(obj instanceof Volume) { Volume other = (Volume)obj; return other.minX == minX && other.minY == minY && other.minZ == minZ && other.maxX == maxX && other.maxY == maxY && other.maxZ == maxZ; } return super.equals(obj); } @Override public String toString() { return toChatMessage().getUnformattedText(); } @Override public IChatComponent toChatMessage() {
return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.volume", minX, minY, minZ, maxX, maxY, maxZ);
MyEssentials/MyEssentials-Core
src/main/java/myessentials/entities/api/Volume.java
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // } // // Path: src/main/java/myessentials/chat/api/IChatFormat.java // public interface IChatFormat { // // IChatComponent toChatMessage(); // // } // // Path: src/main/java/myessentials/json/api/SerializerTemplate.java // public abstract class SerializerTemplate<T> implements JsonSerializer<T>, JsonDeserializer<T> { // // public GsonBuilder createBuilder() { // GsonBuilder builder = new GsonBuilder(); // register(builder); // return builder; // } // // public abstract void register(GsonBuilder builder); // }
import com.google.gson.*; import myessentials.MyEssentialsCore; import myessentials.chat.api.IChatFormat; import myessentials.json.api.SerializerTemplate; import net.minecraft.util.IChatComponent; import net.minecraftforge.common.util.ForgeDirection; import java.lang.reflect.Type;
z2= (maxZ > other.getMaxZ()) ? other.getMaxZ() : maxZ; return new Volume(x1, y1, z1, x2, y2, z2); } return null; } public int getVolumeAmount() { return (maxX - minX + 1) * (maxY - minY + 1) * (maxZ - minZ + 1); } @Override public boolean equals(Object obj) { if(obj instanceof Volume) { Volume other = (Volume)obj; return other.minX == minX && other.minY == minY && other.minZ == minZ && other.maxX == maxX && other.maxY == maxY && other.maxZ == maxZ; } return super.equals(obj); } @Override public String toString() { return toChatMessage().getUnformattedText(); } @Override public IChatComponent toChatMessage() { return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.volume", minX, minY, minZ, maxX, maxY, maxZ); }
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // } // // Path: src/main/java/myessentials/chat/api/IChatFormat.java // public interface IChatFormat { // // IChatComponent toChatMessage(); // // } // // Path: src/main/java/myessentials/json/api/SerializerTemplate.java // public abstract class SerializerTemplate<T> implements JsonSerializer<T>, JsonDeserializer<T> { // // public GsonBuilder createBuilder() { // GsonBuilder builder = new GsonBuilder(); // register(builder); // return builder; // } // // public abstract void register(GsonBuilder builder); // } // Path: src/main/java/myessentials/entities/api/Volume.java import com.google.gson.*; import myessentials.MyEssentialsCore; import myessentials.chat.api.IChatFormat; import myessentials.json.api.SerializerTemplate; import net.minecraft.util.IChatComponent; import net.minecraftforge.common.util.ForgeDirection; import java.lang.reflect.Type; z2= (maxZ > other.getMaxZ()) ? other.getMaxZ() : maxZ; return new Volume(x1, y1, z1, x2, y2, z2); } return null; } public int getVolumeAmount() { return (maxX - minX + 1) * (maxY - minY + 1) * (maxZ - minZ + 1); } @Override public boolean equals(Object obj) { if(obj instanceof Volume) { Volume other = (Volume)obj; return other.minX == minX && other.minY == minY && other.minZ == minZ && other.maxX == maxX && other.maxY == maxY && other.maxZ == maxZ; } return super.equals(obj); } @Override public String toString() { return toChatMessage().getUnformattedText(); } @Override public IChatComponent toChatMessage() { return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.volume", minX, minY, minZ, maxX, maxY, maxZ); }
public static class Serializer extends SerializerTemplate<Volume> {
MyEssentials/MyEssentials-Core
src/main/java/myessentials/entities/api/ChunkPos.java
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // } // // Path: src/main/java/myessentials/chat/api/IChatFormat.java // public interface IChatFormat { // // IChatComponent toChatMessage(); // // }
import myessentials.MyEssentialsCore; import myessentials.chat.api.IChatFormat; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.IChatComponent;
package myessentials.entities.api; /** * Helper class for storing position of a chunk */ public class ChunkPos implements IChatFormat { private final int dim; private final int x; private final int z; public ChunkPos(int dim, int x, int z) { this.dim = dim; this.x = x; this.z = z; } public int getX() { return x; } public int getZ() { return z; } public int getDim() { return dim; } @Override public String toString() { return toChatMessage().getUnformattedText(); } @Override public IChatComponent toChatMessage() {
// Path: src/main/java/myessentials/MyEssentialsCore.java // @Mod(modid = "MyEssentials-Core", name = "MyEssentials-Core", version = "@VERSION@", dependencies = "required-after:Forge", acceptableRemoteVersions = "*") // public class MyEssentialsCore { // @Instance("MyEssentials-Core") // public static MyEssentialsCore instance; // // public Local LOCAL; // public Logger LOG; // // @EventHandler // public void preInit(FMLPreInitializationEvent ev) { // // LOG = ev.getModLog(); // Constants.CONFIG_FOLDER = ev.getModConfigurationDirectory().getPath() + "/MyEssentials-Core/"; // Constants.DATABASE_FOLDER = ev.getModConfigurationDirectory().getParent() + "/databases/"; // // Load Configs // Config.instance.init(Constants.CONFIG_FOLDER + "/Core.cfg", "MyEssentials-Core"); // // REF: The localization can simply take the whole config instance to get the localization needed. // LOCAL = new Local(Constants.CONFIG_FOLDER + "/localization/", Config.instance.localization.get(), "/myessentials/localization/", MyEssentialsCore.class); // LocalManager.register(LOCAL, "myessentials"); // // // Register handlers/trackers // FMLCommonHandler.instance().bus().register(PlayerTracker.instance); // MinecraftForge.EVENT_BUS.register(PlayerTracker.instance); // // FMLCommonHandler.instance().bus().register(ToolManager.instance); // MinecraftForge.EVENT_BUS.register(ToolManager.instance); // // FMLCommonHandler.instance().bus().register(SignManager.instance); // MinecraftForge.EVENT_BUS.register(SignManager.instance); // } // } // // Path: src/main/java/myessentials/chat/api/IChatFormat.java // public interface IChatFormat { // // IChatComponent toChatMessage(); // // } // Path: src/main/java/myessentials/entities/api/ChunkPos.java import myessentials.MyEssentialsCore; import myessentials.chat.api.IChatFormat; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.IChatComponent; package myessentials.entities.api; /** * Helper class for storing position of a chunk */ public class ChunkPos implements IChatFormat { private final int dim; private final int x; private final int z; public ChunkPos(int dim, int x, int z) { this.dim = dim; this.x = x; this.z = z; } public int getX() { return x; } public int getZ() { return z; } public int getDim() { return dim; } @Override public String toString() { return toChatMessage().getUnformattedText(); } @Override public IChatComponent toChatMessage() {
return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.chunkpos", x, z, dim);
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/entities/tool/ToolTest.java
// Path: src/main/java/myessentials/entities/api/tool/ToolManager.java // public class ToolManager { // // public static final ToolManager instance = new ToolManager(); // // private final List<Tool> tools = new ArrayList<Tool>(); // // public boolean register(Tool tool) { // for(Tool t : tools) { // if(t.owner == tool.owner && t.getItemStack() != null) { // t.owner.addChatMessage(new ChatComponentText("You already have a tool!")); // return false; // } // } // // tools.add(tool); // tool.giveItemStack(); // return true; // } // // public Tool get(EntityPlayer owner) { // for(Tool tool : tools) { // if(tool.owner == owner) { // return tool; // } // } // return null; // } // // public void remove(Tool tool) { // tools.remove(tool); // PlayerUtils.takeItemFromPlayer(tool.owner, tool.getItemStack(), 1); // } // // @SubscribeEvent // public void onPlayerInteract(PlayerInteractEvent ev) { // if(!(ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_AIR || ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK)) { // return; // } // // ItemStack currentStack = ev.entityPlayer.inventory.getCurrentItem(); // if(currentStack == null) { // return; // } // // for(Iterator<Tool> it = tools.iterator(); it.hasNext(); ) { // Tool tool = it.next(); // if(tool.owner == null) { // it.remove(); // continue; // } // // if(ev.entityPlayer == tool.owner && tool.getItemStack() == currentStack) { // if (ev.entityPlayer.isSneaking() && ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_AIR) { // tool.onShiftRightClick(); // return; // } else if (ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK) { // tool.onItemUse(new BlockPos(ev.x, ev.y, ev.z, ev.world.provider.dimensionId), ev.face); // return; // } // } // } // } // // @SubscribeEvent // public void onUseHoe(UseHoeEvent ev) { // for(Tool tool : tools) { // if (ev.current == tool.getItemStack()) { // ev.setCanceled(true); // return; // } // } // } // // @SubscribeEvent // public void onPlayerLogout(PlayerEvent.PlayerLoggedOutEvent ev) { // for(int i = 0; i < ev.player.inventory.getSizeInventory(); i++) { // ItemStack stack = ev.player.inventory.getStackInSlot(i); // if(stack == null || !stack.getDisplayName().startsWith(Tool.IDENTIFIER)) { // continue; // } // // PlayerUtils.takeItemFromPlayer(ev.player, stack, 1); // } // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // }
import junit.framework.Assert; import metest.api.TestPlayer; import myessentials.entities.api.tool.ToolManager; import myessentials.test.MECTest; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import org.junit.Before; import org.junit.Test;
package myessentials.test.entities.tool; public class ToolTest extends MECTest { private EntityPlayerMP player; @Before public void initTool() { player = new TestPlayer(server, "Tool Tester"); server.worldServerForDimension(0).setBlock(21, 200, 21, Blocks.stone); } private FakeTool createTool() { player.inventory.dropAllItems(); FakeTool tool = new FakeTool(player); // FakePlayer problems try { // REF: Method ToolManager.register is calling giveItemStack which should not
// Path: src/main/java/myessentials/entities/api/tool/ToolManager.java // public class ToolManager { // // public static final ToolManager instance = new ToolManager(); // // private final List<Tool> tools = new ArrayList<Tool>(); // // public boolean register(Tool tool) { // for(Tool t : tools) { // if(t.owner == tool.owner && t.getItemStack() != null) { // t.owner.addChatMessage(new ChatComponentText("You already have a tool!")); // return false; // } // } // // tools.add(tool); // tool.giveItemStack(); // return true; // } // // public Tool get(EntityPlayer owner) { // for(Tool tool : tools) { // if(tool.owner == owner) { // return tool; // } // } // return null; // } // // public void remove(Tool tool) { // tools.remove(tool); // PlayerUtils.takeItemFromPlayer(tool.owner, tool.getItemStack(), 1); // } // // @SubscribeEvent // public void onPlayerInteract(PlayerInteractEvent ev) { // if(!(ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_AIR || ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK)) { // return; // } // // ItemStack currentStack = ev.entityPlayer.inventory.getCurrentItem(); // if(currentStack == null) { // return; // } // // for(Iterator<Tool> it = tools.iterator(); it.hasNext(); ) { // Tool tool = it.next(); // if(tool.owner == null) { // it.remove(); // continue; // } // // if(ev.entityPlayer == tool.owner && tool.getItemStack() == currentStack) { // if (ev.entityPlayer.isSneaking() && ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_AIR) { // tool.onShiftRightClick(); // return; // } else if (ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK) { // tool.onItemUse(new BlockPos(ev.x, ev.y, ev.z, ev.world.provider.dimensionId), ev.face); // return; // } // } // } // } // // @SubscribeEvent // public void onUseHoe(UseHoeEvent ev) { // for(Tool tool : tools) { // if (ev.current == tool.getItemStack()) { // ev.setCanceled(true); // return; // } // } // } // // @SubscribeEvent // public void onPlayerLogout(PlayerEvent.PlayerLoggedOutEvent ev) { // for(int i = 0; i < ev.player.inventory.getSizeInventory(); i++) { // ItemStack stack = ev.player.inventory.getStackInSlot(i); // if(stack == null || !stack.getDisplayName().startsWith(Tool.IDENTIFIER)) { // continue; // } // // PlayerUtils.takeItemFromPlayer(ev.player, stack, 1); // } // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // Path: src/test/java/myessentials/test/entities/tool/ToolTest.java import junit.framework.Assert; import metest.api.TestPlayer; import myessentials.entities.api.tool.ToolManager; import myessentials.test.MECTest; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import org.junit.Before; import org.junit.Test; package myessentials.test.entities.tool; public class ToolTest extends MECTest { private EntityPlayerMP player; @Before public void initTool() { player = new TestPlayer(server, "Tool Tester"); server.worldServerForDimension(0).setBlock(21, 200, 21, Blocks.stone); } private FakeTool createTool() { player.inventory.dropAllItems(); FakeTool tool = new FakeTool(player); // FakePlayer problems try { // REF: Method ToolManager.register is calling giveItemStack which should not
ToolManager.instance.register(tool);
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/utils/ItemUtilsTest.java
// Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // // Path: src/main/java/myessentials/utils/ItemUtils.java // public class ItemUtils { // // private ItemUtils() { // // } // // /** // * Returns the item from a String that has this pattern: (modid):(unique_name)[:meta] // */ // public static Item itemFromName(String itemName) { // String[] split = itemName.split(":"); // return GameRegistry.findItem(split[0], split[1]); // } // // /** // * Returns the ItemStack from a String that has this pattern: (modid):(unique_name)[:meta] // */ // public static ItemStack itemStackFromName(String itemName) { // String[] split = itemName.split(":"); // // Item item = GameRegistry.findItem(split[0], split[1]); // if (item == null) { // return null; // } // // return new ItemStack(item, 1, split.length > 2 ? Integer.parseInt(split[2]) : 0); // } // // /** // * Returns the unique identifier of given ItemStack // */ // public static String nameFromItemStack(ItemStack itemStack) { // String name = GameRegistry.findUniqueIdentifierFor(itemStack.getItem()).toString(); // if(itemStack.getItemDamage() != 0) // name += ":" + itemStack.getItemDamage(); // return name; // } // }
import cpw.mods.fml.common.registry.GameRegistry; import junit.framework.Assert; import myessentials.test.MECTest; import myessentials.utils.ItemUtils; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import org.junit.Test;
package myessentials.test.utils; public class ItemUtilsTest extends MECTest { @Test public void shouldGetItemFromName() {
// Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // // Path: src/main/java/myessentials/utils/ItemUtils.java // public class ItemUtils { // // private ItemUtils() { // // } // // /** // * Returns the item from a String that has this pattern: (modid):(unique_name)[:meta] // */ // public static Item itemFromName(String itemName) { // String[] split = itemName.split(":"); // return GameRegistry.findItem(split[0], split[1]); // } // // /** // * Returns the ItemStack from a String that has this pattern: (modid):(unique_name)[:meta] // */ // public static ItemStack itemStackFromName(String itemName) { // String[] split = itemName.split(":"); // // Item item = GameRegistry.findItem(split[0], split[1]); // if (item == null) { // return null; // } // // return new ItemStack(item, 1, split.length > 2 ? Integer.parseInt(split[2]) : 0); // } // // /** // * Returns the unique identifier of given ItemStack // */ // public static String nameFromItemStack(ItemStack itemStack) { // String name = GameRegistry.findUniqueIdentifierFor(itemStack.getItem()).toString(); // if(itemStack.getItemDamage() != 0) // name += ":" + itemStack.getItemDamage(); // return name; // } // } // Path: src/test/java/myessentials/test/utils/ItemUtilsTest.java import cpw.mods.fml.common.registry.GameRegistry; import junit.framework.Assert; import myessentials.test.MECTest; import myessentials.utils.ItemUtils; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import org.junit.Test; package myessentials.test.utils; public class ItemUtilsTest extends MECTest { @Test public void shouldGetItemFromName() {
Assert.assertEquals("Item should exist in the current registry", Items.bow, ItemUtils.itemFromName("minecraft:bow"));
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/utils/ClassUtilsTest.java
// Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // // Path: src/main/java/myessentials/utils/ClassUtils.java // public class ClassUtils { // // private ClassUtils() { // } // // /** // * Searches for the class using the path. Example: "net.minecraft.block.Block" // */ // public static boolean isClassLoaded(String classPath) { // boolean value; // try { // value = Class.forName(classPath) != null; // } catch (ClassNotFoundException ex) { // value = false; // } // return value; // } // // public static boolean isBukkitLoaded() { // return MinecraftServer.getServer().getServerModName().contains("cauldron") || MinecraftServer.getServer().getServerModName().contains("mcpc"); // } // // public static Collection<Class<?>> getAllInterfaces(Class<?> cls) { // Set<Class<?>> interfaces = new HashSet<Class<?>>(); // // interfaces.addAll(Arrays.asList(cls.getInterfaces())); // // Class<?> s = cls.getSuperclass(); // if (s != null) { // interfaces.addAll(getAllInterfaces(s)); // } // // return interfaces; // } // }
import junit.framework.Assert; import myessentials.test.MECTest; import myessentials.utils.ClassUtils; import org.junit.Test;
package myessentials.test.utils; public class ClassUtilsTest extends MECTest { @Test public void shouldVerifyIfClassIsLoaded() {
// Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // // Path: src/main/java/myessentials/utils/ClassUtils.java // public class ClassUtils { // // private ClassUtils() { // } // // /** // * Searches for the class using the path. Example: "net.minecraft.block.Block" // */ // public static boolean isClassLoaded(String classPath) { // boolean value; // try { // value = Class.forName(classPath) != null; // } catch (ClassNotFoundException ex) { // value = false; // } // return value; // } // // public static boolean isBukkitLoaded() { // return MinecraftServer.getServer().getServerModName().contains("cauldron") || MinecraftServer.getServer().getServerModName().contains("mcpc"); // } // // public static Collection<Class<?>> getAllInterfaces(Class<?> cls) { // Set<Class<?>> interfaces = new HashSet<Class<?>>(); // // interfaces.addAll(Arrays.asList(cls.getInterfaces())); // // Class<?> s = cls.getSuperclass(); // if (s != null) { // interfaces.addAll(getAllInterfaces(s)); // } // // return interfaces; // } // } // Path: src/test/java/myessentials/test/utils/ClassUtilsTest.java import junit.framework.Assert; import myessentials.test.MECTest; import myessentials.utils.ClassUtils; import org.junit.Test; package myessentials.test.utils; public class ClassUtilsTest extends MECTest { @Test public void shouldVerifyIfClassIsLoaded() {
Assert.assertTrue("Method did not detect that a loaded class is loaded", ClassUtils.isClassLoaded("net.minecraft.block.Block"));
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/utils/WorldUtilsTest.java
// Path: src/main/java/myessentials/entities/api/ChunkPos.java // public class ChunkPos implements IChatFormat { // private final int dim; // private final int x; // private final int z; // // public ChunkPos(int dim, int x, int z) { // this.dim = dim; // this.x = x; // this.z = z; // } // // public int getX() { // return x; // } // // public int getZ() { // return z; // } // // public int getDim() { // return dim; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.chunkpos", x, z, dim); // } // // public NBTTagCompound toNBTTagCompound() { // NBTTagCompound tag = new NBTTagCompound(); // tag.setInteger("x", x); // tag.setInteger("z", z); // return tag; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof ChunkPos) { // ChunkPos other = (ChunkPos) obj; // return other.x == x && other.z == z && other.dim == dim; // } else { // return super.equals(obj); // } // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // // Path: src/main/java/myessentials/utils/WorldUtils.java // public class WorldUtils { // // private WorldUtils() { // } // // /** // * Transforms a box made out of actual coordinates to a list of all the chunks that this box is in // */ // public static List<ChunkPos> getChunksInBox(int dim, int minX, int minZ, int maxX, int maxZ) { // List<ChunkPos> list = new ArrayList<ChunkPos>(); // for (int i = minX >> 4; i <= maxX >> 4; i++) { // for (int j = minZ >> 4; j <= maxZ >> 4; j++) { // list.add(new ChunkPos(dim, i, j)); // } // } // return list; // } // // /** // * Drops the specified itemstack in the worls as an EntityItem // */ // public static void dropAsEntity(World world, int x, int y, int z, ItemStack itemStack) { // if (itemStack == null) { // return; // } // double f = 0.7D; // double dx = world.rand.nextFloat() * f + (1.0D - f) * 0.5D; // double dy = world.rand.nextFloat() * f + (1.0D - f) * 0.5D; // double dz = world.rand.nextFloat() * f + (1.0D - f) * 0.5D; // // EntityItem entityItem = new EntityItem(world, x + dx, y + dy, z + dz, itemStack); // world.spawnEntityInWorld(entityItem); // } // // /** // * Returns the first block from top to bottom that is considered not opaque // */ // public static int getMaxHeightWithSolid(int dim, int x, int z) { // World world = MinecraftServer.getServer().worldServerForDimension(dim); // int y = world.getActualHeight(); // while(!world.getBlock(x, y, z).getMaterial().isOpaque() && y > 0) // y--; // return y; // } // }
import myessentials.entities.api.ChunkPos; import myessentials.test.MECTest; import myessentials.utils.WorldUtils; import net.minecraft.init.Blocks; import net.minecraft.world.World; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List;
package myessentials.test.utils; public class WorldUtilsTest extends MECTest { @Test public void shouldTransformWorldCoordsIntoChunkCoords() {
// Path: src/main/java/myessentials/entities/api/ChunkPos.java // public class ChunkPos implements IChatFormat { // private final int dim; // private final int x; // private final int z; // // public ChunkPos(int dim, int x, int z) { // this.dim = dim; // this.x = x; // this.z = z; // } // // public int getX() { // return x; // } // // public int getZ() { // return z; // } // // public int getDim() { // return dim; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.chunkpos", x, z, dim); // } // // public NBTTagCompound toNBTTagCompound() { // NBTTagCompound tag = new NBTTagCompound(); // tag.setInteger("x", x); // tag.setInteger("z", z); // return tag; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof ChunkPos) { // ChunkPos other = (ChunkPos) obj; // return other.x == x && other.z == z && other.dim == dim; // } else { // return super.equals(obj); // } // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // // Path: src/main/java/myessentials/utils/WorldUtils.java // public class WorldUtils { // // private WorldUtils() { // } // // /** // * Transforms a box made out of actual coordinates to a list of all the chunks that this box is in // */ // public static List<ChunkPos> getChunksInBox(int dim, int minX, int minZ, int maxX, int maxZ) { // List<ChunkPos> list = new ArrayList<ChunkPos>(); // for (int i = minX >> 4; i <= maxX >> 4; i++) { // for (int j = minZ >> 4; j <= maxZ >> 4; j++) { // list.add(new ChunkPos(dim, i, j)); // } // } // return list; // } // // /** // * Drops the specified itemstack in the worls as an EntityItem // */ // public static void dropAsEntity(World world, int x, int y, int z, ItemStack itemStack) { // if (itemStack == null) { // return; // } // double f = 0.7D; // double dx = world.rand.nextFloat() * f + (1.0D - f) * 0.5D; // double dy = world.rand.nextFloat() * f + (1.0D - f) * 0.5D; // double dz = world.rand.nextFloat() * f + (1.0D - f) * 0.5D; // // EntityItem entityItem = new EntityItem(world, x + dx, y + dy, z + dz, itemStack); // world.spawnEntityInWorld(entityItem); // } // // /** // * Returns the first block from top to bottom that is considered not opaque // */ // public static int getMaxHeightWithSolid(int dim, int x, int z) { // World world = MinecraftServer.getServer().worldServerForDimension(dim); // int y = world.getActualHeight(); // while(!world.getBlock(x, y, z).getMaterial().isOpaque() && y > 0) // y--; // return y; // } // } // Path: src/test/java/myessentials/test/utils/WorldUtilsTest.java import myessentials.entities.api.ChunkPos; import myessentials.test.MECTest; import myessentials.utils.WorldUtils; import net.minecraft.init.Blocks; import net.minecraft.world.World; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; package myessentials.test.utils; public class WorldUtilsTest extends MECTest { @Test public void shouldTransformWorldCoordsIntoChunkCoords() {
List<ChunkPos> expectedValues = new ArrayList<ChunkPos>();
MyEssentials/MyEssentials-Core
src/test/java/myessentials/test/utils/WorldUtilsTest.java
// Path: src/main/java/myessentials/entities/api/ChunkPos.java // public class ChunkPos implements IChatFormat { // private final int dim; // private final int x; // private final int z; // // public ChunkPos(int dim, int x, int z) { // this.dim = dim; // this.x = x; // this.z = z; // } // // public int getX() { // return x; // } // // public int getZ() { // return z; // } // // public int getDim() { // return dim; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.chunkpos", x, z, dim); // } // // public NBTTagCompound toNBTTagCompound() { // NBTTagCompound tag = new NBTTagCompound(); // tag.setInteger("x", x); // tag.setInteger("z", z); // return tag; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof ChunkPos) { // ChunkPos other = (ChunkPos) obj; // return other.x == x && other.z == z && other.dim == dim; // } else { // return super.equals(obj); // } // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // // Path: src/main/java/myessentials/utils/WorldUtils.java // public class WorldUtils { // // private WorldUtils() { // } // // /** // * Transforms a box made out of actual coordinates to a list of all the chunks that this box is in // */ // public static List<ChunkPos> getChunksInBox(int dim, int minX, int minZ, int maxX, int maxZ) { // List<ChunkPos> list = new ArrayList<ChunkPos>(); // for (int i = minX >> 4; i <= maxX >> 4; i++) { // for (int j = minZ >> 4; j <= maxZ >> 4; j++) { // list.add(new ChunkPos(dim, i, j)); // } // } // return list; // } // // /** // * Drops the specified itemstack in the worls as an EntityItem // */ // public static void dropAsEntity(World world, int x, int y, int z, ItemStack itemStack) { // if (itemStack == null) { // return; // } // double f = 0.7D; // double dx = world.rand.nextFloat() * f + (1.0D - f) * 0.5D; // double dy = world.rand.nextFloat() * f + (1.0D - f) * 0.5D; // double dz = world.rand.nextFloat() * f + (1.0D - f) * 0.5D; // // EntityItem entityItem = new EntityItem(world, x + dx, y + dy, z + dz, itemStack); // world.spawnEntityInWorld(entityItem); // } // // /** // * Returns the first block from top to bottom that is considered not opaque // */ // public static int getMaxHeightWithSolid(int dim, int x, int z) { // World world = MinecraftServer.getServer().worldServerForDimension(dim); // int y = world.getActualHeight(); // while(!world.getBlock(x, y, z).getMaterial().isOpaque() && y > 0) // y--; // return y; // } // }
import myessentials.entities.api.ChunkPos; import myessentials.test.MECTest; import myessentials.utils.WorldUtils; import net.minecraft.init.Blocks; import net.minecraft.world.World; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List;
package myessentials.test.utils; public class WorldUtilsTest extends MECTest { @Test public void shouldTransformWorldCoordsIntoChunkCoords() { List<ChunkPos> expectedValues = new ArrayList<ChunkPos>(); expectedValues.add(new ChunkPos(0, 0, 0)); expectedValues.add(new ChunkPos(0, 0, 1)); expectedValues.add(new ChunkPos(0, 0, 2)); expectedValues.add(new ChunkPos(0, 0, 3)); expectedValues.add(new ChunkPos(0, 0, 4));
// Path: src/main/java/myessentials/entities/api/ChunkPos.java // public class ChunkPos implements IChatFormat { // private final int dim; // private final int x; // private final int z; // // public ChunkPos(int dim, int x, int z) { // this.dim = dim; // this.x = x; // this.z = z; // } // // public int getX() { // return x; // } // // public int getZ() { // return z; // } // // public int getDim() { // return dim; // } // // @Override // public String toString() { // return toChatMessage().getUnformattedText(); // } // // @Override // public IChatComponent toChatMessage() { // return MyEssentialsCore.instance.LOCAL.getLocalization("myessentials.format.chunkpos", x, z, dim); // } // // public NBTTagCompound toNBTTagCompound() { // NBTTagCompound tag = new NBTTagCompound(); // tag.setInteger("x", x); // tag.setInteger("z", z); // return tag; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof ChunkPos) { // ChunkPos other = (ChunkPos) obj; // return other.x == x && other.z == z && other.dim == dim; // } else { // return super.equals(obj); // } // } // } // // Path: src/test/java/myessentials/test/MECTest.java // public class MECTest extends BaseTest { // // @Before // public void initConfig() { // TestConfig.instance.init(configFile, Constants.MOD_ID); // } // // } // // Path: src/main/java/myessentials/utils/WorldUtils.java // public class WorldUtils { // // private WorldUtils() { // } // // /** // * Transforms a box made out of actual coordinates to a list of all the chunks that this box is in // */ // public static List<ChunkPos> getChunksInBox(int dim, int minX, int minZ, int maxX, int maxZ) { // List<ChunkPos> list = new ArrayList<ChunkPos>(); // for (int i = minX >> 4; i <= maxX >> 4; i++) { // for (int j = minZ >> 4; j <= maxZ >> 4; j++) { // list.add(new ChunkPos(dim, i, j)); // } // } // return list; // } // // /** // * Drops the specified itemstack in the worls as an EntityItem // */ // public static void dropAsEntity(World world, int x, int y, int z, ItemStack itemStack) { // if (itemStack == null) { // return; // } // double f = 0.7D; // double dx = world.rand.nextFloat() * f + (1.0D - f) * 0.5D; // double dy = world.rand.nextFloat() * f + (1.0D - f) * 0.5D; // double dz = world.rand.nextFloat() * f + (1.0D - f) * 0.5D; // // EntityItem entityItem = new EntityItem(world, x + dx, y + dy, z + dz, itemStack); // world.spawnEntityInWorld(entityItem); // } // // /** // * Returns the first block from top to bottom that is considered not opaque // */ // public static int getMaxHeightWithSolid(int dim, int x, int z) { // World world = MinecraftServer.getServer().worldServerForDimension(dim); // int y = world.getActualHeight(); // while(!world.getBlock(x, y, z).getMaterial().isOpaque() && y > 0) // y--; // return y; // } // } // Path: src/test/java/myessentials/test/utils/WorldUtilsTest.java import myessentials.entities.api.ChunkPos; import myessentials.test.MECTest; import myessentials.utils.WorldUtils; import net.minecraft.init.Blocks; import net.minecraft.world.World; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; package myessentials.test.utils; public class WorldUtilsTest extends MECTest { @Test public void shouldTransformWorldCoordsIntoChunkCoords() { List<ChunkPos> expectedValues = new ArrayList<ChunkPos>(); expectedValues.add(new ChunkPos(0, 0, 0)); expectedValues.add(new ChunkPos(0, 0, 1)); expectedValues.add(new ChunkPos(0, 0, 2)); expectedValues.add(new ChunkPos(0, 0, 3)); expectedValues.add(new ChunkPos(0, 0, 4));
List<ChunkPos> chunks = WorldUtils.getChunksInBox(0, 10, 10, 10, 64);
hello/android-buruberi
buruberi-core/src/test/java/is/hello/buruberi/util/SerialQueueTests.java
// Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public class AssertExtensions { // /** // * Checks that a given {@link ThrowingRunnable} throws an exception, calling fail if it does not. // * @param runnable The runnable that should throw an exception. Required. // */ // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // } // // /** // * Variant of the Runnable interface that throws a generic checked exception. // */ // public interface ThrowingRunnable { // void run() throws Exception; // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/BuruberiTestCase.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(constants = BuildConfig.class, // sdk = 21, // shadows = { // ShadowBluetoothManager.class, // ShadowBluetoothAdapterExt.class, // ShadowBluetoothLeScanner.class, // ShadowBluetoothGatt.class, // ShadowBluetoothDeviceExt.class, // }) // public abstract class BuruberiTestCase { // protected BuruberiTestCase() { // final Context baseContext = RuntimeEnvironment.application.getBaseContext(); // BuruberiShadows.setUpSystemServices(baseContext); // } // // @Before // public void setUp() { // ShadowBluetoothAdapterExt shadowBluetoothAdapter = getShadowBluetoothAdapter(); // shadowBluetoothAdapter.setState(BluetoothAdapter.STATE_ON); // shadowBluetoothAdapter.setEnabled(true); // } // // @After // public void tearDown() { // ShadowBluetoothManager shadowBluetoothManager = getShadowBluetoothManager(); // shadowBluetoothManager.clearConnectionStates(); // shadowBluetoothManager.setAdapter(BluetoothAdapter.getDefaultAdapter()); // } // // protected Context getContext() { // return RuntimeEnvironment.application.getApplicationContext(); // } // // protected ShadowBluetoothManager getShadowBluetoothManager() { // BluetoothManager bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE); // return BuruberiShadows.shadowOf(bluetoothManager); // } // // protected ShadowBluetoothAdapterExt getShadowBluetoothAdapter() { // return BuruberiShadows.shadowOf(BluetoothAdapter.getDefaultAdapter()); // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // }
import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import android.support.annotation.Nullable; import org.junit.Test; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import is.hello.buruberi.testing.AssertExtensions; import is.hello.buruberi.testing.BuruberiTestCase; import static is.hello.buruberi.testing.AssertExtensions.assertThrows; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue;
public void exceptions() throws Exception { final SerialQueue queue = new SerialQueue(); // Have to force the queue into the intended state queue.queue.offer(new SerialQueue.Task() { @Override public void run() { throw new RuntimeException(">_<"); } @Override public void cancel(@Nullable Throwable cause) { fail(); } }); final AtomicBoolean cancelCalled = new AtomicBoolean(); queue.queue.offer(new SerialQueue.Task() { @Override public void cancel(@Nullable Throwable cause) { cancelCalled.set(true); assertThat(cause, is(instanceOf(RuntimeException.class))); } @Override public void run() { fail(); } }); queue.busy = true;
// Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public class AssertExtensions { // /** // * Checks that a given {@link ThrowingRunnable} throws an exception, calling fail if it does not. // * @param runnable The runnable that should throw an exception. Required. // */ // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // } // // /** // * Variant of the Runnable interface that throws a generic checked exception. // */ // public interface ThrowingRunnable { // void run() throws Exception; // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/BuruberiTestCase.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(constants = BuildConfig.class, // sdk = 21, // shadows = { // ShadowBluetoothManager.class, // ShadowBluetoothAdapterExt.class, // ShadowBluetoothLeScanner.class, // ShadowBluetoothGatt.class, // ShadowBluetoothDeviceExt.class, // }) // public abstract class BuruberiTestCase { // protected BuruberiTestCase() { // final Context baseContext = RuntimeEnvironment.application.getBaseContext(); // BuruberiShadows.setUpSystemServices(baseContext); // } // // @Before // public void setUp() { // ShadowBluetoothAdapterExt shadowBluetoothAdapter = getShadowBluetoothAdapter(); // shadowBluetoothAdapter.setState(BluetoothAdapter.STATE_ON); // shadowBluetoothAdapter.setEnabled(true); // } // // @After // public void tearDown() { // ShadowBluetoothManager shadowBluetoothManager = getShadowBluetoothManager(); // shadowBluetoothManager.clearConnectionStates(); // shadowBluetoothManager.setAdapter(BluetoothAdapter.getDefaultAdapter()); // } // // protected Context getContext() { // return RuntimeEnvironment.application.getApplicationContext(); // } // // protected ShadowBluetoothManager getShadowBluetoothManager() { // BluetoothManager bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE); // return BuruberiShadows.shadowOf(bluetoothManager); // } // // protected ShadowBluetoothAdapterExt getShadowBluetoothAdapter() { // return BuruberiShadows.shadowOf(BluetoothAdapter.getDefaultAdapter()); // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // } // Path: buruberi-core/src/test/java/is/hello/buruberi/util/SerialQueueTests.java import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import android.support.annotation.Nullable; import org.junit.Test; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import is.hello.buruberi.testing.AssertExtensions; import is.hello.buruberi.testing.BuruberiTestCase; import static is.hello.buruberi.testing.AssertExtensions.assertThrows; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; public void exceptions() throws Exception { final SerialQueue queue = new SerialQueue(); // Have to force the queue into the intended state queue.queue.offer(new SerialQueue.Task() { @Override public void run() { throw new RuntimeException(">_<"); } @Override public void cancel(@Nullable Throwable cause) { fail(); } }); final AtomicBoolean cancelCalled = new AtomicBoolean(); queue.queue.offer(new SerialQueue.Task() { @Override public void cancel(@Nullable Throwable cause) { cancelCalled.set(true); assertThat(cause, is(instanceOf(RuntimeException.class))); } @Override public void run() { fail(); } }); queue.busy = true;
assertThrows(new AssertExtensions.ThrowingRunnable() {
hello/android-buruberi
buruberi-core/src/test/java/is/hello/buruberi/util/SerialQueueTests.java
// Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public class AssertExtensions { // /** // * Checks that a given {@link ThrowingRunnable} throws an exception, calling fail if it does not. // * @param runnable The runnable that should throw an exception. Required. // */ // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // } // // /** // * Variant of the Runnable interface that throws a generic checked exception. // */ // public interface ThrowingRunnable { // void run() throws Exception; // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/BuruberiTestCase.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(constants = BuildConfig.class, // sdk = 21, // shadows = { // ShadowBluetoothManager.class, // ShadowBluetoothAdapterExt.class, // ShadowBluetoothLeScanner.class, // ShadowBluetoothGatt.class, // ShadowBluetoothDeviceExt.class, // }) // public abstract class BuruberiTestCase { // protected BuruberiTestCase() { // final Context baseContext = RuntimeEnvironment.application.getBaseContext(); // BuruberiShadows.setUpSystemServices(baseContext); // } // // @Before // public void setUp() { // ShadowBluetoothAdapterExt shadowBluetoothAdapter = getShadowBluetoothAdapter(); // shadowBluetoothAdapter.setState(BluetoothAdapter.STATE_ON); // shadowBluetoothAdapter.setEnabled(true); // } // // @After // public void tearDown() { // ShadowBluetoothManager shadowBluetoothManager = getShadowBluetoothManager(); // shadowBluetoothManager.clearConnectionStates(); // shadowBluetoothManager.setAdapter(BluetoothAdapter.getDefaultAdapter()); // } // // protected Context getContext() { // return RuntimeEnvironment.application.getApplicationContext(); // } // // protected ShadowBluetoothManager getShadowBluetoothManager() { // BluetoothManager bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE); // return BuruberiShadows.shadowOf(bluetoothManager); // } // // protected ShadowBluetoothAdapterExt getShadowBluetoothAdapter() { // return BuruberiShadows.shadowOf(BluetoothAdapter.getDefaultAdapter()); // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // }
import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import android.support.annotation.Nullable; import org.junit.Test; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import is.hello.buruberi.testing.AssertExtensions; import is.hello.buruberi.testing.BuruberiTestCase; import static is.hello.buruberi.testing.AssertExtensions.assertThrows; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue;
public void exceptions() throws Exception { final SerialQueue queue = new SerialQueue(); // Have to force the queue into the intended state queue.queue.offer(new SerialQueue.Task() { @Override public void run() { throw new RuntimeException(">_<"); } @Override public void cancel(@Nullable Throwable cause) { fail(); } }); final AtomicBoolean cancelCalled = new AtomicBoolean(); queue.queue.offer(new SerialQueue.Task() { @Override public void cancel(@Nullable Throwable cause) { cancelCalled.set(true); assertThat(cause, is(instanceOf(RuntimeException.class))); } @Override public void run() { fail(); } }); queue.busy = true;
// Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public class AssertExtensions { // /** // * Checks that a given {@link ThrowingRunnable} throws an exception, calling fail if it does not. // * @param runnable The runnable that should throw an exception. Required. // */ // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // } // // /** // * Variant of the Runnable interface that throws a generic checked exception. // */ // public interface ThrowingRunnable { // void run() throws Exception; // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/BuruberiTestCase.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(constants = BuildConfig.class, // sdk = 21, // shadows = { // ShadowBluetoothManager.class, // ShadowBluetoothAdapterExt.class, // ShadowBluetoothLeScanner.class, // ShadowBluetoothGatt.class, // ShadowBluetoothDeviceExt.class, // }) // public abstract class BuruberiTestCase { // protected BuruberiTestCase() { // final Context baseContext = RuntimeEnvironment.application.getBaseContext(); // BuruberiShadows.setUpSystemServices(baseContext); // } // // @Before // public void setUp() { // ShadowBluetoothAdapterExt shadowBluetoothAdapter = getShadowBluetoothAdapter(); // shadowBluetoothAdapter.setState(BluetoothAdapter.STATE_ON); // shadowBluetoothAdapter.setEnabled(true); // } // // @After // public void tearDown() { // ShadowBluetoothManager shadowBluetoothManager = getShadowBluetoothManager(); // shadowBluetoothManager.clearConnectionStates(); // shadowBluetoothManager.setAdapter(BluetoothAdapter.getDefaultAdapter()); // } // // protected Context getContext() { // return RuntimeEnvironment.application.getApplicationContext(); // } // // protected ShadowBluetoothManager getShadowBluetoothManager() { // BluetoothManager bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE); // return BuruberiShadows.shadowOf(bluetoothManager); // } // // protected ShadowBluetoothAdapterExt getShadowBluetoothAdapter() { // return BuruberiShadows.shadowOf(BluetoothAdapter.getDefaultAdapter()); // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // } // Path: buruberi-core/src/test/java/is/hello/buruberi/util/SerialQueueTests.java import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import android.support.annotation.Nullable; import org.junit.Test; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import is.hello.buruberi.testing.AssertExtensions; import is.hello.buruberi.testing.BuruberiTestCase; import static is.hello.buruberi.testing.AssertExtensions.assertThrows; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; public void exceptions() throws Exception { final SerialQueue queue = new SerialQueue(); // Have to force the queue into the intended state queue.queue.offer(new SerialQueue.Task() { @Override public void run() { throw new RuntimeException(">_<"); } @Override public void cancel(@Nullable Throwable cause) { fail(); } }); final AtomicBoolean cancelCalled = new AtomicBoolean(); queue.queue.offer(new SerialQueue.Task() { @Override public void cancel(@Nullable Throwable cause) { cancelCalled.set(true); assertThat(cause, is(instanceOf(RuntimeException.class))); } @Override public void run() { fail(); } }); queue.busy = true;
assertThrows(new AssertExtensions.ThrowingRunnable() {
hello/android-buruberi
buruberi-core/src/test/java/is/hello/buruberi/bluetooth/stacks/util/BytesTests.java
// Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public class AssertExtensions { // /** // * Checks that a given {@link ThrowingRunnable} throws an exception, calling fail if it does not. // * @param runnable The runnable that should throw an exception. Required. // */ // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // } // // /** // * Variant of the Runnable interface that throws a generic checked exception. // */ // public interface ThrowingRunnable { // void run() throws Exception; // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/BuruberiTestCase.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(constants = BuildConfig.class, // sdk = 21, // shadows = { // ShadowBluetoothManager.class, // ShadowBluetoothAdapterExt.class, // ShadowBluetoothLeScanner.class, // ShadowBluetoothGatt.class, // ShadowBluetoothDeviceExt.class, // }) // public abstract class BuruberiTestCase { // protected BuruberiTestCase() { // final Context baseContext = RuntimeEnvironment.application.getBaseContext(); // BuruberiShadows.setUpSystemServices(baseContext); // } // // @Before // public void setUp() { // ShadowBluetoothAdapterExt shadowBluetoothAdapter = getShadowBluetoothAdapter(); // shadowBluetoothAdapter.setState(BluetoothAdapter.STATE_ON); // shadowBluetoothAdapter.setEnabled(true); // } // // @After // public void tearDown() { // ShadowBluetoothManager shadowBluetoothManager = getShadowBluetoothManager(); // shadowBluetoothManager.clearConnectionStates(); // shadowBluetoothManager.setAdapter(BluetoothAdapter.getDefaultAdapter()); // } // // protected Context getContext() { // return RuntimeEnvironment.application.getApplicationContext(); // } // // protected ShadowBluetoothManager getShadowBluetoothManager() { // BluetoothManager bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE); // return BuruberiShadows.shadowOf(bluetoothManager); // } // // protected ShadowBluetoothAdapterExt getShadowBluetoothAdapter() { // return BuruberiShadows.shadowOf(BluetoothAdapter.getDefaultAdapter()); // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // }
import org.junit.Test; import java.util.Arrays; import is.hello.buruberi.testing.AssertExtensions; import is.hello.buruberi.testing.BuruberiTestCase; import static is.hello.buruberi.testing.AssertExtensions.assertThrows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
/* * Copyright 2015 Hello Inc. * * 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 is.hello.buruberi.bluetooth.stacks.util; public class BytesTests extends BuruberiTestCase { @Test public void toStringWithBounds() throws Exception { final byte[] emptyBytes = {}; final String emptyString = Bytes.toString(emptyBytes, 0, 0); assertEquals("", emptyString); final byte[] testBytes = { 0x12, 0x14, 0x0f, 0x12 }; assertEquals("1214", Bytes.toString(testBytes, 0, 2)); assertEquals("0F12", Bytes.toString(testBytes, 2, 4));
// Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public class AssertExtensions { // /** // * Checks that a given {@link ThrowingRunnable} throws an exception, calling fail if it does not. // * @param runnable The runnable that should throw an exception. Required. // */ // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // } // // /** // * Variant of the Runnable interface that throws a generic checked exception. // */ // public interface ThrowingRunnable { // void run() throws Exception; // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/BuruberiTestCase.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(constants = BuildConfig.class, // sdk = 21, // shadows = { // ShadowBluetoothManager.class, // ShadowBluetoothAdapterExt.class, // ShadowBluetoothLeScanner.class, // ShadowBluetoothGatt.class, // ShadowBluetoothDeviceExt.class, // }) // public abstract class BuruberiTestCase { // protected BuruberiTestCase() { // final Context baseContext = RuntimeEnvironment.application.getBaseContext(); // BuruberiShadows.setUpSystemServices(baseContext); // } // // @Before // public void setUp() { // ShadowBluetoothAdapterExt shadowBluetoothAdapter = getShadowBluetoothAdapter(); // shadowBluetoothAdapter.setState(BluetoothAdapter.STATE_ON); // shadowBluetoothAdapter.setEnabled(true); // } // // @After // public void tearDown() { // ShadowBluetoothManager shadowBluetoothManager = getShadowBluetoothManager(); // shadowBluetoothManager.clearConnectionStates(); // shadowBluetoothManager.setAdapter(BluetoothAdapter.getDefaultAdapter()); // } // // protected Context getContext() { // return RuntimeEnvironment.application.getApplicationContext(); // } // // protected ShadowBluetoothManager getShadowBluetoothManager() { // BluetoothManager bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE); // return BuruberiShadows.shadowOf(bluetoothManager); // } // // protected ShadowBluetoothAdapterExt getShadowBluetoothAdapter() { // return BuruberiShadows.shadowOf(BluetoothAdapter.getDefaultAdapter()); // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // } // Path: buruberi-core/src/test/java/is/hello/buruberi/bluetooth/stacks/util/BytesTests.java import org.junit.Test; import java.util.Arrays; import is.hello.buruberi.testing.AssertExtensions; import is.hello.buruberi.testing.BuruberiTestCase; import static is.hello.buruberi.testing.AssertExtensions.assertThrows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /* * Copyright 2015 Hello Inc. * * 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 is.hello.buruberi.bluetooth.stacks.util; public class BytesTests extends BuruberiTestCase { @Test public void toStringWithBounds() throws Exception { final byte[] emptyBytes = {}; final String emptyString = Bytes.toString(emptyBytes, 0, 0); assertEquals("", emptyString); final byte[] testBytes = { 0x12, 0x14, 0x0f, 0x12 }; assertEquals("1214", Bytes.toString(testBytes, 0, 2)); assertEquals("0F12", Bytes.toString(testBytes, 2, 4));
assertThrows(new AssertExtensions.ThrowingRunnable() {
hello/android-buruberi
buruberi-core/src/test/java/is/hello/buruberi/bluetooth/stacks/util/BytesTests.java
// Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public class AssertExtensions { // /** // * Checks that a given {@link ThrowingRunnable} throws an exception, calling fail if it does not. // * @param runnable The runnable that should throw an exception. Required. // */ // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // } // // /** // * Variant of the Runnable interface that throws a generic checked exception. // */ // public interface ThrowingRunnable { // void run() throws Exception; // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/BuruberiTestCase.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(constants = BuildConfig.class, // sdk = 21, // shadows = { // ShadowBluetoothManager.class, // ShadowBluetoothAdapterExt.class, // ShadowBluetoothLeScanner.class, // ShadowBluetoothGatt.class, // ShadowBluetoothDeviceExt.class, // }) // public abstract class BuruberiTestCase { // protected BuruberiTestCase() { // final Context baseContext = RuntimeEnvironment.application.getBaseContext(); // BuruberiShadows.setUpSystemServices(baseContext); // } // // @Before // public void setUp() { // ShadowBluetoothAdapterExt shadowBluetoothAdapter = getShadowBluetoothAdapter(); // shadowBluetoothAdapter.setState(BluetoothAdapter.STATE_ON); // shadowBluetoothAdapter.setEnabled(true); // } // // @After // public void tearDown() { // ShadowBluetoothManager shadowBluetoothManager = getShadowBluetoothManager(); // shadowBluetoothManager.clearConnectionStates(); // shadowBluetoothManager.setAdapter(BluetoothAdapter.getDefaultAdapter()); // } // // protected Context getContext() { // return RuntimeEnvironment.application.getApplicationContext(); // } // // protected ShadowBluetoothManager getShadowBluetoothManager() { // BluetoothManager bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE); // return BuruberiShadows.shadowOf(bluetoothManager); // } // // protected ShadowBluetoothAdapterExt getShadowBluetoothAdapter() { // return BuruberiShadows.shadowOf(BluetoothAdapter.getDefaultAdapter()); // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // }
import org.junit.Test; import java.util.Arrays; import is.hello.buruberi.testing.AssertExtensions; import is.hello.buruberi.testing.BuruberiTestCase; import static is.hello.buruberi.testing.AssertExtensions.assertThrows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
/* * Copyright 2015 Hello Inc. * * 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 is.hello.buruberi.bluetooth.stacks.util; public class BytesTests extends BuruberiTestCase { @Test public void toStringWithBounds() throws Exception { final byte[] emptyBytes = {}; final String emptyString = Bytes.toString(emptyBytes, 0, 0); assertEquals("", emptyString); final byte[] testBytes = { 0x12, 0x14, 0x0f, 0x12 }; assertEquals("1214", Bytes.toString(testBytes, 0, 2)); assertEquals("0F12", Bytes.toString(testBytes, 2, 4));
// Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public class AssertExtensions { // /** // * Checks that a given {@link ThrowingRunnable} throws an exception, calling fail if it does not. // * @param runnable The runnable that should throw an exception. Required. // */ // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // } // // /** // * Variant of the Runnable interface that throws a generic checked exception. // */ // public interface ThrowingRunnable { // void run() throws Exception; // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/BuruberiTestCase.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(constants = BuildConfig.class, // sdk = 21, // shadows = { // ShadowBluetoothManager.class, // ShadowBluetoothAdapterExt.class, // ShadowBluetoothLeScanner.class, // ShadowBluetoothGatt.class, // ShadowBluetoothDeviceExt.class, // }) // public abstract class BuruberiTestCase { // protected BuruberiTestCase() { // final Context baseContext = RuntimeEnvironment.application.getBaseContext(); // BuruberiShadows.setUpSystemServices(baseContext); // } // // @Before // public void setUp() { // ShadowBluetoothAdapterExt shadowBluetoothAdapter = getShadowBluetoothAdapter(); // shadowBluetoothAdapter.setState(BluetoothAdapter.STATE_ON); // shadowBluetoothAdapter.setEnabled(true); // } // // @After // public void tearDown() { // ShadowBluetoothManager shadowBluetoothManager = getShadowBluetoothManager(); // shadowBluetoothManager.clearConnectionStates(); // shadowBluetoothManager.setAdapter(BluetoothAdapter.getDefaultAdapter()); // } // // protected Context getContext() { // return RuntimeEnvironment.application.getApplicationContext(); // } // // protected ShadowBluetoothManager getShadowBluetoothManager() { // BluetoothManager bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE); // return BuruberiShadows.shadowOf(bluetoothManager); // } // // protected ShadowBluetoothAdapterExt getShadowBluetoothAdapter() { // return BuruberiShadows.shadowOf(BluetoothAdapter.getDefaultAdapter()); // } // } // // Path: buruberi-core/src/test/java/is/hello/buruberi/testing/AssertExtensions.java // public static void assertThrows(@NonNull ThrowingRunnable runnable) { // try { // runnable.run(); // } catch (Throwable e) { // return; // } // // Assert.fail("expected exception, got none"); // } // Path: buruberi-core/src/test/java/is/hello/buruberi/bluetooth/stacks/util/BytesTests.java import org.junit.Test; import java.util.Arrays; import is.hello.buruberi.testing.AssertExtensions; import is.hello.buruberi.testing.BuruberiTestCase; import static is.hello.buruberi.testing.AssertExtensions.assertThrows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /* * Copyright 2015 Hello Inc. * * 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 is.hello.buruberi.bluetooth.stacks.util; public class BytesTests extends BuruberiTestCase { @Test public void toStringWithBounds() throws Exception { final byte[] emptyBytes = {}; final String emptyString = Bytes.toString(emptyBytes, 0, 0); assertEquals("", emptyString); final byte[] testBytes = { 0x12, 0x14, 0x0f, 0x12 }; assertEquals("1214", Bytes.toString(testBytes, 0, 2)); assertEquals("0F12", Bytes.toString(testBytes, 2, 4));
assertThrows(new AssertExtensions.ThrowingRunnable() {
hello/android-buruberi
buruberi-example/src/main/java/is/hello/buruberi/example/ExampleApplication.java
// Path: buruberi-example/src/main/java/is/hello/buruberi/example/modules/AppModule.java // @Module(complete = false, // includes = { // BluetoothModule.class, // }, // injects = { // ScanActivity.class, // PeripheralActivity.class, // }) // public class AppModule { // } // // Path: buruberi-example/src/main/java/is/hello/buruberi/example/modules/BluetoothModule.java // @Module(complete = false, // injects = { // ScanPresenter.class, // PeripheralPresenter.class, // }) // public class BluetoothModule { // private final Context context; // // public BluetoothModule(@NonNull Context context) { // this.context = context; // } // // @Singleton @Provides LoggerFacade provideLoggerFacade() { // return new LoggerFacade() { // @Override // public void error(@NonNull String tag, @Nullable String message, @Nullable Throwable e) { // Log.e(tag, message, e); // } // // @Override // public void warn(@NonNull String tag, @Nullable String message, @Nullable Throwable e) { // Log.w(tag, message, e); // } // // @Override // public void warn(@NonNull String tag, @Nullable String message) { // Log.w(tag, message); // } // // @Override // public void info(@NonNull String tag, @Nullable String message) { // Log.i(tag, message); // } // // @Override // public void debug(@NonNull String tag, @Nullable String message) { // Log.d(tag, message); // } // }; // } // // @Singleton @Provides BluetoothStack provideBluetoothStack(@NonNull LoggerFacade logger) { // return new Buruberi() // .setApplicationContext(context) // .setLoggerFacade(logger) // .build(); // } // } // // Path: buruberi-example/src/main/java/is/hello/buruberi/example/modules/Injector.java // public interface Injector { // <T> void inject(@NonNull T target); // }
import android.app.Application; import android.support.annotation.NonNull; import dagger.ObjectGraph; import is.hello.buruberi.example.modules.AppModule; import is.hello.buruberi.example.modules.BluetoothModule; import is.hello.buruberi.example.modules.Injector;
package is.hello.buruberi.example; public class ExampleApplication extends Application implements Injector { private ObjectGraph objectGraph; @Override public void onCreate() { super.onCreate();
// Path: buruberi-example/src/main/java/is/hello/buruberi/example/modules/AppModule.java // @Module(complete = false, // includes = { // BluetoothModule.class, // }, // injects = { // ScanActivity.class, // PeripheralActivity.class, // }) // public class AppModule { // } // // Path: buruberi-example/src/main/java/is/hello/buruberi/example/modules/BluetoothModule.java // @Module(complete = false, // injects = { // ScanPresenter.class, // PeripheralPresenter.class, // }) // public class BluetoothModule { // private final Context context; // // public BluetoothModule(@NonNull Context context) { // this.context = context; // } // // @Singleton @Provides LoggerFacade provideLoggerFacade() { // return new LoggerFacade() { // @Override // public void error(@NonNull String tag, @Nullable String message, @Nullable Throwable e) { // Log.e(tag, message, e); // } // // @Override // public void warn(@NonNull String tag, @Nullable String message, @Nullable Throwable e) { // Log.w(tag, message, e); // } // // @Override // public void warn(@NonNull String tag, @Nullable String message) { // Log.w(tag, message); // } // // @Override // public void info(@NonNull String tag, @Nullable String message) { // Log.i(tag, message); // } // // @Override // public void debug(@NonNull String tag, @Nullable String message) { // Log.d(tag, message); // } // }; // } // // @Singleton @Provides BluetoothStack provideBluetoothStack(@NonNull LoggerFacade logger) { // return new Buruberi() // .setApplicationContext(context) // .setLoggerFacade(logger) // .build(); // } // } // // Path: buruberi-example/src/main/java/is/hello/buruberi/example/modules/Injector.java // public interface Injector { // <T> void inject(@NonNull T target); // } // Path: buruberi-example/src/main/java/is/hello/buruberi/example/ExampleApplication.java import android.app.Application; import android.support.annotation.NonNull; import dagger.ObjectGraph; import is.hello.buruberi.example.modules.AppModule; import is.hello.buruberi.example.modules.BluetoothModule; import is.hello.buruberi.example.modules.Injector; package is.hello.buruberi.example; public class ExampleApplication extends Application implements Injector { private ObjectGraph objectGraph; @Override public void onCreate() { super.onCreate();
this.objectGraph = ObjectGraph.create(new BluetoothModule(getBaseContext()),
hello/android-buruberi
buruberi-example/src/main/java/is/hello/buruberi/example/ExampleApplication.java
// Path: buruberi-example/src/main/java/is/hello/buruberi/example/modules/AppModule.java // @Module(complete = false, // includes = { // BluetoothModule.class, // }, // injects = { // ScanActivity.class, // PeripheralActivity.class, // }) // public class AppModule { // } // // Path: buruberi-example/src/main/java/is/hello/buruberi/example/modules/BluetoothModule.java // @Module(complete = false, // injects = { // ScanPresenter.class, // PeripheralPresenter.class, // }) // public class BluetoothModule { // private final Context context; // // public BluetoothModule(@NonNull Context context) { // this.context = context; // } // // @Singleton @Provides LoggerFacade provideLoggerFacade() { // return new LoggerFacade() { // @Override // public void error(@NonNull String tag, @Nullable String message, @Nullable Throwable e) { // Log.e(tag, message, e); // } // // @Override // public void warn(@NonNull String tag, @Nullable String message, @Nullable Throwable e) { // Log.w(tag, message, e); // } // // @Override // public void warn(@NonNull String tag, @Nullable String message) { // Log.w(tag, message); // } // // @Override // public void info(@NonNull String tag, @Nullable String message) { // Log.i(tag, message); // } // // @Override // public void debug(@NonNull String tag, @Nullable String message) { // Log.d(tag, message); // } // }; // } // // @Singleton @Provides BluetoothStack provideBluetoothStack(@NonNull LoggerFacade logger) { // return new Buruberi() // .setApplicationContext(context) // .setLoggerFacade(logger) // .build(); // } // } // // Path: buruberi-example/src/main/java/is/hello/buruberi/example/modules/Injector.java // public interface Injector { // <T> void inject(@NonNull T target); // }
import android.app.Application; import android.support.annotation.NonNull; import dagger.ObjectGraph; import is.hello.buruberi.example.modules.AppModule; import is.hello.buruberi.example.modules.BluetoothModule; import is.hello.buruberi.example.modules.Injector;
package is.hello.buruberi.example; public class ExampleApplication extends Application implements Injector { private ObjectGraph objectGraph; @Override public void onCreate() { super.onCreate(); this.objectGraph = ObjectGraph.create(new BluetoothModule(getBaseContext()),
// Path: buruberi-example/src/main/java/is/hello/buruberi/example/modules/AppModule.java // @Module(complete = false, // includes = { // BluetoothModule.class, // }, // injects = { // ScanActivity.class, // PeripheralActivity.class, // }) // public class AppModule { // } // // Path: buruberi-example/src/main/java/is/hello/buruberi/example/modules/BluetoothModule.java // @Module(complete = false, // injects = { // ScanPresenter.class, // PeripheralPresenter.class, // }) // public class BluetoothModule { // private final Context context; // // public BluetoothModule(@NonNull Context context) { // this.context = context; // } // // @Singleton @Provides LoggerFacade provideLoggerFacade() { // return new LoggerFacade() { // @Override // public void error(@NonNull String tag, @Nullable String message, @Nullable Throwable e) { // Log.e(tag, message, e); // } // // @Override // public void warn(@NonNull String tag, @Nullable String message, @Nullable Throwable e) { // Log.w(tag, message, e); // } // // @Override // public void warn(@NonNull String tag, @Nullable String message) { // Log.w(tag, message); // } // // @Override // public void info(@NonNull String tag, @Nullable String message) { // Log.i(tag, message); // } // // @Override // public void debug(@NonNull String tag, @Nullable String message) { // Log.d(tag, message); // } // }; // } // // @Singleton @Provides BluetoothStack provideBluetoothStack(@NonNull LoggerFacade logger) { // return new Buruberi() // .setApplicationContext(context) // .setLoggerFacade(logger) // .build(); // } // } // // Path: buruberi-example/src/main/java/is/hello/buruberi/example/modules/Injector.java // public interface Injector { // <T> void inject(@NonNull T target); // } // Path: buruberi-example/src/main/java/is/hello/buruberi/example/ExampleApplication.java import android.app.Application; import android.support.annotation.NonNull; import dagger.ObjectGraph; import is.hello.buruberi.example.modules.AppModule; import is.hello.buruberi.example.modules.BluetoothModule; import is.hello.buruberi.example.modules.Injector; package is.hello.buruberi.example; public class ExampleApplication extends Application implements Injector { private ObjectGraph objectGraph; @Override public void onCreate() { super.onCreate(); this.objectGraph = ObjectGraph.create(new BluetoothModule(getBaseContext()),
new AppModule());
hello/android-buruberi
buruberi-core/src/test/java/is/hello/buruberi/bluetooth/stacks/util/AdvertisingDataTests.java
// Path: buruberi-core/src/test/java/is/hello/buruberi/testing/BuruberiTestCase.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(constants = BuildConfig.class, // sdk = 21, // shadows = { // ShadowBluetoothManager.class, // ShadowBluetoothAdapterExt.class, // ShadowBluetoothLeScanner.class, // ShadowBluetoothGatt.class, // ShadowBluetoothDeviceExt.class, // }) // public abstract class BuruberiTestCase { // protected BuruberiTestCase() { // final Context baseContext = RuntimeEnvironment.application.getBaseContext(); // BuruberiShadows.setUpSystemServices(baseContext); // } // // @Before // public void setUp() { // ShadowBluetoothAdapterExt shadowBluetoothAdapter = getShadowBluetoothAdapter(); // shadowBluetoothAdapter.setState(BluetoothAdapter.STATE_ON); // shadowBluetoothAdapter.setEnabled(true); // } // // @After // public void tearDown() { // ShadowBluetoothManager shadowBluetoothManager = getShadowBluetoothManager(); // shadowBluetoothManager.clearConnectionStates(); // shadowBluetoothManager.setAdapter(BluetoothAdapter.getDefaultAdapter()); // } // // protected Context getContext() { // return RuntimeEnvironment.application.getApplicationContext(); // } // // protected ShadowBluetoothManager getShadowBluetoothManager() { // BluetoothManager bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE); // return BuruberiShadows.shadowOf(bluetoothManager); // } // // protected ShadowBluetoothAdapterExt getShadowBluetoothAdapter() { // return BuruberiShadows.shadowOf(BluetoothAdapter.getDefaultAdapter()); // } // } // // Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/util/AdvertisingData.java // public static final int TYPE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS = 0x03;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import android.os.Parcel; import android.os.Parcelable; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.junit.Test; import java.util.Arrays; import java.util.Collection; import java.util.List; import is.hello.buruberi.testing.BuruberiTestCase; import static is.hello.buruberi.bluetooth.stacks.util.AdvertisingData.TYPE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS;
/* * Copyright 2015 Hello Inc. * * 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 is.hello.buruberi.bluetooth.stacks.util; public class AdvertisingDataTests extends BuruberiTestCase { private static final byte[] TEST_PAYLOAD = { // Advertisement contents size (byte) 0x03, // Advertisement data type
// Path: buruberi-core/src/test/java/is/hello/buruberi/testing/BuruberiTestCase.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(constants = BuildConfig.class, // sdk = 21, // shadows = { // ShadowBluetoothManager.class, // ShadowBluetoothAdapterExt.class, // ShadowBluetoothLeScanner.class, // ShadowBluetoothGatt.class, // ShadowBluetoothDeviceExt.class, // }) // public abstract class BuruberiTestCase { // protected BuruberiTestCase() { // final Context baseContext = RuntimeEnvironment.application.getBaseContext(); // BuruberiShadows.setUpSystemServices(baseContext); // } // // @Before // public void setUp() { // ShadowBluetoothAdapterExt shadowBluetoothAdapter = getShadowBluetoothAdapter(); // shadowBluetoothAdapter.setState(BluetoothAdapter.STATE_ON); // shadowBluetoothAdapter.setEnabled(true); // } // // @After // public void tearDown() { // ShadowBluetoothManager shadowBluetoothManager = getShadowBluetoothManager(); // shadowBluetoothManager.clearConnectionStates(); // shadowBluetoothManager.setAdapter(BluetoothAdapter.getDefaultAdapter()); // } // // protected Context getContext() { // return RuntimeEnvironment.application.getApplicationContext(); // } // // protected ShadowBluetoothManager getShadowBluetoothManager() { // BluetoothManager bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE); // return BuruberiShadows.shadowOf(bluetoothManager); // } // // protected ShadowBluetoothAdapterExt getShadowBluetoothAdapter() { // return BuruberiShadows.shadowOf(BluetoothAdapter.getDefaultAdapter()); // } // } // // Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/util/AdvertisingData.java // public static final int TYPE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS = 0x03; // Path: buruberi-core/src/test/java/is/hello/buruberi/bluetooth/stacks/util/AdvertisingDataTests.java import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import android.os.Parcel; import android.os.Parcelable; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.junit.Test; import java.util.Arrays; import java.util.Collection; import java.util.List; import is.hello.buruberi.testing.BuruberiTestCase; import static is.hello.buruberi.bluetooth.stacks.util.AdvertisingData.TYPE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS; /* * Copyright 2015 Hello Inc. * * 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 is.hello.buruberi.bluetooth.stacks.util; public class AdvertisingDataTests extends BuruberiTestCase { private static final byte[] TEST_PAYLOAD = { // Advertisement contents size (byte) 0x03, // Advertisement data type
(byte) TYPE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS,
hello/android-buruberi
buruberi-core/src/main/java/is/hello/buruberi/util/Defaults.java
// Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/util/ErrorListener.java // public interface ErrorListener extends Action1<Throwable> { // } // // Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/util/LoggerFacade.java // public interface LoggerFacade { // void error(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message); // void info(@NonNull String tag, @Nullable String message); // void debug(@NonNull String tag, @Nullable String message); // }
import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import is.hello.buruberi.bluetooth.stacks.util.ErrorListener; import is.hello.buruberi.bluetooth.stacks.util.LoggerFacade;
/* * Copyright 2015 Hello Inc. * * 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 is.hello.buruberi.util; public final class Defaults { public static LoggerFacade createLogcatFacade() { return new LoggerFacade() { @Override public void error(@NonNull String tag, @Nullable String message, @Nullable Throwable e) { Log.e(tag, message, e); } @Override public void warn(@NonNull String tag, @Nullable String message, @Nullable Throwable e) { Log.w(tag, message, e); } @Override public void warn(@NonNull String tag, @Nullable String message) { Log.w(tag, message); } @Override public void info(@NonNull String tag, @Nullable String message) { Log.i(tag, message); } @Override public void debug(@NonNull String tag, @Nullable String message) { Log.d(tag, message); } }; }
// Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/util/ErrorListener.java // public interface ErrorListener extends Action1<Throwable> { // } // // Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/util/LoggerFacade.java // public interface LoggerFacade { // void error(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message); // void info(@NonNull String tag, @Nullable String message); // void debug(@NonNull String tag, @Nullable String message); // } // Path: buruberi-core/src/main/java/is/hello/buruberi/util/Defaults.java import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import is.hello.buruberi.bluetooth.stacks.util.ErrorListener; import is.hello.buruberi.bluetooth.stacks.util.LoggerFacade; /* * Copyright 2015 Hello Inc. * * 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 is.hello.buruberi.util; public final class Defaults { public static LoggerFacade createLogcatFacade() { return new LoggerFacade() { @Override public void error(@NonNull String tag, @Nullable String message, @Nullable Throwable e) { Log.e(tag, message, e); } @Override public void warn(@NonNull String tag, @Nullable String message, @Nullable Throwable e) { Log.w(tag, message, e); } @Override public void warn(@NonNull String tag, @Nullable String message) { Log.w(tag, message); } @Override public void info(@NonNull String tag, @Nullable String message) { Log.i(tag, message); } @Override public void debug(@NonNull String tag, @Nullable String message) { Log.d(tag, message); } }; }
public static ErrorListener createEmptyErrorListener() {
hello/android-buruberi
buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/android/HighPowerPeripheralScanner.java
// Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/BluetoothStack.java // public interface BluetoothStack { // /** // * The log tag that of BluetoothStack use. // */ // String LOG_TAG = "Bluetooth." + BluetoothStack.class.getSimpleName(); // // /** // * A local broadcast that indicates an implicit pairing request has been initiated by the system. // * <p> // * Only available starting in API level 19, Android KitKat. // * // * @see GattPeripheral#EXTRA_NAME for the name of the affected peripheral. // * @see GattPeripheral#EXTRA_ADDRESS for the address of the affected peripheral. // */ // String ACTION_PAIRING_REQUEST = BluetoothStack.class.getName() + ".ACTION_PAIRING_REQUEST"; // // // /** // * Performs a scan for peripherals matching a given set of criteria. // * <p> // * Yields {@link UserDisabledBuruberiException} if // * the device's Bluetooth radio is currently disabled. // * // * @see PeripheralCriteria // */ // @RequiresPermission(allOf = { // Manifest.permission.BLUETOOTH, // Manifest.permission.BLUETOOTH_ADMIN, // }) // @NonNull Observable<List<GattPeripheral>> discoverPeripherals(@NonNull PeripheralCriteria peripheralCriteria); // // /** // * Returns the RxJava {@code Scheduler} used for all stack operations. // */ // @NonNull Scheduler getScheduler(); // // /** // * Vends an observable configured appropriately for use with this {@code BluetoothStack}. // * @return A configured {@code Observable}. // * @see #getScheduler() // */ // <T> Observable<T> newConfiguredObservable(@NonNull Observable.OnSubscribe<T> onSubscribe); // // /** // * Returns an observable that will continuously report the power state // * of the device's bluetooth radio. // * // * @see #isEnabled() for one time values. // */ // @RequiresPermission(Manifest.permission.BLUETOOTH) // Observable<Boolean> enabled(); // // /** // * Returns the current power state of the device's bluetooth radio. // * // * @see #enabled() for observations over time. // */ // @RequiresPermission(Manifest.permission.BLUETOOTH) // boolean isEnabled(); // // /** // * Turns on the device's Bluetooth radio. // * // * @see ChangePowerStateException // */ // @RequiresPermission(allOf = { // Manifest.permission.BLUETOOTH, // Manifest.permission.BLUETOOTH_ADMIN, // }) // Observable<Void> turnOn(); // // /** // * Turns off the device's Bluetooth radio. // * // * @see ChangePowerStateException // */ // @RequiresPermission(allOf = { // Manifest.permission.BLUETOOTH, // Manifest.permission.BLUETOOTH_ADMIN, // }) // Observable<Void> turnOff(); // // // /** // * Returns the logger facade associated with the {@code BluetoothStack}. // */ // @NonNull LoggerFacade getLogger(); // // // /** // * Writes the state of a peripheral into a {@code Parcelable} object. // * // * @param peripheral The peripheral whose state needs to be saved. // * @return The saved state. // */ // @Nullable Parcelable saveState(@NonNull GattPeripheral peripheral); // // /** // * Restores the saved state of a peripheral into a new object. // * // * @param savedState The state to restore. // * @return A new peripheral representing the saved state. // */ // GattPeripheral restoreState(@Nullable Parcelable savedState); // } // // Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/util/LoggerFacade.java // public interface LoggerFacade { // void error(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message); // void info(@NonNull String tag, @Nullable String message); // void debug(@NonNull String tag, @Nullable String message); // }
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.ParcelUuid; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import is.hello.buruberi.bluetooth.stacks.BluetoothStack; import is.hello.buruberi.bluetooth.stacks.util.LoggerFacade; import rx.Observable; import rx.Scheduler; import rx.Subscriber; import rx.Subscription; import rx.functions.Action0;
/* * Copyright 2015 Hello Inc. * * 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 is.hello.buruberi.bluetooth.stacks.android; class HighPowerPeripheralScanner extends BroadcastReceiver implements Observable.OnSubscribe<List<BluetoothDevice>> { /** * Roughly how long the documentation says a scan should take. */ private static final int SCAN_DURATION_S = 15; private final Context context; private final BluetoothAdapter adapter; private final Scheduler.Worker worker;
// Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/BluetoothStack.java // public interface BluetoothStack { // /** // * The log tag that of BluetoothStack use. // */ // String LOG_TAG = "Bluetooth." + BluetoothStack.class.getSimpleName(); // // /** // * A local broadcast that indicates an implicit pairing request has been initiated by the system. // * <p> // * Only available starting in API level 19, Android KitKat. // * // * @see GattPeripheral#EXTRA_NAME for the name of the affected peripheral. // * @see GattPeripheral#EXTRA_ADDRESS for the address of the affected peripheral. // */ // String ACTION_PAIRING_REQUEST = BluetoothStack.class.getName() + ".ACTION_PAIRING_REQUEST"; // // // /** // * Performs a scan for peripherals matching a given set of criteria. // * <p> // * Yields {@link UserDisabledBuruberiException} if // * the device's Bluetooth radio is currently disabled. // * // * @see PeripheralCriteria // */ // @RequiresPermission(allOf = { // Manifest.permission.BLUETOOTH, // Manifest.permission.BLUETOOTH_ADMIN, // }) // @NonNull Observable<List<GattPeripheral>> discoverPeripherals(@NonNull PeripheralCriteria peripheralCriteria); // // /** // * Returns the RxJava {@code Scheduler} used for all stack operations. // */ // @NonNull Scheduler getScheduler(); // // /** // * Vends an observable configured appropriately for use with this {@code BluetoothStack}. // * @return A configured {@code Observable}. // * @see #getScheduler() // */ // <T> Observable<T> newConfiguredObservable(@NonNull Observable.OnSubscribe<T> onSubscribe); // // /** // * Returns an observable that will continuously report the power state // * of the device's bluetooth radio. // * // * @see #isEnabled() for one time values. // */ // @RequiresPermission(Manifest.permission.BLUETOOTH) // Observable<Boolean> enabled(); // // /** // * Returns the current power state of the device's bluetooth radio. // * // * @see #enabled() for observations over time. // */ // @RequiresPermission(Manifest.permission.BLUETOOTH) // boolean isEnabled(); // // /** // * Turns on the device's Bluetooth radio. // * // * @see ChangePowerStateException // */ // @RequiresPermission(allOf = { // Manifest.permission.BLUETOOTH, // Manifest.permission.BLUETOOTH_ADMIN, // }) // Observable<Void> turnOn(); // // /** // * Turns off the device's Bluetooth radio. // * // * @see ChangePowerStateException // */ // @RequiresPermission(allOf = { // Manifest.permission.BLUETOOTH, // Manifest.permission.BLUETOOTH_ADMIN, // }) // Observable<Void> turnOff(); // // // /** // * Returns the logger facade associated with the {@code BluetoothStack}. // */ // @NonNull LoggerFacade getLogger(); // // // /** // * Writes the state of a peripheral into a {@code Parcelable} object. // * // * @param peripheral The peripheral whose state needs to be saved. // * @return The saved state. // */ // @Nullable Parcelable saveState(@NonNull GattPeripheral peripheral); // // /** // * Restores the saved state of a peripheral into a new object. // * // * @param savedState The state to restore. // * @return A new peripheral representing the saved state. // */ // GattPeripheral restoreState(@Nullable Parcelable savedState); // } // // Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/util/LoggerFacade.java // public interface LoggerFacade { // void error(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message); // void info(@NonNull String tag, @Nullable String message); // void debug(@NonNull String tag, @Nullable String message); // } // Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/android/HighPowerPeripheralScanner.java import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.ParcelUuid; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import is.hello.buruberi.bluetooth.stacks.BluetoothStack; import is.hello.buruberi.bluetooth.stacks.util.LoggerFacade; import rx.Observable; import rx.Scheduler; import rx.Subscriber; import rx.Subscription; import rx.functions.Action0; /* * Copyright 2015 Hello Inc. * * 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 is.hello.buruberi.bluetooth.stacks.android; class HighPowerPeripheralScanner extends BroadcastReceiver implements Observable.OnSubscribe<List<BluetoothDevice>> { /** * Roughly how long the documentation says a scan should take. */ private static final int SCAN_DURATION_S = 15; private final Context context; private final BluetoothAdapter adapter; private final Scheduler.Worker worker;
private final LoggerFacade logger;
hello/android-buruberi
buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/android/HighPowerPeripheralScanner.java
// Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/BluetoothStack.java // public interface BluetoothStack { // /** // * The log tag that of BluetoothStack use. // */ // String LOG_TAG = "Bluetooth." + BluetoothStack.class.getSimpleName(); // // /** // * A local broadcast that indicates an implicit pairing request has been initiated by the system. // * <p> // * Only available starting in API level 19, Android KitKat. // * // * @see GattPeripheral#EXTRA_NAME for the name of the affected peripheral. // * @see GattPeripheral#EXTRA_ADDRESS for the address of the affected peripheral. // */ // String ACTION_PAIRING_REQUEST = BluetoothStack.class.getName() + ".ACTION_PAIRING_REQUEST"; // // // /** // * Performs a scan for peripherals matching a given set of criteria. // * <p> // * Yields {@link UserDisabledBuruberiException} if // * the device's Bluetooth radio is currently disabled. // * // * @see PeripheralCriteria // */ // @RequiresPermission(allOf = { // Manifest.permission.BLUETOOTH, // Manifest.permission.BLUETOOTH_ADMIN, // }) // @NonNull Observable<List<GattPeripheral>> discoverPeripherals(@NonNull PeripheralCriteria peripheralCriteria); // // /** // * Returns the RxJava {@code Scheduler} used for all stack operations. // */ // @NonNull Scheduler getScheduler(); // // /** // * Vends an observable configured appropriately for use with this {@code BluetoothStack}. // * @return A configured {@code Observable}. // * @see #getScheduler() // */ // <T> Observable<T> newConfiguredObservable(@NonNull Observable.OnSubscribe<T> onSubscribe); // // /** // * Returns an observable that will continuously report the power state // * of the device's bluetooth radio. // * // * @see #isEnabled() for one time values. // */ // @RequiresPermission(Manifest.permission.BLUETOOTH) // Observable<Boolean> enabled(); // // /** // * Returns the current power state of the device's bluetooth radio. // * // * @see #enabled() for observations over time. // */ // @RequiresPermission(Manifest.permission.BLUETOOTH) // boolean isEnabled(); // // /** // * Turns on the device's Bluetooth radio. // * // * @see ChangePowerStateException // */ // @RequiresPermission(allOf = { // Manifest.permission.BLUETOOTH, // Manifest.permission.BLUETOOTH_ADMIN, // }) // Observable<Void> turnOn(); // // /** // * Turns off the device's Bluetooth radio. // * // * @see ChangePowerStateException // */ // @RequiresPermission(allOf = { // Manifest.permission.BLUETOOTH, // Manifest.permission.BLUETOOTH_ADMIN, // }) // Observable<Void> turnOff(); // // // /** // * Returns the logger facade associated with the {@code BluetoothStack}. // */ // @NonNull LoggerFacade getLogger(); // // // /** // * Writes the state of a peripheral into a {@code Parcelable} object. // * // * @param peripheral The peripheral whose state needs to be saved. // * @return The saved state. // */ // @Nullable Parcelable saveState(@NonNull GattPeripheral peripheral); // // /** // * Restores the saved state of a peripheral into a new object. // * // * @param savedState The state to restore. // * @return A new peripheral representing the saved state. // */ // GattPeripheral restoreState(@Nullable Parcelable savedState); // } // // Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/util/LoggerFacade.java // public interface LoggerFacade { // void error(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message); // void info(@NonNull String tag, @Nullable String message); // void debug(@NonNull String tag, @Nullable String message); // }
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.ParcelUuid; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import is.hello.buruberi.bluetooth.stacks.BluetoothStack; import is.hello.buruberi.bluetooth.stacks.util.LoggerFacade; import rx.Observable; import rx.Scheduler; import rx.Subscriber; import rx.Subscription; import rx.functions.Action0;
case BluetoothAdapter.ACTION_DISCOVERY_STARTED: { worker.schedule(new Action0() { @Override public void call() { onDiscoveryStarted(); } }); break; } case BluetoothAdapter.ACTION_DISCOVERY_FINISHED: { worker.schedule(new Action0() { @Override public void call() { onDiscoveryFinished(); } }); break; } default: { throw new IllegalArgumentException("Unknown intent " + intent); } } } private void onDeviceFound(@NonNull BluetoothDevice device, short rssi, @Nullable ParcelUuid uuid, @Nullable String name) {
// Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/BluetoothStack.java // public interface BluetoothStack { // /** // * The log tag that of BluetoothStack use. // */ // String LOG_TAG = "Bluetooth." + BluetoothStack.class.getSimpleName(); // // /** // * A local broadcast that indicates an implicit pairing request has been initiated by the system. // * <p> // * Only available starting in API level 19, Android KitKat. // * // * @see GattPeripheral#EXTRA_NAME for the name of the affected peripheral. // * @see GattPeripheral#EXTRA_ADDRESS for the address of the affected peripheral. // */ // String ACTION_PAIRING_REQUEST = BluetoothStack.class.getName() + ".ACTION_PAIRING_REQUEST"; // // // /** // * Performs a scan for peripherals matching a given set of criteria. // * <p> // * Yields {@link UserDisabledBuruberiException} if // * the device's Bluetooth radio is currently disabled. // * // * @see PeripheralCriteria // */ // @RequiresPermission(allOf = { // Manifest.permission.BLUETOOTH, // Manifest.permission.BLUETOOTH_ADMIN, // }) // @NonNull Observable<List<GattPeripheral>> discoverPeripherals(@NonNull PeripheralCriteria peripheralCriteria); // // /** // * Returns the RxJava {@code Scheduler} used for all stack operations. // */ // @NonNull Scheduler getScheduler(); // // /** // * Vends an observable configured appropriately for use with this {@code BluetoothStack}. // * @return A configured {@code Observable}. // * @see #getScheduler() // */ // <T> Observable<T> newConfiguredObservable(@NonNull Observable.OnSubscribe<T> onSubscribe); // // /** // * Returns an observable that will continuously report the power state // * of the device's bluetooth radio. // * // * @see #isEnabled() for one time values. // */ // @RequiresPermission(Manifest.permission.BLUETOOTH) // Observable<Boolean> enabled(); // // /** // * Returns the current power state of the device's bluetooth radio. // * // * @see #enabled() for observations over time. // */ // @RequiresPermission(Manifest.permission.BLUETOOTH) // boolean isEnabled(); // // /** // * Turns on the device's Bluetooth radio. // * // * @see ChangePowerStateException // */ // @RequiresPermission(allOf = { // Manifest.permission.BLUETOOTH, // Manifest.permission.BLUETOOTH_ADMIN, // }) // Observable<Void> turnOn(); // // /** // * Turns off the device's Bluetooth radio. // * // * @see ChangePowerStateException // */ // @RequiresPermission(allOf = { // Manifest.permission.BLUETOOTH, // Manifest.permission.BLUETOOTH_ADMIN, // }) // Observable<Void> turnOff(); // // // /** // * Returns the logger facade associated with the {@code BluetoothStack}. // */ // @NonNull LoggerFacade getLogger(); // // // /** // * Writes the state of a peripheral into a {@code Parcelable} object. // * // * @param peripheral The peripheral whose state needs to be saved. // * @return The saved state. // */ // @Nullable Parcelable saveState(@NonNull GattPeripheral peripheral); // // /** // * Restores the saved state of a peripheral into a new object. // * // * @param savedState The state to restore. // * @return A new peripheral representing the saved state. // */ // GattPeripheral restoreState(@Nullable Parcelable savedState); // } // // Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/util/LoggerFacade.java // public interface LoggerFacade { // void error(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message); // void info(@NonNull String tag, @Nullable String message); // void debug(@NonNull String tag, @Nullable String message); // } // Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/android/HighPowerPeripheralScanner.java import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.ParcelUuid; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import is.hello.buruberi.bluetooth.stacks.BluetoothStack; import is.hello.buruberi.bluetooth.stacks.util.LoggerFacade; import rx.Observable; import rx.Scheduler; import rx.Subscriber; import rx.Subscription; import rx.functions.Action0; case BluetoothAdapter.ACTION_DISCOVERY_STARTED: { worker.schedule(new Action0() { @Override public void call() { onDiscoveryStarted(); } }); break; } case BluetoothAdapter.ACTION_DISCOVERY_FINISHED: { worker.schedule(new Action0() { @Override public void call() { onDiscoveryFinished(); } }); break; } default: { throw new IllegalArgumentException("Unknown intent " + intent); } } } private void onDeviceFound(@NonNull BluetoothDevice device, short rssi, @Nullable ParcelUuid uuid, @Nullable String name) {
logger.info(BluetoothStack.LOG_TAG, "high power scan found {" + device + " rssi: " + rssi + ", uuid: " + uuid + ", name: " + name + "}");
hello/android-buruberi
buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/android/SchedulerOperationTimeout.java
// Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/OperationTimeout.java // public interface OperationTimeout { // String LOG_TAG = "Bluetooth." + OperationTimeout.class.getSimpleName(); // // /** // * Called by {@link GattPeripheral}. Schedules a timeout timer. // * <p> // * This method is not assumed to be safe to call until after // * {@link #setTimeoutAction(Action0, Scheduler)} is called. // */ // void schedule(); // // /** // * Called by {@link GattPeripheral}. Unschedules the timeout timer. // * <p> // * It is a valid condition for this method to be called multiple times, // * it should become a no-op after the first call. // * <p> // * This method is not assumed to be safe to call until after // * {@link #setTimeoutAction(Action0, Scheduler)} is called. // */ // void unschedule(); // // /** // * For use by clients. Unschedules and reschedules the timeout timer. // * <p> // * This method is not assumed to be safe to call until after // * {@link #setTimeoutAction(Action0, Scheduler)} is called. // */ // void reschedule(); // // /** // * Called by {@link GattPeripheral}. Specifies an action to run when // * the timeout expires that will allow the stack to clean up any resources. // * <p> // * Client code should check the state of a peripheral after a timeout has expired. // * // * @param action Stack specific logic to handle the timeout. // * @param scheduler The scheduler to run the handler on. // */ // void setTimeoutAction(@NonNull Action0 action, @NonNull Scheduler scheduler); // } // // Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/util/LoggerFacade.java // public interface LoggerFacade { // void error(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message); // void info(@NonNull String tag, @Nullable String message); // void debug(@NonNull String tag, @Nullable String message); // }
import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.concurrent.TimeUnit; import is.hello.buruberi.bluetooth.stacks.OperationTimeout; import is.hello.buruberi.bluetooth.stacks.util.LoggerFacade; import rx.Scheduler; import rx.Subscription; import rx.functions.Action0;
/* * Copyright 2015 Hello Inc. * * 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 is.hello.buruberi.bluetooth.stacks.android; /** * Simple implementation of {@link OperationTimeout} that uses deferred workers. */ public final class SchedulerOperationTimeout implements OperationTimeout { private final String name; private final long durationMs;
// Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/OperationTimeout.java // public interface OperationTimeout { // String LOG_TAG = "Bluetooth." + OperationTimeout.class.getSimpleName(); // // /** // * Called by {@link GattPeripheral}. Schedules a timeout timer. // * <p> // * This method is not assumed to be safe to call until after // * {@link #setTimeoutAction(Action0, Scheduler)} is called. // */ // void schedule(); // // /** // * Called by {@link GattPeripheral}. Unschedules the timeout timer. // * <p> // * It is a valid condition for this method to be called multiple times, // * it should become a no-op after the first call. // * <p> // * This method is not assumed to be safe to call until after // * {@link #setTimeoutAction(Action0, Scheduler)} is called. // */ // void unschedule(); // // /** // * For use by clients. Unschedules and reschedules the timeout timer. // * <p> // * This method is not assumed to be safe to call until after // * {@link #setTimeoutAction(Action0, Scheduler)} is called. // */ // void reschedule(); // // /** // * Called by {@link GattPeripheral}. Specifies an action to run when // * the timeout expires that will allow the stack to clean up any resources. // * <p> // * Client code should check the state of a peripheral after a timeout has expired. // * // * @param action Stack specific logic to handle the timeout. // * @param scheduler The scheduler to run the handler on. // */ // void setTimeoutAction(@NonNull Action0 action, @NonNull Scheduler scheduler); // } // // Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/util/LoggerFacade.java // public interface LoggerFacade { // void error(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message, @Nullable Throwable e); // void warn(@NonNull String tag, @Nullable String message); // void info(@NonNull String tag, @Nullable String message); // void debug(@NonNull String tag, @Nullable String message); // } // Path: buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/android/SchedulerOperationTimeout.java import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.concurrent.TimeUnit; import is.hello.buruberi.bluetooth.stacks.OperationTimeout; import is.hello.buruberi.bluetooth.stacks.util.LoggerFacade; import rx.Scheduler; import rx.Subscription; import rx.functions.Action0; /* * Copyright 2015 Hello Inc. * * 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 is.hello.buruberi.bluetooth.stacks.android; /** * Simple implementation of {@link OperationTimeout} that uses deferred workers. */ public final class SchedulerOperationTimeout implements OperationTimeout { private final String name; private final long durationMs;
private final LoggerFacade logger;
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/ui/wizard/IWizardPage.java
// Path: src/com/eldorado/remoteresources/ui/wizard/IWizard.java // public enum WizardStatus { // OK, INFO, WARNING, ERROR // };
import java.util.List; import javax.swing.SwingWorker; import com.eldorado.remoteresources.ui.wizard.IWizard.WizardStatus;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.ui.wizard; /** * This interface defines a minimum wizard page * * @author Marcelo Marzola Bossoni * */ public interface IWizardPage { public boolean hasNextPage(); public boolean hasPreviousPage(); public boolean isPageValid(); public void setNextPage(IWizardPage page); public IWizardPage getNextPage(); public void setPreviousPage(IWizardPage page); public IWizardPage getPreviousPage(); public String getDescription(); public void setDescription(String description); public void setErrorMessage(String errorMessage); public String getErrorMessage();
// Path: src/com/eldorado/remoteresources/ui/wizard/IWizard.java // public enum WizardStatus { // OK, INFO, WARNING, ERROR // }; // Path: src/com/eldorado/remoteresources/ui/wizard/IWizardPage.java import java.util.List; import javax.swing.SwingWorker; import com.eldorado.remoteresources.ui.wizard.IWizard.WizardStatus; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.ui.wizard; /** * This interface defines a minimum wizard page * * @author Marcelo Marzola Bossoni * */ public interface IWizardPage { public boolean hasNextPage(); public boolean hasPreviousPage(); public boolean isPageValid(); public void setNextPage(IWizardPage page); public IWizardPage getNextPage(); public void setPreviousPage(IWizardPage page); public IWizardPage getPreviousPage(); public String getDescription(); public void setDescription(String description); public void setErrorMessage(String errorMessage); public String getErrorMessage();
public void setErrorLevel(WizardStatus level);
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlRebootMessage.java
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // }
import com.eldorado.remoteresources.utils.SubType;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to handle files (pull/push/delete) * * @author Rafael Dias Santos * */ public class ControlRebootMessage extends CommandMessage { private static final long serialVersionUID = 5481207318846024671L; public ControlRebootMessage(int sequenceNumber, String serialNumber,
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlRebootMessage.java import com.eldorado.remoteresources.utils.SubType; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to handle files (pull/push/delete) * * @author Rafael Dias Santos * */ public class ControlRebootMessage extends CommandMessage { private static final long serialVersionUID = 5481207318846024671L; public ControlRebootMessage(int sequenceNumber, String serialNumber,
SubType subType, String[] params) {
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlPackageHandlingMessage.java
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // }
import com.eldorado.remoteresources.utils.SubType;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to handle files (pull/push/delete) * * @author Rafael Dias Santos * */ public class ControlPackageHandlingMessage extends CommandMessage { private static final long serialVersionUID = 5481207318846024671L; public ControlPackageHandlingMessage(int sequenceNumber,
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlPackageHandlingMessage.java import com.eldorado.remoteresources.utils.SubType; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to handle files (pull/push/delete) * * @author Rafael Dias Santos * */ public class ControlPackageHandlingMessage extends CommandMessage { private static final long serialVersionUID = 5481207318846024671L; public ControlPackageHandlingMessage(int sequenceNumber,
String serialNumber, SubType subType, String[] params) {
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/server/AndroidDevice.java
// Path: src/com/eldorado/remoteresources/android/common/Keys.java // public enum Keys { // /** */ // HOME, // /** */ // BACK, // /** */ // VOLUME_UP, // /** */ // VOLUME_DOWN, // /** */ // POWER, // /** */ // CAMERA, // /** */ // CLEAR, // /** */ // DEL, // /** */ // FOCUS, // /** */ // MENU, // /** */ // SEARCH; // // @Override // public String toString() { // return "KEYCODE_" + super.toString(); // } // } // // Path: src/com/eldorado/remoteresources/utils/StringUtils.java // public class StringUtils { // /** // * // * @param str // * @return // */ // public static boolean isEmpty(String str) { // if (str == null) { // return true; // } // // return str.isEmpty(); // } // // public static byte[] compress(String log) throws IOException { // ByteArrayOutputStream xzOutput = new ByteArrayOutputStream(); // XZOutputStream xzStream = new XZOutputStream(xzOutput, // new LZMA2Options(LZMA2Options.PRESET_MAX)); // xzStream.write(log.getBytes()); // xzStream.close(); // return xzOutput.toByteArray(); // } // // public static String decompress(byte[] log) throws IOException { // XZInputStream xzInputStream = new XZInputStream( // new ByteArrayInputStream(log)); // byte firstByte = (byte) xzInputStream.read(); // byte[] buffer = new byte[xzInputStream.available()]; // buffer[0] = firstByte; // xzInputStream.read(buffer, 1, buffer.length - 2); // xzInputStream.close(); // return new String(buffer); // } // // }
import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.android.chimpchat.adb.AdbChimpDevice; import com.android.chimpchat.core.TouchPressType; import com.android.ddmlib.IDevice; import com.eldorado.remoteresources.android.common.Keys; import com.eldorado.remoteresources.utils.StringUtils;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.server; /** * * * */ public class AndroidDevice { /** * */ private IDevice device; /** * */ private AdbChimpDevice chimpDevice; /** * */ private final String serialNumber; /** * */ private String deviceModel; /** * */ private Dimension screenSize; /** * */ private static final String KEYCODE_SPACE = String.valueOf(62); /** * */ private static final Pattern[] DISPLAY_SIZE_PATTERNS = { Pattern.compile("\\scur=(?<width>\\d+)x(?<height>\\d+)\\s", Pattern.CASE_INSENSITIVE), Pattern.compile( "displaywidth\\s*\\=\\s*(?<width>\\d+).*displayheight\\s*\\=\\s*(?<height>\\d+)", Pattern.CASE_INSENSITIVE) }; /** * * @param device */ public AndroidDevice(IDevice device) { this.device = device; serialNumber = device.getSerialNumber(); chimpDevice = new AdbChimpDevice(device); getScreenSize(); } public IDevice getDevice() { return device; } public void setDevice(IDevice device) { this.device = device; } /** * * @return */ public String getDeviceModel() {
// Path: src/com/eldorado/remoteresources/android/common/Keys.java // public enum Keys { // /** */ // HOME, // /** */ // BACK, // /** */ // VOLUME_UP, // /** */ // VOLUME_DOWN, // /** */ // POWER, // /** */ // CAMERA, // /** */ // CLEAR, // /** */ // DEL, // /** */ // FOCUS, // /** */ // MENU, // /** */ // SEARCH; // // @Override // public String toString() { // return "KEYCODE_" + super.toString(); // } // } // // Path: src/com/eldorado/remoteresources/utils/StringUtils.java // public class StringUtils { // /** // * // * @param str // * @return // */ // public static boolean isEmpty(String str) { // if (str == null) { // return true; // } // // return str.isEmpty(); // } // // public static byte[] compress(String log) throws IOException { // ByteArrayOutputStream xzOutput = new ByteArrayOutputStream(); // XZOutputStream xzStream = new XZOutputStream(xzOutput, // new LZMA2Options(LZMA2Options.PRESET_MAX)); // xzStream.write(log.getBytes()); // xzStream.close(); // return xzOutput.toByteArray(); // } // // public static String decompress(byte[] log) throws IOException { // XZInputStream xzInputStream = new XZInputStream( // new ByteArrayInputStream(log)); // byte firstByte = (byte) xzInputStream.read(); // byte[] buffer = new byte[xzInputStream.available()]; // buffer[0] = firstByte; // xzInputStream.read(buffer, 1, buffer.length - 2); // xzInputStream.close(); // return new String(buffer); // } // // } // Path: src/com/eldorado/remoteresources/android/server/AndroidDevice.java import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.android.chimpchat.adb.AdbChimpDevice; import com.android.chimpchat.core.TouchPressType; import com.android.ddmlib.IDevice; import com.eldorado.remoteresources.android.common.Keys; import com.eldorado.remoteresources.utils.StringUtils; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.server; /** * * * */ public class AndroidDevice { /** * */ private IDevice device; /** * */ private AdbChimpDevice chimpDevice; /** * */ private final String serialNumber; /** * */ private String deviceModel; /** * */ private Dimension screenSize; /** * */ private static final String KEYCODE_SPACE = String.valueOf(62); /** * */ private static final Pattern[] DISPLAY_SIZE_PATTERNS = { Pattern.compile("\\scur=(?<width>\\d+)x(?<height>\\d+)\\s", Pattern.CASE_INSENSITIVE), Pattern.compile( "displaywidth\\s*\\=\\s*(?<width>\\d+).*displayheight\\s*\\=\\s*(?<height>\\d+)", Pattern.CASE_INSENSITIVE) }; /** * * @param device */ public AndroidDevice(IDevice device) { this.device = device; serialNumber = device.getSerialNumber(); chimpDevice = new AdbChimpDevice(device); getScreenSize(); } public IDevice getDevice() { return device; } public void setDevice(IDevice device) { this.device = device; } /** * * @return */ public String getDeviceModel() {
if (StringUtils.isEmpty(deviceModel)) {
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/server/AndroidDevice.java
// Path: src/com/eldorado/remoteresources/android/common/Keys.java // public enum Keys { // /** */ // HOME, // /** */ // BACK, // /** */ // VOLUME_UP, // /** */ // VOLUME_DOWN, // /** */ // POWER, // /** */ // CAMERA, // /** */ // CLEAR, // /** */ // DEL, // /** */ // FOCUS, // /** */ // MENU, // /** */ // SEARCH; // // @Override // public String toString() { // return "KEYCODE_" + super.toString(); // } // } // // Path: src/com/eldorado/remoteresources/utils/StringUtils.java // public class StringUtils { // /** // * // * @param str // * @return // */ // public static boolean isEmpty(String str) { // if (str == null) { // return true; // } // // return str.isEmpty(); // } // // public static byte[] compress(String log) throws IOException { // ByteArrayOutputStream xzOutput = new ByteArrayOutputStream(); // XZOutputStream xzStream = new XZOutputStream(xzOutput, // new LZMA2Options(LZMA2Options.PRESET_MAX)); // xzStream.write(log.getBytes()); // xzStream.close(); // return xzOutput.toByteArray(); // } // // public static String decompress(byte[] log) throws IOException { // XZInputStream xzInputStream = new XZInputStream( // new ByteArrayInputStream(log)); // byte firstByte = (byte) xzInputStream.read(); // byte[] buffer = new byte[xzInputStream.available()]; // buffer[0] = firstByte; // xzInputStream.read(buffer, 1, buffer.length - 2); // xzInputStream.close(); // return new String(buffer); // } // // }
import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.android.chimpchat.adb.AdbChimpDevice; import com.android.chimpchat.core.TouchPressType; import com.android.ddmlib.IDevice; import com.eldorado.remoteresources.android.common.Keys; import com.eldorado.remoteresources.utils.StringUtils;
chimpDevice.getManager().quit(); device = null; chimpDevice = null; } catch (Exception e) { // TODO: handle exception } } @Override public boolean equals(Object obj) { return obj instanceof AndroidDevice ? ((AndroidDevice) obj) .getSerialNumber().equalsIgnoreCase(serialNumber) : false; } /** * * @param key * @param pressType */ private void pressKey(String key, TouchPressType pressType) { if (isOnline()) { chimpDevice.press(key, pressType); } } /** * * @param key */
// Path: src/com/eldorado/remoteresources/android/common/Keys.java // public enum Keys { // /** */ // HOME, // /** */ // BACK, // /** */ // VOLUME_UP, // /** */ // VOLUME_DOWN, // /** */ // POWER, // /** */ // CAMERA, // /** */ // CLEAR, // /** */ // DEL, // /** */ // FOCUS, // /** */ // MENU, // /** */ // SEARCH; // // @Override // public String toString() { // return "KEYCODE_" + super.toString(); // } // } // // Path: src/com/eldorado/remoteresources/utils/StringUtils.java // public class StringUtils { // /** // * // * @param str // * @return // */ // public static boolean isEmpty(String str) { // if (str == null) { // return true; // } // // return str.isEmpty(); // } // // public static byte[] compress(String log) throws IOException { // ByteArrayOutputStream xzOutput = new ByteArrayOutputStream(); // XZOutputStream xzStream = new XZOutputStream(xzOutput, // new LZMA2Options(LZMA2Options.PRESET_MAX)); // xzStream.write(log.getBytes()); // xzStream.close(); // return xzOutput.toByteArray(); // } // // public static String decompress(byte[] log) throws IOException { // XZInputStream xzInputStream = new XZInputStream( // new ByteArrayInputStream(log)); // byte firstByte = (byte) xzInputStream.read(); // byte[] buffer = new byte[xzInputStream.available()]; // buffer[0] = firstByte; // xzInputStream.read(buffer, 1, buffer.length - 2); // xzInputStream.close(); // return new String(buffer); // } // // } // Path: src/com/eldorado/remoteresources/android/server/AndroidDevice.java import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.android.chimpchat.adb.AdbChimpDevice; import com.android.chimpchat.core.TouchPressType; import com.android.ddmlib.IDevice; import com.eldorado.remoteresources.android.common.Keys; import com.eldorado.remoteresources.utils.StringUtils; chimpDevice.getManager().quit(); device = null; chimpDevice = null; } catch (Exception e) { // TODO: handle exception } } @Override public boolean equals(Object obj) { return obj instanceof AndroidDevice ? ((AndroidDevice) obj) .getSerialNumber().equalsIgnoreCase(serialNumber) : false; } /** * * @param key * @param pressType */ private void pressKey(String key, TouchPressType pressType) { if (isOnline()) { chimpDevice.press(key, pressType); } } /** * * @param key */
public void keyDown(Keys key) {
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/UpdateScriptFile.java
// Path: src/com/eldorado/remoteresources/ui/actions/ClientManipulationScript.java // public class ClientManipulationScript { // // private static final String DEFAULT_CLIENT_SCRIPT_DIR = RemoteResourcesConfiguration // .getRemoteResourcesDir() != null ? RemoteResourcesConfiguration // .getRemoteResourcesDir() + File.separator + "scripts" : System //$NON-NLS-1$ // .getProperty("user.home"); // // private static final String CLIENT_SCRIPT_FILENAME_EXTENSION = ".txt"; //$NON-NLS-1$ // // private static String outputFile = null; // private BufferedWriter out; // // private static String serialNumber; // private static String host; // private static String port; // // public boolean playGenerateScriptFile(String device, String host, // String port, String path, String name) { // // serialNumber = device; // ClientManipulationScript.host = host; // ClientManipulationScript.port = port; // // File fOutputDir = new File(path); // // if (!fOutputDir.exists()) { // fOutputDir.mkdirs(); // } // // outputFile = path + File.separator + name; // // File f = new File(outputFile); // if (!f.exists()) { // try { // out = new BufferedWriter(new FileWriter(outputFile)); // return true; // } catch (IOException e) { // e.printStackTrace(); // } // } // return false; // } // // public void stopGenerateScriptFile(Vector<String> actions) { // Iterator<String> it = actions.iterator(); // // try { // out.write(serialNumber); // out.newLine(); // while (it.hasNext()) { // System.out.println(); // out.write(it.next().toString()); // out.newLine(); // } // out.close(); // Script.clean(); // } catch (IOException e) { // // } // } // // public void createScriptFile(String device, String host, String port, // String path, String name, Vector<String> actions) { // if (playGenerateScriptFile(device, host, port, path, name)) { // stopGenerateScriptFile(actions); // } // Script.clean(); // } // // // ================== READ A SCRIPT ================== // public Vector<String> readScriptFile(File f) { // Vector<String> actions = null; // BufferedReader reader = null; // try { // if (f.canRead()) { // actions = new Vector<String>(); // reader = new BufferedReader(new FileReader(f)); // String line = reader.readLine(); // // while (line != null) { // actions.add(line); // line = reader.readLine(); // } // } // } catch (FileNotFoundException e) { // } catch (IOException e) { // } finally { // if (reader != null) { // try { // reader.close(); // } catch (IOException e) { // // do nothing // } // } // } // // return actions; // } // // // ================== UPDATE SCRIPT ================== // public void updateScriptFile(File f, Vector<String> actions) { // // BufferedWriter writer = null; // Iterator it = actions.iterator(); // // try { // if (f.canRead() && !it.equals(null)) { // writer = new BufferedWriter(new PrintWriter(new FileWriter(f))); // while (it.hasNext()) { // writer.write(it.next().toString()); // writer.newLine(); // } // } // // writer.close(); // } catch (FileNotFoundException e) { // } catch (IOException e) { // } finally { // if (writer != null) { // try { // writer.close(); // } catch (IOException e) { // // do nothing // } // } // } // // } // }
import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.util.Iterator; import java.util.Vector; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ScrollPaneConstants; import com.eldorado.remoteresources.ui.actions.ClientManipulationScript;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources; public class UpdateScriptFile extends JFrame { // TODO: remove me (this class) when I won't be useful anymore! =) private static String linha; private static String tempo; private static Vector<String> vetScript; private static final int OPCAO_SLEEP = 1; private static final int OPCAO_PAUSE = 2; private final static JTextArea actionsText = new JTextArea(); private final JButton saveButton = new JButton("Save"); private final JRadioButton sleepRadio = new JRadioButton("Tag Sleep", true); private final JRadioButton pauseRadio = new JRadioButton("Tag Pause");
// Path: src/com/eldorado/remoteresources/ui/actions/ClientManipulationScript.java // public class ClientManipulationScript { // // private static final String DEFAULT_CLIENT_SCRIPT_DIR = RemoteResourcesConfiguration // .getRemoteResourcesDir() != null ? RemoteResourcesConfiguration // .getRemoteResourcesDir() + File.separator + "scripts" : System //$NON-NLS-1$ // .getProperty("user.home"); // // private static final String CLIENT_SCRIPT_FILENAME_EXTENSION = ".txt"; //$NON-NLS-1$ // // private static String outputFile = null; // private BufferedWriter out; // // private static String serialNumber; // private static String host; // private static String port; // // public boolean playGenerateScriptFile(String device, String host, // String port, String path, String name) { // // serialNumber = device; // ClientManipulationScript.host = host; // ClientManipulationScript.port = port; // // File fOutputDir = new File(path); // // if (!fOutputDir.exists()) { // fOutputDir.mkdirs(); // } // // outputFile = path + File.separator + name; // // File f = new File(outputFile); // if (!f.exists()) { // try { // out = new BufferedWriter(new FileWriter(outputFile)); // return true; // } catch (IOException e) { // e.printStackTrace(); // } // } // return false; // } // // public void stopGenerateScriptFile(Vector<String> actions) { // Iterator<String> it = actions.iterator(); // // try { // out.write(serialNumber); // out.newLine(); // while (it.hasNext()) { // System.out.println(); // out.write(it.next().toString()); // out.newLine(); // } // out.close(); // Script.clean(); // } catch (IOException e) { // // } // } // // public void createScriptFile(String device, String host, String port, // String path, String name, Vector<String> actions) { // if (playGenerateScriptFile(device, host, port, path, name)) { // stopGenerateScriptFile(actions); // } // Script.clean(); // } // // // ================== READ A SCRIPT ================== // public Vector<String> readScriptFile(File f) { // Vector<String> actions = null; // BufferedReader reader = null; // try { // if (f.canRead()) { // actions = new Vector<String>(); // reader = new BufferedReader(new FileReader(f)); // String line = reader.readLine(); // // while (line != null) { // actions.add(line); // line = reader.readLine(); // } // } // } catch (FileNotFoundException e) { // } catch (IOException e) { // } finally { // if (reader != null) { // try { // reader.close(); // } catch (IOException e) { // // do nothing // } // } // } // // return actions; // } // // // ================== UPDATE SCRIPT ================== // public void updateScriptFile(File f, Vector<String> actions) { // // BufferedWriter writer = null; // Iterator it = actions.iterator(); // // try { // if (f.canRead() && !it.equals(null)) { // writer = new BufferedWriter(new PrintWriter(new FileWriter(f))); // while (it.hasNext()) { // writer.write(it.next().toString()); // writer.newLine(); // } // } // // writer.close(); // } catch (FileNotFoundException e) { // } catch (IOException e) { // } finally { // if (writer != null) { // try { // writer.close(); // } catch (IOException e) { // // do nothing // } // } // } // // } // } // Path: src/com/eldorado/remoteresources/UpdateScriptFile.java import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.util.Iterator; import java.util.Vector; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ScrollPaneConstants; import com.eldorado.remoteresources.ui.actions.ClientManipulationScript; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources; public class UpdateScriptFile extends JFrame { // TODO: remove me (this class) when I won't be useful anymore! =) private static String linha; private static String tempo; private static Vector<String> vetScript; private static final int OPCAO_SLEEP = 1; private static final int OPCAO_PAUSE = 2; private final static JTextArea actionsText = new JTextArea(); private final JButton saveButton = new JButton("Save"); private final JRadioButton sleepRadio = new JRadioButton("Tag Sleep", true); private final JRadioButton pauseRadio = new JRadioButton("Tag Pause");
private final static ClientManipulationScript cScript = new ClientManipulationScript();
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/CommandMessage.java
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // }
import com.eldorado.remoteresources.utils.SubType;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to run adb command * * @author Rafael Dias Santos * */ public abstract class CommandMessage extends ControlMessage { // TODO protected final String serialNumber; protected final String[] params;
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/CommandMessage.java import com.eldorado.remoteresources.utils.SubType; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to run adb command * * @author Rafael Dias Santos * */ public abstract class CommandMessage extends ControlMessage { // TODO protected final String serialNumber; protected final String[] params;
protected final SubType subType;
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlFileHandlingMessage.java
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // }
import com.eldorado.remoteresources.utils.SubType;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to handle files (pull/push/delete) * * @author Rafael Dias Santos * */ public class ControlFileHandlingMessage extends CommandMessage { private static final long serialVersionUID = 5481207318846024671L; public ControlFileHandlingMessage(int sequenceNumber, String serialNumber,
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlFileHandlingMessage.java import com.eldorado.remoteresources.utils.SubType; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to handle files (pull/push/delete) * * @author Rafael Dias Santos * */ public class ControlFileHandlingMessage extends CommandMessage { private static final long serialVersionUID = 5481207318846024671L; public ControlFileHandlingMessage(int sequenceNumber, String serialNumber,
SubType subType, String[] params) {
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/CommandMessageFactory.java
// Path: src/com/eldorado/remoteresources/utils/Command.java // public abstract class Command { // protected CommandType type; // protected SubType subType; // protected String[] params; // // public CommandType getCommandType() { // return type; // } // // public SubType getSubType() { // return subType; // } // // public abstract boolean areParametersValid(); // // public String[] getParams() { // return params; // } // }
import com.eldorado.remoteresources.utils.Command;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to run shell command * * @author Rafael Dias Santos * */ public class CommandMessageFactory { /** * */ private static final long serialVersionUID = 1467637828016992406L;
// Path: src/com/eldorado/remoteresources/utils/Command.java // public abstract class Command { // protected CommandType type; // protected SubType subType; // protected String[] params; // // public CommandType getCommandType() { // return type; // } // // public SubType getSubType() { // return subType; // } // // public abstract boolean areParametersValid(); // // public String[] getParams() { // return params; // } // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/CommandMessageFactory.java import com.eldorado.remoteresources.utils.Command; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to run shell command * * @author Rafael Dias Santos * */ public class CommandMessageFactory { /** * */ private static final long serialVersionUID = 1467637828016992406L;
public static CommandMessage getCommandMessage(Command command,
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/data/DataMessage.java
// Path: src/com/eldorado/remoteresources/android/common/connection/messages/Message.java // public abstract class Message implements Serializable { // // private static final long serialVersionUID = -1051009758389055769L; // // public static final int MAX_SEQUENCE_NUMBER = 1 << 16; // // /** // * The message type: check {@link MessageType} // */ // private final MessageType type; // // /** // * The message sequence number for the client/server connection // */ // private final int sequenceNumber; // // /** // * Create a new message with a sequence number and type // * // * @param sequenceNumber // * the sequence number // * @param type // * the message type // */ // public Message(int sequenceNumber, MessageType type) { // this.type = type; // this.sequenceNumber = sequenceNumber; // } // // /** // * Get this message type. // * // * @return the type of this message // * @see {@link MessageType} for available types // */ // public MessageType getMessageType() { // return type; // } // // /** // * Get this message sequence number // * // * @return this message sequence number // */ // public int getSequenceNumber() { // return sequenceNumber; // } // // } // // Path: src/com/eldorado/remoteresources/android/common/connection/messages/MessageType.java // public enum MessageType { // CONTROL_MESSAGE, DATA_MESSAGE; // }
import com.eldorado.remoteresources.android.common.connection.messages.Message; import com.eldorado.remoteresources.android.common.connection.messages.MessageType;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.data; /** * A data message * * @author Marcelo Marzola Bossoni * */ public abstract class DataMessage extends Message { private static final long serialVersionUID = 2991317175997003007L; private final DataMessageType messageType; /** * Create a new data message * * @param sequenceNumber * the message sequence number * @param messageType * the message type * @see {@link DataMessageType} for available types */ public DataMessage(int sequenceNumber, DataMessageType messageType) {
// Path: src/com/eldorado/remoteresources/android/common/connection/messages/Message.java // public abstract class Message implements Serializable { // // private static final long serialVersionUID = -1051009758389055769L; // // public static final int MAX_SEQUENCE_NUMBER = 1 << 16; // // /** // * The message type: check {@link MessageType} // */ // private final MessageType type; // // /** // * The message sequence number for the client/server connection // */ // private final int sequenceNumber; // // /** // * Create a new message with a sequence number and type // * // * @param sequenceNumber // * the sequence number // * @param type // * the message type // */ // public Message(int sequenceNumber, MessageType type) { // this.type = type; // this.sequenceNumber = sequenceNumber; // } // // /** // * Get this message type. // * // * @return the type of this message // * @see {@link MessageType} for available types // */ // public MessageType getMessageType() { // return type; // } // // /** // * Get this message sequence number // * // * @return this message sequence number // */ // public int getSequenceNumber() { // return sequenceNumber; // } // // } // // Path: src/com/eldorado/remoteresources/android/common/connection/messages/MessageType.java // public enum MessageType { // CONTROL_MESSAGE, DATA_MESSAGE; // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/data/DataMessage.java import com.eldorado.remoteresources.android.common.connection.messages.Message; import com.eldorado.remoteresources.android.common.connection.messages.MessageType; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.data; /** * A data message * * @author Marcelo Marzola Bossoni * */ public abstract class DataMessage extends Message { private static final long serialVersionUID = 2991317175997003007L; private final DataMessageType messageType; /** * Create a new data message * * @param sequenceNumber * the message sequence number * @param messageType * the message type * @see {@link DataMessageType} for available types */ public DataMessage(int sequenceNumber, DataMessageType messageType) {
super(sequenceNumber, MessageType.DATA_MESSAGE);
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlRunShellCommandMessage.java
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // }
import com.eldorado.remoteresources.utils.SubType;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to run shell command * * @author Rafael Dias Santos * */ public class ControlRunShellCommandMessage extends CommandMessage { public ControlRunShellCommandMessage(int sequenceNumber,
// Path: src/com/eldorado/remoteresources/utils/SubType.java // public enum SubType { // NONE, PULL, PUSH, INSTALL, UNINSTALL // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/ControlRunShellCommandMessage.java import com.eldorado.remoteresources.utils.SubType; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * Message with informations to run shell command * * @author Rafael Dias Santos * */ public class ControlRunShellCommandMessage extends CommandMessage { public ControlRunShellCommandMessage(int sequenceNumber,
String serialNumber, SubType subType, String[] params) {
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/android/common/connection/messages/control/KeyCommandMessage.java
// Path: src/com/eldorado/remoteresources/android/common/Keys.java // public enum Keys { // /** */ // HOME, // /** */ // BACK, // /** */ // VOLUME_UP, // /** */ // VOLUME_DOWN, // /** */ // POWER, // /** */ // CAMERA, // /** */ // CLEAR, // /** */ // DEL, // /** */ // FOCUS, // /** */ // MENU, // /** */ // SEARCH; // // @Override // public String toString() { // return "KEYCODE_" + super.toString(); // } // }
import com.eldorado.remoteresources.android.common.Keys;
/* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * This class represents a key command to be executed * * @author Marcelo Marzola Bossoni * */ public class KeyCommandMessage extends DeviceCommandMessage { private static final long serialVersionUID = 7784219670587270710L; public final KeyCommandMessageType keyCommandMessageType;
// Path: src/com/eldorado/remoteresources/android/common/Keys.java // public enum Keys { // /** */ // HOME, // /** */ // BACK, // /** */ // VOLUME_UP, // /** */ // VOLUME_DOWN, // /** */ // POWER, // /** */ // CAMERA, // /** */ // CLEAR, // /** */ // DEL, // /** */ // FOCUS, // /** */ // MENU, // /** */ // SEARCH; // // @Override // public String toString() { // return "KEYCODE_" + super.toString(); // } // } // Path: src/com/eldorado/remoteresources/android/common/connection/messages/control/KeyCommandMessage.java import com.eldorado.remoteresources.android.common.Keys; /* * (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/). * * This file is part of the software Remote Resources * * All rights reserved. This file and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.eldorado.remoteresources.android.common.connection.messages.control; /** * This class represents a key command to be executed * * @author Marcelo Marzola Bossoni * */ public class KeyCommandMessage extends DeviceCommandMessage { private static final long serialVersionUID = 7784219670587270710L; public final KeyCommandMessageType keyCommandMessageType;
private final Keys key;