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
|
|---|---|---|---|---|---|---|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/criteria/Accept.java
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
|
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
|
package de.jformchecker.criteria;
/**
* Checks that value is equal to one of the acceptable values.
*
* Based on work of armandino (at) gmail.com
*/
public class Accept implements Criterion {
private String[] acceptableValues;
Accept(String... values) {
this.acceptableValues = values;
}
protected boolean areEqual(String v1, String v2) {
return v1.equals(v2);
}
@Override
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
// Path: src/main/java/de/jformchecker/criteria/Accept.java
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
package de.jformchecker.criteria;
/**
* Checks that value is equal to one of the acceptable values.
*
* Based on work of armandino (at) gmail.com
*/
public class Accept implements Criterion {
private String[] acceptableValues;
Accept(String... values) {
this.acceptableValues = values;
}
protected boolean areEqual(String v1, String v2) {
return v1.equals(v2);
}
@Override
|
public ValidationResult validate(FormCheckerElement value) {
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/elements/HiddenInput.java
|
// Path: src/main/java/de/jformchecker/AttributeUtils.java
// public class AttributeUtils {
//
//
// public static String buildAttributes(Map<String, String> attributes) {
// StringBuilder attrStr = new StringBuilder();
// attributes.forEach((k,v) ->
// attrStr.append(AttributeUtils.buildSingleAttribute(k, attributes.get(k)))
// );
// return attrStr.toString();
// }
//
// public static String buildSingleAttribute(String key, String value) {
// StringBuilder attrStr = new StringBuilder();
// if (StringUtils.isEmpty(value)) {
// attrStr.append(key);
// } else {
// attrStr.append(key).append("=\"").append(value).append("\"");
// }
// attrStr.append(" ");
// return attrStr.toString();
// }
//
// public static String buildAttributes(TagAttributes attributes) {
// return AttributeUtils.buildAttributes(attributes.attributes);
// }
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
//
// Path: src/main/java/de/jformchecker/TagAttributes.java
// public class TagAttributes {
//
// // conveniance methods
// public static TagAttributes of(String key, String value) {
// return new TagAttributes(key, value);
// }
//
// public static TagAttributes of(Map<String, String> attribs) {
// return new TagAttributes(attribs);
// }
//
// LinkedHashMap<String, String> attributes;
//
// public TagAttributes(Map<String, String> attribs) {
// attributes = new LinkedHashMap<>(attribs);
// }
//
// public TagAttributes(LinkedHashMap<String, String> attribs) {
// attributes = attribs;
// }
//
// public TagAttributes() {
// this(new LinkedHashMap<>());
// }
//
// public TagAttributes(String key, String value) {
// this();
// this.put(key, value);
// }
//
// public TagAttributes put(String key, String value) {
// attributes.put(key, value);
// return this;
// }
//
// public String get(String key) {
// return attributes.get(key);
// }
//
// public void addToAttribute(String key, String value) {
// if (!attributes.containsKey(key)) {
// attributes.put(key, value);
// } else {
// attributes.put(key, attributes.get(key) + value);
// }
// }
//
// public Set<String> keySet() {
// return attributes.keySet();
// }
//
// public Map<String, String> getAttributes() {
// return attributes;
// }
//
// public void add(TagAttributes formAttributes) {
// if (formAttributes != null) {
// formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// public void add(LinkedHashMap<String, String> attribs) {
// if (attribs != null) {
// attribs.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// }
|
import java.util.Map;
import de.jformchecker.AttributeUtils;
import de.jformchecker.FormCheckerElement;
import de.jformchecker.TagAttributes;
|
package de.jformchecker.elements;
public class HiddenInput extends AbstractInput<HiddenInput> implements FormCheckerElement {
public static HiddenInput build(String name) {
HiddenInput i = new HiddenInput();
i.name = name;
return i;
}
@Override
public String getInputTag(Map<String, String> attributes) {
|
// Path: src/main/java/de/jformchecker/AttributeUtils.java
// public class AttributeUtils {
//
//
// public static String buildAttributes(Map<String, String> attributes) {
// StringBuilder attrStr = new StringBuilder();
// attributes.forEach((k,v) ->
// attrStr.append(AttributeUtils.buildSingleAttribute(k, attributes.get(k)))
// );
// return attrStr.toString();
// }
//
// public static String buildSingleAttribute(String key, String value) {
// StringBuilder attrStr = new StringBuilder();
// if (StringUtils.isEmpty(value)) {
// attrStr.append(key);
// } else {
// attrStr.append(key).append("=\"").append(value).append("\"");
// }
// attrStr.append(" ");
// return attrStr.toString();
// }
//
// public static String buildAttributes(TagAttributes attributes) {
// return AttributeUtils.buildAttributes(attributes.attributes);
// }
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
//
// Path: src/main/java/de/jformchecker/TagAttributes.java
// public class TagAttributes {
//
// // conveniance methods
// public static TagAttributes of(String key, String value) {
// return new TagAttributes(key, value);
// }
//
// public static TagAttributes of(Map<String, String> attribs) {
// return new TagAttributes(attribs);
// }
//
// LinkedHashMap<String, String> attributes;
//
// public TagAttributes(Map<String, String> attribs) {
// attributes = new LinkedHashMap<>(attribs);
// }
//
// public TagAttributes(LinkedHashMap<String, String> attribs) {
// attributes = attribs;
// }
//
// public TagAttributes() {
// this(new LinkedHashMap<>());
// }
//
// public TagAttributes(String key, String value) {
// this();
// this.put(key, value);
// }
//
// public TagAttributes put(String key, String value) {
// attributes.put(key, value);
// return this;
// }
//
// public String get(String key) {
// return attributes.get(key);
// }
//
// public void addToAttribute(String key, String value) {
// if (!attributes.containsKey(key)) {
// attributes.put(key, value);
// } else {
// attributes.put(key, attributes.get(key) + value);
// }
// }
//
// public Set<String> keySet() {
// return attributes.keySet();
// }
//
// public Map<String, String> getAttributes() {
// return attributes;
// }
//
// public void add(TagAttributes formAttributes) {
// if (formAttributes != null) {
// formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// public void add(LinkedHashMap<String, String> attribs) {
// if (attribs != null) {
// attribs.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// }
// Path: src/main/java/de/jformchecker/elements/HiddenInput.java
import java.util.Map;
import de.jformchecker.AttributeUtils;
import de.jformchecker.FormCheckerElement;
import de.jformchecker.TagAttributes;
package de.jformchecker.elements;
public class HiddenInput extends AbstractInput<HiddenInput> implements FormCheckerElement {
public static HiddenInput build(String name) {
HiddenInput i = new HiddenInput();
i.name = name;
return i;
}
@Override
public String getInputTag(Map<String, String> attributes) {
|
TagAttributes tagAttributes = new TagAttributes(attributes);
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/themes/TwoColumnBootstrapFormBuilder.java
|
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
//
// Path: src/main/java/de/jformchecker/TagAttributes.java
// public class TagAttributes {
//
// // conveniance methods
// public static TagAttributes of(String key, String value) {
// return new TagAttributes(key, value);
// }
//
// public static TagAttributes of(Map<String, String> attribs) {
// return new TagAttributes(attribs);
// }
//
// LinkedHashMap<String, String> attributes;
//
// public TagAttributes(Map<String, String> attribs) {
// attributes = new LinkedHashMap<>(attribs);
// }
//
// public TagAttributes(LinkedHashMap<String, String> attribs) {
// attributes = attribs;
// }
//
// public TagAttributes() {
// this(new LinkedHashMap<>());
// }
//
// public TagAttributes(String key, String value) {
// this();
// this.put(key, value);
// }
//
// public TagAttributes put(String key, String value) {
// attributes.put(key, value);
// return this;
// }
//
// public String get(String key) {
// return attributes.get(key);
// }
//
// public void addToAttribute(String key, String value) {
// if (!attributes.containsKey(key)) {
// attributes.put(key, value);
// } else {
// attributes.put(key, attributes.get(key) + value);
// }
// }
//
// public Set<String> keySet() {
// return attributes.keySet();
// }
//
// public Map<String, String> getAttributes() {
// return attributes;
// }
//
// public void add(TagAttributes formAttributes) {
// if (formAttributes != null) {
// formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// public void add(LinkedHashMap<String, String> attribs) {
// if (attribs != null) {
// attribs.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// }
//
// Path: src/main/java/de/jformchecker/Wrapper.java
// public class Wrapper {
// public final String start;
// public final String end;
//
// public static Wrapper of(String start, String end) {
// return new Wrapper(start, end);
// }
//
// public Wrapper(String start, String end) {
// this.start = start;
// this.end = end;
// }
//
// public String getStart() {
// return start;
// }
//
// public String getEnd() {
// return end;
// }
//
// public String wrap(String content) {
// return new StringBuffer(start).append(content).append(end).toString();
// }
//
// public static Wrapper empty() {
// return Wrapper.of("", "");
// }
//
// public static Wrapper ofTag(String tagName) {
// return Wrapper.of("<" + tagName + ">", "</" + tagName + ">");
// }
//
// }
|
import de.jformchecker.FormCheckerElement;
import de.jformchecker.TagAttributes;
import de.jformchecker.Wrapper;
|
package de.jformchecker.themes;
public class TwoColumnBootstrapFormBuilder extends BasicFormBuilder {
public TagAttributes getLabelAttributes(FormCheckerElement elem) {
TagAttributes attributes = new TagAttributes();
attributes.put("class", "col-sm-2 control-label");
return attributes;
}
|
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
//
// Path: src/main/java/de/jformchecker/TagAttributes.java
// public class TagAttributes {
//
// // conveniance methods
// public static TagAttributes of(String key, String value) {
// return new TagAttributes(key, value);
// }
//
// public static TagAttributes of(Map<String, String> attribs) {
// return new TagAttributes(attribs);
// }
//
// LinkedHashMap<String, String> attributes;
//
// public TagAttributes(Map<String, String> attribs) {
// attributes = new LinkedHashMap<>(attribs);
// }
//
// public TagAttributes(LinkedHashMap<String, String> attribs) {
// attributes = attribs;
// }
//
// public TagAttributes() {
// this(new LinkedHashMap<>());
// }
//
// public TagAttributes(String key, String value) {
// this();
// this.put(key, value);
// }
//
// public TagAttributes put(String key, String value) {
// attributes.put(key, value);
// return this;
// }
//
// public String get(String key) {
// return attributes.get(key);
// }
//
// public void addToAttribute(String key, String value) {
// if (!attributes.containsKey(key)) {
// attributes.put(key, value);
// } else {
// attributes.put(key, attributes.get(key) + value);
// }
// }
//
// public Set<String> keySet() {
// return attributes.keySet();
// }
//
// public Map<String, String> getAttributes() {
// return attributes;
// }
//
// public void add(TagAttributes formAttributes) {
// if (formAttributes != null) {
// formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// public void add(LinkedHashMap<String, String> attribs) {
// if (attribs != null) {
// attribs.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// }
//
// Path: src/main/java/de/jformchecker/Wrapper.java
// public class Wrapper {
// public final String start;
// public final String end;
//
// public static Wrapper of(String start, String end) {
// return new Wrapper(start, end);
// }
//
// public Wrapper(String start, String end) {
// this.start = start;
// this.end = end;
// }
//
// public String getStart() {
// return start;
// }
//
// public String getEnd() {
// return end;
// }
//
// public String wrap(String content) {
// return new StringBuffer(start).append(content).append(end).toString();
// }
//
// public static Wrapper empty() {
// return Wrapper.of("", "");
// }
//
// public static Wrapper ofTag(String tagName) {
// return Wrapper.of("<" + tagName + ">", "</" + tagName + ">");
// }
//
// }
// Path: src/main/java/de/jformchecker/themes/TwoColumnBootstrapFormBuilder.java
import de.jformchecker.FormCheckerElement;
import de.jformchecker.TagAttributes;
import de.jformchecker.Wrapper;
package de.jformchecker.themes;
public class TwoColumnBootstrapFormBuilder extends BasicFormBuilder {
public TagAttributes getLabelAttributes(FormCheckerElement elem) {
TagAttributes attributes = new TagAttributes();
attributes.put("class", "col-sm-2 control-label");
return attributes;
}
|
public Wrapper getWrapperForInput(FormCheckerElement elem) {
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/criteria/MaxLength.java
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
|
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
|
package de.jformchecker.criteria;
/**
* Checks that value is not greater than the specified maximum.
*
* Based on work of armandino (at) gmail.com
*/
public final class MaxLength implements Criterion {
private int maxLength;
MaxLength(int maxLength) {
this.maxLength = maxLength;
}
public int getMaxLength() {
return maxLength;
}
@Override
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
// Path: src/main/java/de/jformchecker/criteria/MaxLength.java
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
package de.jformchecker.criteria;
/**
* Checks that value is not greater than the specified maximum.
*
* Based on work of armandino (at) gmail.com
*/
public final class MaxLength implements Criterion {
private int maxLength;
MaxLength(int maxLength) {
this.maxLength = maxLength;
}
public int getMaxLength() {
return maxLength;
}
@Override
|
public ValidationResult validate(FormCheckerElement value) {
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/Criterion.java
|
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java
// public class ValidationResult {
//
// boolean isValid = false;
//
// // caching:
// private static ValidationResult okResult = new ValidationResult(true, "", null, null);
//
// public boolean isValid() {
// return isValid;
// }
//
// public String getMessage() {
// return message;
// }
//
// public Object[] getErrorVals() {
// return errorVals;
// }
//
// String message;
// String translatedMessage;
// Object[] errorVals;
//
// public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) {
// this.isValid = isValid;
// this.message = message;
// this.errorVals = errorVals;
// this.translatedMessage = translatedMessage;
// }
//
// // factory methods
// public static ValidationResult of_(boolean isValid, String message, Object... errorVals) {
// return new ValidationResult(isValid, message, errorVals, null);
// }
//
// public static ValidationResult fail(String message, Object... errorVals) {
// return new ValidationResult(false, message, errorVals, null);
// }
//
// public static ValidationResult failWithTranslated(String message, Object... errorVals) {
// return new ValidationResult(false, null, errorVals, message);
// }
//
// public static ValidationResult failWithTranslated(String message) {
// return new ValidationResult(false, null, new Object[0], message);
// }
//
// public static ValidationResult ok() {
// // RFE: Could return always the same object! will reduce memory
// // footprint!
// return okResult;
// }
//
// public String getTranslatedMessage() {
// return translatedMessage;
// }
//
// }
|
import de.jformchecker.criteria.ValidationResult;
|
package de.jformchecker;
/**
* A criterion that checks a formchecker element
*
*/
@FunctionalInterface
public interface Criterion {
/**
* Tests whether the specified value satisfies this criterion.
*
* @param value
* to be tested against this criterion.
* @return a ValidationResult which holds true or false for validaton result
* and a potential errormsg
*/
|
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java
// public class ValidationResult {
//
// boolean isValid = false;
//
// // caching:
// private static ValidationResult okResult = new ValidationResult(true, "", null, null);
//
// public boolean isValid() {
// return isValid;
// }
//
// public String getMessage() {
// return message;
// }
//
// public Object[] getErrorVals() {
// return errorVals;
// }
//
// String message;
// String translatedMessage;
// Object[] errorVals;
//
// public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) {
// this.isValid = isValid;
// this.message = message;
// this.errorVals = errorVals;
// this.translatedMessage = translatedMessage;
// }
//
// // factory methods
// public static ValidationResult of_(boolean isValid, String message, Object... errorVals) {
// return new ValidationResult(isValid, message, errorVals, null);
// }
//
// public static ValidationResult fail(String message, Object... errorVals) {
// return new ValidationResult(false, message, errorVals, null);
// }
//
// public static ValidationResult failWithTranslated(String message, Object... errorVals) {
// return new ValidationResult(false, null, errorVals, message);
// }
//
// public static ValidationResult failWithTranslated(String message) {
// return new ValidationResult(false, null, new Object[0], message);
// }
//
// public static ValidationResult ok() {
// // RFE: Could return always the same object! will reduce memory
// // footprint!
// return okResult;
// }
//
// public String getTranslatedMessage() {
// return translatedMessage;
// }
//
// }
// Path: src/main/java/de/jformchecker/Criterion.java
import de.jformchecker.criteria.ValidationResult;
package de.jformchecker;
/**
* A criterion that checks a formchecker element
*
*/
@FunctionalInterface
public interface Criterion {
/**
* Tests whether the specified value satisfies this criterion.
*
* @param value
* to be tested against this criterion.
* @return a ValidationResult which holds true or false for validaton result
* and a potential errormsg
*/
|
public ValidationResult validate(FormCheckerElement value);
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/criteria/Regex.java
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
|
import java.util.regex.Pattern;
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
|
package de.jformchecker.criteria;
/**
* Checks if a string matches a regular expression.
*
* Based on work of armandino (at) gmail.com
*/
public class Regex implements Criterion {
private Pattern pattern;
private String errorMsg = "jformchecker.regexp";
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
Regex(String pattern) {
this.pattern = Pattern.compile(pattern);
}
@Override
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
// Path: src/main/java/de/jformchecker/criteria/Regex.java
import java.util.regex.Pattern;
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
package de.jformchecker.criteria;
/**
* Checks if a string matches a regular expression.
*
* Based on work of armandino (at) gmail.com
*/
public class Regex implements Criterion {
private Pattern pattern;
private String errorMsg = "jformchecker.regexp";
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
Regex(String pattern) {
this.pattern = Pattern.compile(pattern);
}
@Override
|
public ValidationResult validate(FormCheckerElement value) {
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/elements/RadioInput.java
|
// Path: src/main/java/de/jformchecker/AttributeUtils.java
// public class AttributeUtils {
//
//
// public static String buildAttributes(Map<String, String> attributes) {
// StringBuilder attrStr = new StringBuilder();
// attributes.forEach((k,v) ->
// attrStr.append(AttributeUtils.buildSingleAttribute(k, attributes.get(k)))
// );
// return attrStr.toString();
// }
//
// public static String buildSingleAttribute(String key, String value) {
// StringBuilder attrStr = new StringBuilder();
// if (StringUtils.isEmpty(value)) {
// attrStr.append(key);
// } else {
// attrStr.append(key).append("=\"").append(value).append("\"");
// }
// attrStr.append(" ");
// return attrStr.toString();
// }
//
// public static String buildAttributes(TagAttributes attributes) {
// return AttributeUtils.buildAttributes(attributes.attributes);
// }
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
|
import java.util.LinkedHashMap;
import java.util.Map;
import de.jformchecker.AttributeUtils;
import de.jformchecker.FormCheckerElement;
|
public static RadioInput build(String name, String keys[], String values[]) {
RadioInput si = RadioInput.build(name);
if (keys.length != values.length) {
throw new IllegalArgumentException("Key / Values with unequal lenght");
}
LinkedHashMap<String, String> possibleNames = new LinkedHashMap<>();
for (int i = 0; i < keys.length; i++) {
possibleNames.put(keys[i], values[i]);
}
si.setPossibleValues(possibleNames);
return si;
}
public String getInputTag(Map<String, String> attributes) {
StringBuilder inputTag = new StringBuilder();
possibleNames.forEach((key, value) -> {
// leer - bedeutet: Radio - Button ist optional, also nicht als
// radio ausgeben!
if (!"".equals(value)) {
inputTag.append(this.getInputTag(key, attributes) + " <label for=\"form-radio-" + name + "-" + key + "\" class=\""
+ "" + "\" id=\"label-" + name + "-" + key + "\">" + value + " </label>\n");
}
// do not increase tab-index:
// http://stackoverflow.com/questions/14322564/can-you-tab-through-all-radio-buttons
});
return inputTag.toString();
}
public String getInputTag(String curValue, Map<String, String> attributes) {
|
// Path: src/main/java/de/jformchecker/AttributeUtils.java
// public class AttributeUtils {
//
//
// public static String buildAttributes(Map<String, String> attributes) {
// StringBuilder attrStr = new StringBuilder();
// attributes.forEach((k,v) ->
// attrStr.append(AttributeUtils.buildSingleAttribute(k, attributes.get(k)))
// );
// return attrStr.toString();
// }
//
// public static String buildSingleAttribute(String key, String value) {
// StringBuilder attrStr = new StringBuilder();
// if (StringUtils.isEmpty(value)) {
// attrStr.append(key);
// } else {
// attrStr.append(key).append("=\"").append(value).append("\"");
// }
// attrStr.append(" ");
// return attrStr.toString();
// }
//
// public static String buildAttributes(TagAttributes attributes) {
// return AttributeUtils.buildAttributes(attributes.attributes);
// }
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
// Path: src/main/java/de/jformchecker/elements/RadioInput.java
import java.util.LinkedHashMap;
import java.util.Map;
import de.jformchecker.AttributeUtils;
import de.jformchecker.FormCheckerElement;
public static RadioInput build(String name, String keys[], String values[]) {
RadioInput si = RadioInput.build(name);
if (keys.length != values.length) {
throw new IllegalArgumentException("Key / Values with unequal lenght");
}
LinkedHashMap<String, String> possibleNames = new LinkedHashMap<>();
for (int i = 0; i < keys.length; i++) {
possibleNames.put(keys[i], values[i]);
}
si.setPossibleValues(possibleNames);
return si;
}
public String getInputTag(Map<String, String> attributes) {
StringBuilder inputTag = new StringBuilder();
possibleNames.forEach((key, value) -> {
// leer - bedeutet: Radio - Button ist optional, also nicht als
// radio ausgeben!
if (!"".equals(value)) {
inputTag.append(this.getInputTag(key, attributes) + " <label for=\"form-radio-" + name + "-" + key + "\" class=\""
+ "" + "\" id=\"label-" + name + "-" + key + "\">" + value + " </label>\n");
}
// do not increase tab-index:
// http://stackoverflow.com/questions/14322564/can-you-tab-through-all-radio-buttons
});
return inputTag.toString();
}
public String getInputTag(String curValue, Map<String, String> attributes) {
|
return "<input id=\"form-radio-" + name + "-" + curValue + "\" " + AttributeUtils.buildAttributes(attributes)
|
jochen777/jFormchecker
|
src/test/java/de/jformchecker/test/builders/CustomValidation.java
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
//
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java
// public class ValidationResult {
//
// boolean isValid = false;
//
// // caching:
// private static ValidationResult okResult = new ValidationResult(true, "", null, null);
//
// public boolean isValid() {
// return isValid;
// }
//
// public String getMessage() {
// return message;
// }
//
// public Object[] getErrorVals() {
// return errorVals;
// }
//
// String message;
// String translatedMessage;
// Object[] errorVals;
//
// public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) {
// this.isValid = isValid;
// this.message = message;
// this.errorVals = errorVals;
// this.translatedMessage = translatedMessage;
// }
//
// // factory methods
// public static ValidationResult of_(boolean isValid, String message, Object... errorVals) {
// return new ValidationResult(isValid, message, errorVals, null);
// }
//
// public static ValidationResult fail(String message, Object... errorVals) {
// return new ValidationResult(false, message, errorVals, null);
// }
//
// public static ValidationResult failWithTranslated(String message, Object... errorVals) {
// return new ValidationResult(false, null, errorVals, message);
// }
//
// public static ValidationResult failWithTranslated(String message) {
// return new ValidationResult(false, null, new Object[0], message);
// }
//
// public static ValidationResult ok() {
// // RFE: Could return always the same object! will reduce memory
// // footprint!
// return okResult;
// }
//
// public String getTranslatedMessage() {
// return translatedMessage;
// }
//
// }
|
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
import de.jformchecker.criteria.ValidationResult;
|
package de.jformchecker.test.builders;
public class CustomValidation implements Criterion {
@Override
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
//
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java
// public class ValidationResult {
//
// boolean isValid = false;
//
// // caching:
// private static ValidationResult okResult = new ValidationResult(true, "", null, null);
//
// public boolean isValid() {
// return isValid;
// }
//
// public String getMessage() {
// return message;
// }
//
// public Object[] getErrorVals() {
// return errorVals;
// }
//
// String message;
// String translatedMessage;
// Object[] errorVals;
//
// public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) {
// this.isValid = isValid;
// this.message = message;
// this.errorVals = errorVals;
// this.translatedMessage = translatedMessage;
// }
//
// // factory methods
// public static ValidationResult of_(boolean isValid, String message, Object... errorVals) {
// return new ValidationResult(isValid, message, errorVals, null);
// }
//
// public static ValidationResult fail(String message, Object... errorVals) {
// return new ValidationResult(false, message, errorVals, null);
// }
//
// public static ValidationResult failWithTranslated(String message, Object... errorVals) {
// return new ValidationResult(false, null, errorVals, message);
// }
//
// public static ValidationResult failWithTranslated(String message) {
// return new ValidationResult(false, null, new Object[0], message);
// }
//
// public static ValidationResult ok() {
// // RFE: Could return always the same object! will reduce memory
// // footprint!
// return okResult;
// }
//
// public String getTranslatedMessage() {
// return translatedMessage;
// }
//
// }
// Path: src/test/java/de/jformchecker/test/builders/CustomValidation.java
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
import de.jformchecker.criteria.ValidationResult;
package de.jformchecker.test.builders;
public class CustomValidation implements Criterion {
@Override
|
public ValidationResult validate(FormCheckerElement value) {
|
jochen777/jFormchecker
|
src/test/java/de/jformchecker/test/builders/CustomValidation.java
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
//
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java
// public class ValidationResult {
//
// boolean isValid = false;
//
// // caching:
// private static ValidationResult okResult = new ValidationResult(true, "", null, null);
//
// public boolean isValid() {
// return isValid;
// }
//
// public String getMessage() {
// return message;
// }
//
// public Object[] getErrorVals() {
// return errorVals;
// }
//
// String message;
// String translatedMessage;
// Object[] errorVals;
//
// public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) {
// this.isValid = isValid;
// this.message = message;
// this.errorVals = errorVals;
// this.translatedMessage = translatedMessage;
// }
//
// // factory methods
// public static ValidationResult of_(boolean isValid, String message, Object... errorVals) {
// return new ValidationResult(isValid, message, errorVals, null);
// }
//
// public static ValidationResult fail(String message, Object... errorVals) {
// return new ValidationResult(false, message, errorVals, null);
// }
//
// public static ValidationResult failWithTranslated(String message, Object... errorVals) {
// return new ValidationResult(false, null, errorVals, message);
// }
//
// public static ValidationResult failWithTranslated(String message) {
// return new ValidationResult(false, null, new Object[0], message);
// }
//
// public static ValidationResult ok() {
// // RFE: Could return always the same object! will reduce memory
// // footprint!
// return okResult;
// }
//
// public String getTranslatedMessage() {
// return translatedMessage;
// }
//
// }
|
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
import de.jformchecker.criteria.ValidationResult;
|
package de.jformchecker.test.builders;
public class CustomValidation implements Criterion {
@Override
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
//
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java
// public class ValidationResult {
//
// boolean isValid = false;
//
// // caching:
// private static ValidationResult okResult = new ValidationResult(true, "", null, null);
//
// public boolean isValid() {
// return isValid;
// }
//
// public String getMessage() {
// return message;
// }
//
// public Object[] getErrorVals() {
// return errorVals;
// }
//
// String message;
// String translatedMessage;
// Object[] errorVals;
//
// public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) {
// this.isValid = isValid;
// this.message = message;
// this.errorVals = errorVals;
// this.translatedMessage = translatedMessage;
// }
//
// // factory methods
// public static ValidationResult of_(boolean isValid, String message, Object... errorVals) {
// return new ValidationResult(isValid, message, errorVals, null);
// }
//
// public static ValidationResult fail(String message, Object... errorVals) {
// return new ValidationResult(false, message, errorVals, null);
// }
//
// public static ValidationResult failWithTranslated(String message, Object... errorVals) {
// return new ValidationResult(false, null, errorVals, message);
// }
//
// public static ValidationResult failWithTranslated(String message) {
// return new ValidationResult(false, null, new Object[0], message);
// }
//
// public static ValidationResult ok() {
// // RFE: Could return always the same object! will reduce memory
// // footprint!
// return okResult;
// }
//
// public String getTranslatedMessage() {
// return translatedMessage;
// }
//
// }
// Path: src/test/java/de/jformchecker/test/builders/CustomValidation.java
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
import de.jformchecker.criteria.ValidationResult;
package de.jformchecker.test.builders;
public class CustomValidation implements Criterion {
@Override
|
public ValidationResult validate(FormCheckerElement value) {
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/criteria/StartsWith.java
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
|
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
|
package de.jformchecker.criteria;
/**
* Checks if value starts with the given string.
*
* Based on work of armandino (at) gmail.com
*/
public final class StartsWith implements Criterion {
private String[] prefixes;
StartsWith(String... prefixes) {
this.prefixes = prefixes;
}
@Override
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
// Path: src/main/java/de/jformchecker/criteria/StartsWith.java
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
package de.jformchecker.criteria;
/**
* Checks if value starts with the given string.
*
* Based on work of armandino (at) gmail.com
*/
public final class StartsWith implements Criterion {
private String[] prefixes;
StartsWith(String... prefixes) {
this.prefixes = prefixes;
}
@Override
|
public ValidationResult validate(FormCheckerElement value) {
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/View.java
|
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java
// public class ValidationResult {
//
// boolean isValid = false;
//
// // caching:
// private static ValidationResult okResult = new ValidationResult(true, "", null, null);
//
// public boolean isValid() {
// return isValid;
// }
//
// public String getMessage() {
// return message;
// }
//
// public Object[] getErrorVals() {
// return errorVals;
// }
//
// String message;
// String translatedMessage;
// Object[] errorVals;
//
// public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) {
// this.isValid = isValid;
// this.message = message;
// this.errorVals = errorVals;
// this.translatedMessage = translatedMessage;
// }
//
// // factory methods
// public static ValidationResult of_(boolean isValid, String message, Object... errorVals) {
// return new ValidationResult(isValid, message, errorVals, null);
// }
//
// public static ValidationResult fail(String message, Object... errorVals) {
// return new ValidationResult(false, message, errorVals, null);
// }
//
// public static ValidationResult failWithTranslated(String message, Object... errorVals) {
// return new ValidationResult(false, null, errorVals, message);
// }
//
// public static ValidationResult failWithTranslated(String message) {
// return new ValidationResult(false, null, new Object[0], message);
// }
//
// public static ValidationResult ok() {
// // RFE: Could return always the same object! will reduce memory
// // footprint!
// return okResult;
// }
//
// public String getTranslatedMessage() {
// return translatedMessage;
// }
//
// }
|
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.jformchecker.criteria.ValidationResult;
|
// input-element via a macro!
public String getElement(String name) {
return formBuilder.generateHtmlForElement(fc.firstRun, fc.config.getProperties(), form.getElement(name), this.form.isHtml5Validation());
}
public List<String> getElementNames() {
List<String> elementNames = new ArrayList<>();
form.elements.forEach((elem) -> elementNames.add(elem.getName()));
return elementNames;
}
public String getInput(String name) {
return form.getElement(name).getInputTag();
}
public String getInput(String name, Map<String, String> map) {
return form.getElement(name).getInputTag(map);
}
public String getType(String name) {
return form.getElement(name).getType();
}
public boolean isError(String name) {
return !formBuilder.getErrors(form.getElement(name), fc.firstRun).isValid();
}
public String getError(String name) {
|
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java
// public class ValidationResult {
//
// boolean isValid = false;
//
// // caching:
// private static ValidationResult okResult = new ValidationResult(true, "", null, null);
//
// public boolean isValid() {
// return isValid;
// }
//
// public String getMessage() {
// return message;
// }
//
// public Object[] getErrorVals() {
// return errorVals;
// }
//
// String message;
// String translatedMessage;
// Object[] errorVals;
//
// public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) {
// this.isValid = isValid;
// this.message = message;
// this.errorVals = errorVals;
// this.translatedMessage = translatedMessage;
// }
//
// // factory methods
// public static ValidationResult of_(boolean isValid, String message, Object... errorVals) {
// return new ValidationResult(isValid, message, errorVals, null);
// }
//
// public static ValidationResult fail(String message, Object... errorVals) {
// return new ValidationResult(false, message, errorVals, null);
// }
//
// public static ValidationResult failWithTranslated(String message, Object... errorVals) {
// return new ValidationResult(false, null, errorVals, message);
// }
//
// public static ValidationResult failWithTranslated(String message) {
// return new ValidationResult(false, null, new Object[0], message);
// }
//
// public static ValidationResult ok() {
// // RFE: Could return always the same object! will reduce memory
// // footprint!
// return okResult;
// }
//
// public String getTranslatedMessage() {
// return translatedMessage;
// }
//
// }
// Path: src/main/java/de/jformchecker/View.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.jformchecker.criteria.ValidationResult;
// input-element via a macro!
public String getElement(String name) {
return formBuilder.generateHtmlForElement(fc.firstRun, fc.config.getProperties(), form.getElement(name), this.form.isHtml5Validation());
}
public List<String> getElementNames() {
List<String> elementNames = new ArrayList<>();
form.elements.forEach((elem) -> elementNames.add(elem.getName()));
return elementNames;
}
public String getInput(String name) {
return form.getElement(name).getInputTag();
}
public String getInput(String name, Map<String, String> map) {
return form.getElement(name).getInputTag(map);
}
public String getType(String name) {
return form.getElement(name).getType();
}
public boolean isError(String name) {
return !formBuilder.getErrors(form.getElement(name), fc.firstRun).isValid();
}
public String getError(String name) {
|
ValidationResult vr = formBuilder.getErrors(form.getElement(name), fc.firstRun);
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/criteria/And.java
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
|
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
|
package de.jformchecker.criteria;
/**
* Performs an <tt>AND</tt> over all criteria on the given value.
*
* Based on work of armandino (at) gmail.com
*/
public final class And implements Criterion {
private Criterion[] criteria;
And(Criterion... criteria) {
if (criteria.length < 2)
throw new IllegalArgumentException(getClass().getName() + " requires at least two criteria");
this.criteria = criteria;
}
@Override
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
// Path: src/main/java/de/jformchecker/criteria/And.java
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
package de.jformchecker.criteria;
/**
* Performs an <tt>AND</tt> over all criteria on the given value.
*
* Based on work of armandino (at) gmail.com
*/
public final class And implements Criterion {
private Criterion[] criteria;
And(Criterion... criteria) {
if (criteria.length < 2)
throw new IllegalArgumentException(getClass().getName() + " requires at least two criteria");
this.criteria = criteria;
}
@Override
|
public ValidationResult validate(FormCheckerElement value) {
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/criteria/Or.java
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
|
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
|
package de.jformchecker.criteria;
/**
* Performs an <tt>OR</tt> over all criteria on the given value.
*
* Based on work of armandino (at) gmail.com
*/
public final class Or implements Criterion {
private Criterion[] criteria;
Or(Criterion... criteria) {
if (criteria.length < 2)
throw new IllegalArgumentException(getClass().getName() + " requires at least two criteria");
this.criteria = criteria;
}
@Override
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
// Path: src/main/java/de/jformchecker/criteria/Or.java
import de.jformchecker.Criterion;
import de.jformchecker.FormCheckerElement;
package de.jformchecker.criteria;
/**
* Performs an <tt>OR</tt> over all criteria on the given value.
*
* Based on work of armandino (at) gmail.com
*/
public final class Or implements Criterion {
private Criterion[] criteria;
Or(Criterion... criteria) {
if (criteria.length < 2)
throw new IllegalArgumentException(getClass().getName() + " requires at least two criteria");
this.criteria = criteria;
}
@Override
|
public ValidationResult validate(FormCheckerElement value) {
|
jochen777/jFormchecker
|
src/test/java/de/jformchecker/test/CriteriaTests.java
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/criteria/Criteria.java
// public class Criteria {
// private static final Email email = new Email();
// private static final ZipCode zipCode = new ZipCode();
// private static final PostcodeCA postcodeCA = new PostcodeCA();
//
// public static Criterion and(Criterion... criteria) {
// return new And(criteria);
// }
//
// public static Criterion or(Criterion... criteria) {
// return new Or(criteria);
// }
//
// public static Criterion accept(String... values) {
// return new Accept(values);
// }
//
// public static AcceptString acceptString(String... values) {
// return new AcceptString(values);
// }
//
// public static Criterion min(int min) {
// return new Min(min);
// }
//
// public static Criterion max(int max) {
// return new Max(max);
// }
//
// public static Criterion number() {
// return new Number();
// }
//
// public static Criterion range(int min, int max) {
// return new Range(min, max);
// }
//
// public static Criterion length(int min, int max) {
// return new Length(min, max);
// }
//
// public static Criterion exactLength(int length) {
// return new ExactLength(length);
// }
//
// public static Criterion minLength(int min) {
// return new MinLength(min);
// }
//
// public static Criterion maxLength(int max) {
// return new MaxLength(max);
// }
//
// public static Criterion regex(String pattern) {
// return new Regex(pattern);
// }
//
// public static Criterion startsWith(String... prefix) {
// return new StartsWith(prefix);
// }
//
// public static Criterion emailAddress() {
// return email;
// }
//
// public static Criterion strongPassword(int minLength) {
// return new StrongPassword(minLength);
// }
//
// public static Criterion zipcode() {
// return zipCode;
// }
//
// public static Criterion postcodeCA() {
// return postcodeCA;
// }
//
// }
//
// Path: src/main/java/de/jformchecker/elements/TextInput.java
// public class TextInput extends AbstractInput<TextInput> implements FormCheckerElement {
//
// private String placeholderText = "";
//
// public static TextInput build(String name) {
// TextInput i = new TextInput();
// i.name = name;
// return i;
// }
//
// public TextInput setPlaceholerText(String placeholderText) {
// this.placeholderText = placeholderText;
// return this;
// }
//
// @Override
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) {
// TagAttributes tagAttributes = new TagAttributes(attributes);
// tagAttributes.add(this.inputAttributes);
// return String.format("<input " + buildAllAttributes(tagAttributes, messageSource, html5Validation) + buildMaxLen()
// + "type=\"text\" name=\"%s\" value=\"%s\"" + getPlaceholder() + ">", name,
// (value == null ? "" : getValueHtmlEncoded()));
// }
//
//
// protected String getPlaceholder() {
// return StringUtils.isEmpty(placeholderText) ? ""
// : " placeholder=\"" + Escape.htmlText(placeholderText) + "\"";
// }
//
// @Override
// public String getType() {
// return "text";
// }
//
//
// }
|
import org.junit.Assert;
import org.junit.Test;
import de.jformchecker.Criterion;
import de.jformchecker.criteria.Criteria;
import de.jformchecker.elements.TextInput;
|
package de.jformchecker.test;
/**
* Tests some criterias
*
* @author jochen
*
*/
public class CriteriaTests {
@Test
public void testMax() {
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/criteria/Criteria.java
// public class Criteria {
// private static final Email email = new Email();
// private static final ZipCode zipCode = new ZipCode();
// private static final PostcodeCA postcodeCA = new PostcodeCA();
//
// public static Criterion and(Criterion... criteria) {
// return new And(criteria);
// }
//
// public static Criterion or(Criterion... criteria) {
// return new Or(criteria);
// }
//
// public static Criterion accept(String... values) {
// return new Accept(values);
// }
//
// public static AcceptString acceptString(String... values) {
// return new AcceptString(values);
// }
//
// public static Criterion min(int min) {
// return new Min(min);
// }
//
// public static Criterion max(int max) {
// return new Max(max);
// }
//
// public static Criterion number() {
// return new Number();
// }
//
// public static Criterion range(int min, int max) {
// return new Range(min, max);
// }
//
// public static Criterion length(int min, int max) {
// return new Length(min, max);
// }
//
// public static Criterion exactLength(int length) {
// return new ExactLength(length);
// }
//
// public static Criterion minLength(int min) {
// return new MinLength(min);
// }
//
// public static Criterion maxLength(int max) {
// return new MaxLength(max);
// }
//
// public static Criterion regex(String pattern) {
// return new Regex(pattern);
// }
//
// public static Criterion startsWith(String... prefix) {
// return new StartsWith(prefix);
// }
//
// public static Criterion emailAddress() {
// return email;
// }
//
// public static Criterion strongPassword(int minLength) {
// return new StrongPassword(minLength);
// }
//
// public static Criterion zipcode() {
// return zipCode;
// }
//
// public static Criterion postcodeCA() {
// return postcodeCA;
// }
//
// }
//
// Path: src/main/java/de/jformchecker/elements/TextInput.java
// public class TextInput extends AbstractInput<TextInput> implements FormCheckerElement {
//
// private String placeholderText = "";
//
// public static TextInput build(String name) {
// TextInput i = new TextInput();
// i.name = name;
// return i;
// }
//
// public TextInput setPlaceholerText(String placeholderText) {
// this.placeholderText = placeholderText;
// return this;
// }
//
// @Override
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) {
// TagAttributes tagAttributes = new TagAttributes(attributes);
// tagAttributes.add(this.inputAttributes);
// return String.format("<input " + buildAllAttributes(tagAttributes, messageSource, html5Validation) + buildMaxLen()
// + "type=\"text\" name=\"%s\" value=\"%s\"" + getPlaceholder() + ">", name,
// (value == null ? "" : getValueHtmlEncoded()));
// }
//
//
// protected String getPlaceholder() {
// return StringUtils.isEmpty(placeholderText) ? ""
// : " placeholder=\"" + Escape.htmlText(placeholderText) + "\"";
// }
//
// @Override
// public String getType() {
// return "text";
// }
//
//
// }
// Path: src/test/java/de/jformchecker/test/CriteriaTests.java
import org.junit.Assert;
import org.junit.Test;
import de.jformchecker.Criterion;
import de.jformchecker.criteria.Criteria;
import de.jformchecker.elements.TextInput;
package de.jformchecker.test;
/**
* Tests some criterias
*
* @author jochen
*
*/
public class CriteriaTests {
@Test
public void testMax() {
|
Criterion c = Criteria.max(100);
|
jochen777/jFormchecker
|
src/test/java/de/jformchecker/test/CriteriaTests.java
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/criteria/Criteria.java
// public class Criteria {
// private static final Email email = new Email();
// private static final ZipCode zipCode = new ZipCode();
// private static final PostcodeCA postcodeCA = new PostcodeCA();
//
// public static Criterion and(Criterion... criteria) {
// return new And(criteria);
// }
//
// public static Criterion or(Criterion... criteria) {
// return new Or(criteria);
// }
//
// public static Criterion accept(String... values) {
// return new Accept(values);
// }
//
// public static AcceptString acceptString(String... values) {
// return new AcceptString(values);
// }
//
// public static Criterion min(int min) {
// return new Min(min);
// }
//
// public static Criterion max(int max) {
// return new Max(max);
// }
//
// public static Criterion number() {
// return new Number();
// }
//
// public static Criterion range(int min, int max) {
// return new Range(min, max);
// }
//
// public static Criterion length(int min, int max) {
// return new Length(min, max);
// }
//
// public static Criterion exactLength(int length) {
// return new ExactLength(length);
// }
//
// public static Criterion minLength(int min) {
// return new MinLength(min);
// }
//
// public static Criterion maxLength(int max) {
// return new MaxLength(max);
// }
//
// public static Criterion regex(String pattern) {
// return new Regex(pattern);
// }
//
// public static Criterion startsWith(String... prefix) {
// return new StartsWith(prefix);
// }
//
// public static Criterion emailAddress() {
// return email;
// }
//
// public static Criterion strongPassword(int minLength) {
// return new StrongPassword(minLength);
// }
//
// public static Criterion zipcode() {
// return zipCode;
// }
//
// public static Criterion postcodeCA() {
// return postcodeCA;
// }
//
// }
//
// Path: src/main/java/de/jformchecker/elements/TextInput.java
// public class TextInput extends AbstractInput<TextInput> implements FormCheckerElement {
//
// private String placeholderText = "";
//
// public static TextInput build(String name) {
// TextInput i = new TextInput();
// i.name = name;
// return i;
// }
//
// public TextInput setPlaceholerText(String placeholderText) {
// this.placeholderText = placeholderText;
// return this;
// }
//
// @Override
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) {
// TagAttributes tagAttributes = new TagAttributes(attributes);
// tagAttributes.add(this.inputAttributes);
// return String.format("<input " + buildAllAttributes(tagAttributes, messageSource, html5Validation) + buildMaxLen()
// + "type=\"text\" name=\"%s\" value=\"%s\"" + getPlaceholder() + ">", name,
// (value == null ? "" : getValueHtmlEncoded()));
// }
//
//
// protected String getPlaceholder() {
// return StringUtils.isEmpty(placeholderText) ? ""
// : " placeholder=\"" + Escape.htmlText(placeholderText) + "\"";
// }
//
// @Override
// public String getType() {
// return "text";
// }
//
//
// }
|
import org.junit.Assert;
import org.junit.Test;
import de.jformchecker.Criterion;
import de.jformchecker.criteria.Criteria;
import de.jformchecker.elements.TextInput;
|
package de.jformchecker.test;
/**
* Tests some criterias
*
* @author jochen
*
*/
public class CriteriaTests {
@Test
public void testMax() {
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/criteria/Criteria.java
// public class Criteria {
// private static final Email email = new Email();
// private static final ZipCode zipCode = new ZipCode();
// private static final PostcodeCA postcodeCA = new PostcodeCA();
//
// public static Criterion and(Criterion... criteria) {
// return new And(criteria);
// }
//
// public static Criterion or(Criterion... criteria) {
// return new Or(criteria);
// }
//
// public static Criterion accept(String... values) {
// return new Accept(values);
// }
//
// public static AcceptString acceptString(String... values) {
// return new AcceptString(values);
// }
//
// public static Criterion min(int min) {
// return new Min(min);
// }
//
// public static Criterion max(int max) {
// return new Max(max);
// }
//
// public static Criterion number() {
// return new Number();
// }
//
// public static Criterion range(int min, int max) {
// return new Range(min, max);
// }
//
// public static Criterion length(int min, int max) {
// return new Length(min, max);
// }
//
// public static Criterion exactLength(int length) {
// return new ExactLength(length);
// }
//
// public static Criterion minLength(int min) {
// return new MinLength(min);
// }
//
// public static Criterion maxLength(int max) {
// return new MaxLength(max);
// }
//
// public static Criterion regex(String pattern) {
// return new Regex(pattern);
// }
//
// public static Criterion startsWith(String... prefix) {
// return new StartsWith(prefix);
// }
//
// public static Criterion emailAddress() {
// return email;
// }
//
// public static Criterion strongPassword(int minLength) {
// return new StrongPassword(minLength);
// }
//
// public static Criterion zipcode() {
// return zipCode;
// }
//
// public static Criterion postcodeCA() {
// return postcodeCA;
// }
//
// }
//
// Path: src/main/java/de/jformchecker/elements/TextInput.java
// public class TextInput extends AbstractInput<TextInput> implements FormCheckerElement {
//
// private String placeholderText = "";
//
// public static TextInput build(String name) {
// TextInput i = new TextInput();
// i.name = name;
// return i;
// }
//
// public TextInput setPlaceholerText(String placeholderText) {
// this.placeholderText = placeholderText;
// return this;
// }
//
// @Override
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) {
// TagAttributes tagAttributes = new TagAttributes(attributes);
// tagAttributes.add(this.inputAttributes);
// return String.format("<input " + buildAllAttributes(tagAttributes, messageSource, html5Validation) + buildMaxLen()
// + "type=\"text\" name=\"%s\" value=\"%s\"" + getPlaceholder() + ">", name,
// (value == null ? "" : getValueHtmlEncoded()));
// }
//
//
// protected String getPlaceholder() {
// return StringUtils.isEmpty(placeholderText) ? ""
// : " placeholder=\"" + Escape.htmlText(placeholderText) + "\"";
// }
//
// @Override
// public String getType() {
// return "text";
// }
//
//
// }
// Path: src/test/java/de/jformchecker/test/CriteriaTests.java
import org.junit.Assert;
import org.junit.Test;
import de.jformchecker.Criterion;
import de.jformchecker.criteria.Criteria;
import de.jformchecker.elements.TextInput;
package de.jformchecker.test;
/**
* Tests some criterias
*
* @author jochen
*
*/
public class CriteriaTests {
@Test
public void testMax() {
|
Criterion c = Criteria.max(100);
|
jochen777/jFormchecker
|
src/test/java/de/jformchecker/test/CriteriaTests.java
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/criteria/Criteria.java
// public class Criteria {
// private static final Email email = new Email();
// private static final ZipCode zipCode = new ZipCode();
// private static final PostcodeCA postcodeCA = new PostcodeCA();
//
// public static Criterion and(Criterion... criteria) {
// return new And(criteria);
// }
//
// public static Criterion or(Criterion... criteria) {
// return new Or(criteria);
// }
//
// public static Criterion accept(String... values) {
// return new Accept(values);
// }
//
// public static AcceptString acceptString(String... values) {
// return new AcceptString(values);
// }
//
// public static Criterion min(int min) {
// return new Min(min);
// }
//
// public static Criterion max(int max) {
// return new Max(max);
// }
//
// public static Criterion number() {
// return new Number();
// }
//
// public static Criterion range(int min, int max) {
// return new Range(min, max);
// }
//
// public static Criterion length(int min, int max) {
// return new Length(min, max);
// }
//
// public static Criterion exactLength(int length) {
// return new ExactLength(length);
// }
//
// public static Criterion minLength(int min) {
// return new MinLength(min);
// }
//
// public static Criterion maxLength(int max) {
// return new MaxLength(max);
// }
//
// public static Criterion regex(String pattern) {
// return new Regex(pattern);
// }
//
// public static Criterion startsWith(String... prefix) {
// return new StartsWith(prefix);
// }
//
// public static Criterion emailAddress() {
// return email;
// }
//
// public static Criterion strongPassword(int minLength) {
// return new StrongPassword(minLength);
// }
//
// public static Criterion zipcode() {
// return zipCode;
// }
//
// public static Criterion postcodeCA() {
// return postcodeCA;
// }
//
// }
//
// Path: src/main/java/de/jformchecker/elements/TextInput.java
// public class TextInput extends AbstractInput<TextInput> implements FormCheckerElement {
//
// private String placeholderText = "";
//
// public static TextInput build(String name) {
// TextInput i = new TextInput();
// i.name = name;
// return i;
// }
//
// public TextInput setPlaceholerText(String placeholderText) {
// this.placeholderText = placeholderText;
// return this;
// }
//
// @Override
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) {
// TagAttributes tagAttributes = new TagAttributes(attributes);
// tagAttributes.add(this.inputAttributes);
// return String.format("<input " + buildAllAttributes(tagAttributes, messageSource, html5Validation) + buildMaxLen()
// + "type=\"text\" name=\"%s\" value=\"%s\"" + getPlaceholder() + ">", name,
// (value == null ? "" : getValueHtmlEncoded()));
// }
//
//
// protected String getPlaceholder() {
// return StringUtils.isEmpty(placeholderText) ? ""
// : " placeholder=\"" + Escape.htmlText(placeholderText) + "\"";
// }
//
// @Override
// public String getType() {
// return "text";
// }
//
//
// }
|
import org.junit.Assert;
import org.junit.Test;
import de.jformchecker.Criterion;
import de.jformchecker.criteria.Criteria;
import de.jformchecker.elements.TextInput;
|
package de.jformchecker.test;
/**
* Tests some criterias
*
* @author jochen
*
*/
public class CriteriaTests {
@Test
public void testMax() {
Criterion c = Criteria.max(100);
Assert.assertTrue("30 is smaller than 100. This should be true!", c.validate(buildSampleInput(30)).isValid());
}
@Test
public void testMin() {
Criterion c = Criteria.min(100);
Assert.assertTrue("110 is bigger than 100. This should be true!", c.validate(buildSampleInput(110)).isValid());
}
@Test
public void testStrongPassword() {
Criterion c = Criteria.strongPassword(15);
Assert.assertTrue("This password should be strong enough",
c.validate(buildSampleInput("abcAd4bcas!fegdt")).isValid());
}
@Test
public void testEmail() {
Criterion c = Criteria.emailAddress();
String goodEmail = "test@test.de";
Assert.assertTrue("This Email should be valid: " + goodEmail,
c.validate(buildSampleInput(goodEmail)).isValid());
String badEmail = "asdf@asdfkd@l.de";
Assert.assertTrue("This Email should be not valid: " + badEmail,
!(c.validate(buildSampleInput(badEmail)).isValid()));
}
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
//
// Path: src/main/java/de/jformchecker/criteria/Criteria.java
// public class Criteria {
// private static final Email email = new Email();
// private static final ZipCode zipCode = new ZipCode();
// private static final PostcodeCA postcodeCA = new PostcodeCA();
//
// public static Criterion and(Criterion... criteria) {
// return new And(criteria);
// }
//
// public static Criterion or(Criterion... criteria) {
// return new Or(criteria);
// }
//
// public static Criterion accept(String... values) {
// return new Accept(values);
// }
//
// public static AcceptString acceptString(String... values) {
// return new AcceptString(values);
// }
//
// public static Criterion min(int min) {
// return new Min(min);
// }
//
// public static Criterion max(int max) {
// return new Max(max);
// }
//
// public static Criterion number() {
// return new Number();
// }
//
// public static Criterion range(int min, int max) {
// return new Range(min, max);
// }
//
// public static Criterion length(int min, int max) {
// return new Length(min, max);
// }
//
// public static Criterion exactLength(int length) {
// return new ExactLength(length);
// }
//
// public static Criterion minLength(int min) {
// return new MinLength(min);
// }
//
// public static Criterion maxLength(int max) {
// return new MaxLength(max);
// }
//
// public static Criterion regex(String pattern) {
// return new Regex(pattern);
// }
//
// public static Criterion startsWith(String... prefix) {
// return new StartsWith(prefix);
// }
//
// public static Criterion emailAddress() {
// return email;
// }
//
// public static Criterion strongPassword(int minLength) {
// return new StrongPassword(minLength);
// }
//
// public static Criterion zipcode() {
// return zipCode;
// }
//
// public static Criterion postcodeCA() {
// return postcodeCA;
// }
//
// }
//
// Path: src/main/java/de/jformchecker/elements/TextInput.java
// public class TextInput extends AbstractInput<TextInput> implements FormCheckerElement {
//
// private String placeholderText = "";
//
// public static TextInput build(String name) {
// TextInput i = new TextInput();
// i.name = name;
// return i;
// }
//
// public TextInput setPlaceholerText(String placeholderText) {
// this.placeholderText = placeholderText;
// return this;
// }
//
// @Override
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) {
// TagAttributes tagAttributes = new TagAttributes(attributes);
// tagAttributes.add(this.inputAttributes);
// return String.format("<input " + buildAllAttributes(tagAttributes, messageSource, html5Validation) + buildMaxLen()
// + "type=\"text\" name=\"%s\" value=\"%s\"" + getPlaceholder() + ">", name,
// (value == null ? "" : getValueHtmlEncoded()));
// }
//
//
// protected String getPlaceholder() {
// return StringUtils.isEmpty(placeholderText) ? ""
// : " placeholder=\"" + Escape.htmlText(placeholderText) + "\"";
// }
//
// @Override
// public String getType() {
// return "text";
// }
//
//
// }
// Path: src/test/java/de/jformchecker/test/CriteriaTests.java
import org.junit.Assert;
import org.junit.Test;
import de.jformchecker.Criterion;
import de.jformchecker.criteria.Criteria;
import de.jformchecker.elements.TextInput;
package de.jformchecker.test;
/**
* Tests some criterias
*
* @author jochen
*
*/
public class CriteriaTests {
@Test
public void testMax() {
Criterion c = Criteria.max(100);
Assert.assertTrue("30 is smaller than 100. This should be true!", c.validate(buildSampleInput(30)).isValid());
}
@Test
public void testMin() {
Criterion c = Criteria.min(100);
Assert.assertTrue("110 is bigger than 100. This should be true!", c.validate(buildSampleInput(110)).isValid());
}
@Test
public void testStrongPassword() {
Criterion c = Criteria.strongPassword(15);
Assert.assertTrue("This password should be strong enough",
c.validate(buildSampleInput("abcAd4bcas!fegdt")).isValid());
}
@Test
public void testEmail() {
Criterion c = Criteria.emailAddress();
String goodEmail = "test@test.de";
Assert.assertTrue("This Email should be valid: " + goodEmail,
c.validate(buildSampleInput(goodEmail)).isValid());
String badEmail = "asdf@asdfkd@l.de";
Assert.assertTrue("This Email should be not valid: " + badEmail,
!(c.validate(buildSampleInput(badEmail)).isValid()));
}
|
private TextInput buildSampleInput(int val) {
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/elements/LongTextInput.java
|
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
//
// Path: src/main/java/de/jformchecker/TagAttributes.java
// public class TagAttributes {
//
// // conveniance methods
// public static TagAttributes of(String key, String value) {
// return new TagAttributes(key, value);
// }
//
// public static TagAttributes of(Map<String, String> attribs) {
// return new TagAttributes(attribs);
// }
//
// LinkedHashMap<String, String> attributes;
//
// public TagAttributes(Map<String, String> attribs) {
// attributes = new LinkedHashMap<>(attribs);
// }
//
// public TagAttributes(LinkedHashMap<String, String> attribs) {
// attributes = attribs;
// }
//
// public TagAttributes() {
// this(new LinkedHashMap<>());
// }
//
// public TagAttributes(String key, String value) {
// this();
// this.put(key, value);
// }
//
// public TagAttributes put(String key, String value) {
// attributes.put(key, value);
// return this;
// }
//
// public String get(String key) {
// return attributes.get(key);
// }
//
// public void addToAttribute(String key, String value) {
// if (!attributes.containsKey(key)) {
// attributes.put(key, value);
// } else {
// attributes.put(key, attributes.get(key) + value);
// }
// }
//
// public Set<String> keySet() {
// return attributes.keySet();
// }
//
// public Map<String, String> getAttributes() {
// return attributes;
// }
//
// public void add(TagAttributes formAttributes) {
// if (formAttributes != null) {
// formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// public void add(LinkedHashMap<String, String> attribs) {
// if (attribs != null) {
// attribs.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// }
//
// Path: src/main/java/de/jformchecker/message/MessageSource.java
// @FunctionalInterface
// public interface MessageSource {
//
// public String getMessage(String key);
//
// public default String getSafeMessage(String key) {
// try {
// String msg = this.getMessage(key);
// return msg;
// } catch (Exception e) {
// return "??" + key + "??";
// }
// }
//
//
// public default String getMessage(ValidationResult vr) {
// // give translated messages higher prio than message-keys
// if (vr.getTranslatedMessage() != null) {
// return vr.getTranslatedMessage();
// } else
// if (vr.getMessage() != null) {
// return(String.format(this.getSafeMessage(
// vr.getMessage()
// ), vr.getErrorVals()));
//
// } else {
// throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text");
// }
// }
//
// }
|
import java.util.Map;
import de.jformchecker.FormCheckerElement;
import de.jformchecker.TagAttributes;
import de.jformchecker.message.MessageSource;
|
package de.jformchecker.elements;
public class LongTextInput extends TextInput implements FormCheckerElement {
public static LongTextInput build(String name) {
LongTextInput i = new LongTextInput();
i.name = name;
return i;
}
@Override
|
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
//
// Path: src/main/java/de/jformchecker/TagAttributes.java
// public class TagAttributes {
//
// // conveniance methods
// public static TagAttributes of(String key, String value) {
// return new TagAttributes(key, value);
// }
//
// public static TagAttributes of(Map<String, String> attribs) {
// return new TagAttributes(attribs);
// }
//
// LinkedHashMap<String, String> attributes;
//
// public TagAttributes(Map<String, String> attribs) {
// attributes = new LinkedHashMap<>(attribs);
// }
//
// public TagAttributes(LinkedHashMap<String, String> attribs) {
// attributes = attribs;
// }
//
// public TagAttributes() {
// this(new LinkedHashMap<>());
// }
//
// public TagAttributes(String key, String value) {
// this();
// this.put(key, value);
// }
//
// public TagAttributes put(String key, String value) {
// attributes.put(key, value);
// return this;
// }
//
// public String get(String key) {
// return attributes.get(key);
// }
//
// public void addToAttribute(String key, String value) {
// if (!attributes.containsKey(key)) {
// attributes.put(key, value);
// } else {
// attributes.put(key, attributes.get(key) + value);
// }
// }
//
// public Set<String> keySet() {
// return attributes.keySet();
// }
//
// public Map<String, String> getAttributes() {
// return attributes;
// }
//
// public void add(TagAttributes formAttributes) {
// if (formAttributes != null) {
// formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// public void add(LinkedHashMap<String, String> attribs) {
// if (attribs != null) {
// attribs.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// }
//
// Path: src/main/java/de/jformchecker/message/MessageSource.java
// @FunctionalInterface
// public interface MessageSource {
//
// public String getMessage(String key);
//
// public default String getSafeMessage(String key) {
// try {
// String msg = this.getMessage(key);
// return msg;
// } catch (Exception e) {
// return "??" + key + "??";
// }
// }
//
//
// public default String getMessage(ValidationResult vr) {
// // give translated messages higher prio than message-keys
// if (vr.getTranslatedMessage() != null) {
// return vr.getTranslatedMessage();
// } else
// if (vr.getMessage() != null) {
// return(String.format(this.getSafeMessage(
// vr.getMessage()
// ), vr.getErrorVals()));
//
// } else {
// throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text");
// }
// }
//
// }
// Path: src/main/java/de/jformchecker/elements/LongTextInput.java
import java.util.Map;
import de.jformchecker.FormCheckerElement;
import de.jformchecker.TagAttributes;
import de.jformchecker.message.MessageSource;
package de.jformchecker.elements;
public class LongTextInput extends TextInput implements FormCheckerElement {
public static LongTextInput build(String name) {
LongTextInput i = new LongTextInput();
i.name = name;
return i;
}
@Override
|
public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) {
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/criteria/AcceptString.java
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
|
import de.jformchecker.Criterion;
|
package de.jformchecker.criteria;
/**
* Checks if string is equal to one of the passed in strings.
*
* Based on work of armandino (at) gmail.com
*/
public final class AcceptString extends Accept {
private boolean caseSensitive = true;
AcceptString(String... values) {
super(values);
}
protected boolean areEqual(String v1, String v2) {
if (caseSensitive)
return super.areEqual(v1, v2);
return v1.equalsIgnoreCase(v2);
}
/**
* Specifies string comparison to be case-insensitive.
*/
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
// Path: src/main/java/de/jformchecker/criteria/AcceptString.java
import de.jformchecker.Criterion;
package de.jformchecker.criteria;
/**
* Checks if string is equal to one of the passed in strings.
*
* Based on work of armandino (at) gmail.com
*/
public final class AcceptString extends Accept {
private boolean caseSensitive = true;
AcceptString(String... values) {
super(values);
}
protected boolean areEqual(String v1, String v2) {
if (caseSensitive)
return super.areEqual(v1, v2);
return v1.equalsIgnoreCase(v2);
}
/**
* Specifies string comparison to be case-insensitive.
*/
|
public Criterion ignoreCase() {
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/validator/EmptyFormValidator.java
|
// Path: src/main/java/de/jformchecker/FormCheckerForm.java
// public abstract class FormCheckerForm {
//
// List<FormCheckerElement> elements = new ArrayList<>();
// List<FormValidator> validators = new ArrayList<>();
// private Map<String, FormCheckerElement> fastAccess = new LinkedHashMap<>();
// String submitLabel = "OK";
// private MessageSource messageSource;
//
// boolean protectedAgainstCSRF = false;
// boolean showSubmitButton = true;
//
// SessionSet sessionSet;
// SessionGet sessionGet;
//
// String id="id"; // default
//
// boolean html5Validation = true;
//
// Method method = Method.POST;
//
//
// public String getSubmitLabel() {
// return submitLabel;
// }
//
//
// public void setSubmitLabel(String submitLabel) {
// this.submitLabel = submitLabel;
// }
//
// private TagAttributes formTagAttributes = new TagAttributes();
//
// public TagAttributes getFormTagAttributes() {
// return formTagAttributes;
// }
//
// public void setFormTagAttributes(LinkedHashMap<String, String> formTagAttributes) {
// this.formTagAttributes = new TagAttributes(formTagAttributes);
// }
//
// public Map<String, FormCheckerElement> getElementsAsMap() {
// return fastAccess;
// }
//
//
//
// // Should be overriden
// public abstract void init();
//
// public void disableHtml5Validation() {
// html5Validation = false;
// }
//
// public List<FormValidator> getValidators() {
// return validators;
// }
//
// public FormCheckerForm add(FormCheckerElement elem) {
// // RFE: Exception, if elem is added twice!
// elements.add(elem);
// fastAccess.put(elem.getName(), elem);
// return this;
// }
//
// public List<FormCheckerElement> getElements() {
// return elements;
// }
//
// public FormCheckerForm addFormValidator(FormValidator formValidator) {
// validators.add(formValidator);
// return this;
// }
//
// public FormCheckerElement getElement(String name) {
// return fastAccess.get(name);
// }
//
//
// public MessageSource getMessageSource() {
// return messageSource;
// }
//
//
// public void setMessageSource(MessageSource messageSource) {
// this.messageSource = messageSource;
// }
//
//
// public boolean isProtectedAgainstCSRF() {
// return protectedAgainstCSRF;
// }
//
//
// public void setProtectedAgainstCSRF(boolean protectedAgainstCSRF) {
// this.protectedAgainstCSRF = protectedAgainstCSRF;
// }
//
//
// public SessionGet getSessionGet() {
// return sessionGet;
// }
//
//
// public void setSessionGet(SessionGet sessionGet) {
// this.sessionGet = sessionGet;
// }
//
//
// public SessionSet getSessionSet() {
// return sessionSet;
// }
//
//
// public void setSessionSet(SessionSet sessionSet) {
// this.sessionSet = sessionSet;
// }
//
//
// public String getId() {
// return id;
// }
//
//
// public void setId(String id) {
// this.id = id;
// }
//
// public enum Method {
// POST, GET
// }
//
// public Method getMethod() {
// return method;
// }
//
//
// public void setMethod(Method method) {
// this.method = method;
// }
//
//
// public void hideSubmitButton() {
// this.showSubmitButton = false;
// }
//
//
// public boolean isShowSubmitButton() {
// return this.showSubmitButton;
// }
//
//
// public boolean isHtml5Validation() {
// return html5Validation;
// }
//
// }
//
// Path: src/main/java/de/jformchecker/FormValidator.java
// @FunctionalInterface
// public interface FormValidator {
// /**
// * checks a complete form.
// * If something is invalid, return false. If everything is okay, return true
// * @param form
// * @return
// */
// public boolean validate(FormCheckerForm form);
// }
|
import de.jformchecker.FormCheckerForm;
import de.jformchecker.FormValidator;
|
package de.jformchecker.validator;
public class EmptyFormValidator implements FormValidator {
@Override
|
// Path: src/main/java/de/jformchecker/FormCheckerForm.java
// public abstract class FormCheckerForm {
//
// List<FormCheckerElement> elements = new ArrayList<>();
// List<FormValidator> validators = new ArrayList<>();
// private Map<String, FormCheckerElement> fastAccess = new LinkedHashMap<>();
// String submitLabel = "OK";
// private MessageSource messageSource;
//
// boolean protectedAgainstCSRF = false;
// boolean showSubmitButton = true;
//
// SessionSet sessionSet;
// SessionGet sessionGet;
//
// String id="id"; // default
//
// boolean html5Validation = true;
//
// Method method = Method.POST;
//
//
// public String getSubmitLabel() {
// return submitLabel;
// }
//
//
// public void setSubmitLabel(String submitLabel) {
// this.submitLabel = submitLabel;
// }
//
// private TagAttributes formTagAttributes = new TagAttributes();
//
// public TagAttributes getFormTagAttributes() {
// return formTagAttributes;
// }
//
// public void setFormTagAttributes(LinkedHashMap<String, String> formTagAttributes) {
// this.formTagAttributes = new TagAttributes(formTagAttributes);
// }
//
// public Map<String, FormCheckerElement> getElementsAsMap() {
// return fastAccess;
// }
//
//
//
// // Should be overriden
// public abstract void init();
//
// public void disableHtml5Validation() {
// html5Validation = false;
// }
//
// public List<FormValidator> getValidators() {
// return validators;
// }
//
// public FormCheckerForm add(FormCheckerElement elem) {
// // RFE: Exception, if elem is added twice!
// elements.add(elem);
// fastAccess.put(elem.getName(), elem);
// return this;
// }
//
// public List<FormCheckerElement> getElements() {
// return elements;
// }
//
// public FormCheckerForm addFormValidator(FormValidator formValidator) {
// validators.add(formValidator);
// return this;
// }
//
// public FormCheckerElement getElement(String name) {
// return fastAccess.get(name);
// }
//
//
// public MessageSource getMessageSource() {
// return messageSource;
// }
//
//
// public void setMessageSource(MessageSource messageSource) {
// this.messageSource = messageSource;
// }
//
//
// public boolean isProtectedAgainstCSRF() {
// return protectedAgainstCSRF;
// }
//
//
// public void setProtectedAgainstCSRF(boolean protectedAgainstCSRF) {
// this.protectedAgainstCSRF = protectedAgainstCSRF;
// }
//
//
// public SessionGet getSessionGet() {
// return sessionGet;
// }
//
//
// public void setSessionGet(SessionGet sessionGet) {
// this.sessionGet = sessionGet;
// }
//
//
// public SessionSet getSessionSet() {
// return sessionSet;
// }
//
//
// public void setSessionSet(SessionSet sessionSet) {
// this.sessionSet = sessionSet;
// }
//
//
// public String getId() {
// return id;
// }
//
//
// public void setId(String id) {
// this.id = id;
// }
//
// public enum Method {
// POST, GET
// }
//
// public Method getMethod() {
// return method;
// }
//
//
// public void setMethod(Method method) {
// this.method = method;
// }
//
//
// public void hideSubmitButton() {
// this.showSubmitButton = false;
// }
//
//
// public boolean isShowSubmitButton() {
// return this.showSubmitButton;
// }
//
//
// public boolean isHtml5Validation() {
// return html5Validation;
// }
//
// }
//
// Path: src/main/java/de/jformchecker/FormValidator.java
// @FunctionalInterface
// public interface FormValidator {
// /**
// * checks a complete form.
// * If something is invalid, return false. If everything is okay, return true
// * @param form
// * @return
// */
// public boolean validate(FormCheckerForm form);
// }
// Path: src/main/java/de/jformchecker/validator/EmptyFormValidator.java
import de.jformchecker.FormCheckerForm;
import de.jformchecker.FormValidator;
package de.jformchecker.validator;
public class EmptyFormValidator implements FormValidator {
@Override
|
public boolean validate(FormCheckerForm form) {
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/criteria/Criteria.java
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
|
import de.jformchecker.Criterion;
|
package de.jformchecker.criteria;
/**
* A collection of static methods to create commonly used criteria.
*
* Based on work of armandino (at) gmail.com
*/
public class Criteria {
private static final Email email = new Email();
private static final ZipCode zipCode = new ZipCode();
private static final PostcodeCA postcodeCA = new PostcodeCA();
|
// Path: src/main/java/de/jformchecker/Criterion.java
// @FunctionalInterface
// public interface Criterion {
// /**
// * Tests whether the specified value satisfies this criterion.
// *
// * @param value
// * to be tested against this criterion.
// * @return a ValidationResult which holds true or false for validaton result
// * and a potential errormsg
// */
// public ValidationResult validate(FormCheckerElement value);
//
// }
// Path: src/main/java/de/jformchecker/criteria/Criteria.java
import de.jformchecker.Criterion;
package de.jformchecker.criteria;
/**
* A collection of static methods to create commonly used criteria.
*
* Based on work of armandino (at) gmail.com
*/
public class Criteria {
private static final Email email = new Email();
private static final ZipCode zipCode = new ZipCode();
private static final PostcodeCA postcodeCA = new PostcodeCA();
|
public static Criterion and(Criterion... criteria) {
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/elements/FileUploadInput.java
|
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
//
// Path: src/main/java/de/jformchecker/TagAttributes.java
// public class TagAttributes {
//
// // conveniance methods
// public static TagAttributes of(String key, String value) {
// return new TagAttributes(key, value);
// }
//
// public static TagAttributes of(Map<String, String> attribs) {
// return new TagAttributes(attribs);
// }
//
// LinkedHashMap<String, String> attributes;
//
// public TagAttributes(Map<String, String> attribs) {
// attributes = new LinkedHashMap<>(attribs);
// }
//
// public TagAttributes(LinkedHashMap<String, String> attribs) {
// attributes = attribs;
// }
//
// public TagAttributes() {
// this(new LinkedHashMap<>());
// }
//
// public TagAttributes(String key, String value) {
// this();
// this.put(key, value);
// }
//
// public TagAttributes put(String key, String value) {
// attributes.put(key, value);
// return this;
// }
//
// public String get(String key) {
// return attributes.get(key);
// }
//
// public void addToAttribute(String key, String value) {
// if (!attributes.containsKey(key)) {
// attributes.put(key, value);
// } else {
// attributes.put(key, attributes.get(key) + value);
// }
// }
//
// public Set<String> keySet() {
// return attributes.keySet();
// }
//
// public Map<String, String> getAttributes() {
// return attributes;
// }
//
// public void add(TagAttributes formAttributes) {
// if (formAttributes != null) {
// formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// public void add(LinkedHashMap<String, String> attribs) {
// if (attribs != null) {
// attribs.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// }
|
import java.util.Map;
import de.jformchecker.FormCheckerElement;
import de.jformchecker.TagAttributes;
|
package de.jformchecker.elements;
public class FileUploadInput extends AbstractInput<FileUploadInput> implements FormCheckerElement {
public static FileUploadInput build(String name) {
FileUploadInput i = new FileUploadInput();
i.name = name;
return i;
}
@Override
public String getInputTag(Map<String, String> attributes) {
|
// Path: src/main/java/de/jformchecker/FormCheckerElement.java
// public interface FormCheckerElement {
//
// // RFE: check, if some methods can be protected
//
// // get internal name of this input-element
// public String getName();
//
// // set internal name
// public void setName(String name);
//
//
// // get the value that the user entered
// public String getValue();
//
// // get the value that the user entered, but html-encoded
// @Deprecated
// public String getValueHtmlEncoded();
//
// public void setValue(String value);
//
// public String getPreSetValue();
//
// // set an initial value to the element, before the user edited it.
// public <T extends FormCheckerElement> T setPreSetValue(String value);
//
// public <T extends FormCheckerElement> T setTabIndex(int tabIndex);
//
// public int getTabIndex();
//
// public int getLastTabIndex();
//
// // set the test in the label (builder pattern)
//
// public <T extends FormCheckerElement> T setDescription(String desc);
//
// // as "setDescription" but does not return anything (no builder pattern)
// public void changeDescription(String desc);
//
// public String getDescription();
//
// // returns true if element is valid
// public boolean isValid();
//
// public void setInvalid();
//
// // inits the value with the current http-request
// public void init(Request req, boolean firstrun, Validator validator);
//
// public ValidationResult getValidationResult();
//
// public void setValidationResult(ValidationResult validationResult);
//
// public String getInputTag();
//
// public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
//
// @Deprecated
// public String getInputTag(Map<String, String> attributes);
//
// public boolean isRequired();
//
// public <T extends FormCheckerElement> T setRequired();
//
// public List<Criterion> getCriteria();
//
// public void setFormChecker(FormChecker fc);
//
// // returns the complete label-html tag
// public String getLabel();
//
// // returns the label-html and the input-html
// public String getCompleteInput(); // RFE: Perhaps toString makes this even
// // more convenient?!
//
// public String getHelpText();
//
// // sets the size attribute
// public <T extends FormCheckerElement> T setSize(int size);
//
// public String getType();
//
// }
//
// Path: src/main/java/de/jformchecker/TagAttributes.java
// public class TagAttributes {
//
// // conveniance methods
// public static TagAttributes of(String key, String value) {
// return new TagAttributes(key, value);
// }
//
// public static TagAttributes of(Map<String, String> attribs) {
// return new TagAttributes(attribs);
// }
//
// LinkedHashMap<String, String> attributes;
//
// public TagAttributes(Map<String, String> attribs) {
// attributes = new LinkedHashMap<>(attribs);
// }
//
// public TagAttributes(LinkedHashMap<String, String> attribs) {
// attributes = attribs;
// }
//
// public TagAttributes() {
// this(new LinkedHashMap<>());
// }
//
// public TagAttributes(String key, String value) {
// this();
// this.put(key, value);
// }
//
// public TagAttributes put(String key, String value) {
// attributes.put(key, value);
// return this;
// }
//
// public String get(String key) {
// return attributes.get(key);
// }
//
// public void addToAttribute(String key, String value) {
// if (!attributes.containsKey(key)) {
// attributes.put(key, value);
// } else {
// attributes.put(key, attributes.get(key) + value);
// }
// }
//
// public Set<String> keySet() {
// return attributes.keySet();
// }
//
// public Map<String, String> getAttributes() {
// return attributes;
// }
//
// public void add(TagAttributes formAttributes) {
// if (formAttributes != null) {
// formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// public void add(LinkedHashMap<String, String> attribs) {
// if (attribs != null) {
// attribs.forEach((key, value) -> this.addToAttribute(key, value));
// }
// }
//
// }
// Path: src/main/java/de/jformchecker/elements/FileUploadInput.java
import java.util.Map;
import de.jformchecker.FormCheckerElement;
import de.jformchecker.TagAttributes;
package de.jformchecker.elements;
public class FileUploadInput extends AbstractInput<FileUploadInput> implements FormCheckerElement {
public static FileUploadInput build(String name) {
FileUploadInput i = new FileUploadInput();
i.name = name;
return i;
}
@Override
public String getInputTag(Map<String, String> attributes) {
|
TagAttributes tagAttributes = new TagAttributes(attributes);
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/FormCheckerForm.java
|
// Path: src/main/java/de/jformchecker/message/MessageSource.java
// @FunctionalInterface
// public interface MessageSource {
//
// public String getMessage(String key);
//
// public default String getSafeMessage(String key) {
// try {
// String msg = this.getMessage(key);
// return msg;
// } catch (Exception e) {
// return "??" + key + "??";
// }
// }
//
//
// public default String getMessage(ValidationResult vr) {
// // give translated messages higher prio than message-keys
// if (vr.getTranslatedMessage() != null) {
// return vr.getTranslatedMessage();
// } else
// if (vr.getMessage() != null) {
// return(String.format(this.getSafeMessage(
// vr.getMessage()
// ), vr.getErrorVals()));
//
// } else {
// throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text");
// }
// }
//
// }
//
// Path: src/main/java/de/jformchecker/request/SessionGet.java
// @FunctionalInterface
// public interface SessionGet {
// public Object getAttribute(String name);
// }
//
// Path: src/main/java/de/jformchecker/request/SessionSet.java
// @FunctionalInterface
// public interface SessionSet {
// public void setAttribute(String name, Object o);
// }
|
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import de.jformchecker.message.MessageSource;
import de.jformchecker.request.SessionGet;
import de.jformchecker.request.SessionSet;
|
package de.jformchecker;
// holds a collection of form-Elements that can be rendered by formchecker
public abstract class FormCheckerForm {
List<FormCheckerElement> elements = new ArrayList<>();
List<FormValidator> validators = new ArrayList<>();
private Map<String, FormCheckerElement> fastAccess = new LinkedHashMap<>();
String submitLabel = "OK";
|
// Path: src/main/java/de/jformchecker/message/MessageSource.java
// @FunctionalInterface
// public interface MessageSource {
//
// public String getMessage(String key);
//
// public default String getSafeMessage(String key) {
// try {
// String msg = this.getMessage(key);
// return msg;
// } catch (Exception e) {
// return "??" + key + "??";
// }
// }
//
//
// public default String getMessage(ValidationResult vr) {
// // give translated messages higher prio than message-keys
// if (vr.getTranslatedMessage() != null) {
// return vr.getTranslatedMessage();
// } else
// if (vr.getMessage() != null) {
// return(String.format(this.getSafeMessage(
// vr.getMessage()
// ), vr.getErrorVals()));
//
// } else {
// throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text");
// }
// }
//
// }
//
// Path: src/main/java/de/jformchecker/request/SessionGet.java
// @FunctionalInterface
// public interface SessionGet {
// public Object getAttribute(String name);
// }
//
// Path: src/main/java/de/jformchecker/request/SessionSet.java
// @FunctionalInterface
// public interface SessionSet {
// public void setAttribute(String name, Object o);
// }
// Path: src/main/java/de/jformchecker/FormCheckerForm.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import de.jformchecker.message.MessageSource;
import de.jformchecker.request.SessionGet;
import de.jformchecker.request.SessionSet;
package de.jformchecker;
// holds a collection of form-Elements that can be rendered by formchecker
public abstract class FormCheckerForm {
List<FormCheckerElement> elements = new ArrayList<>();
List<FormValidator> validators = new ArrayList<>();
private Map<String, FormCheckerElement> fastAccess = new LinkedHashMap<>();
String submitLabel = "OK";
|
private MessageSource messageSource;
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/FormCheckerForm.java
|
// Path: src/main/java/de/jformchecker/message/MessageSource.java
// @FunctionalInterface
// public interface MessageSource {
//
// public String getMessage(String key);
//
// public default String getSafeMessage(String key) {
// try {
// String msg = this.getMessage(key);
// return msg;
// } catch (Exception e) {
// return "??" + key + "??";
// }
// }
//
//
// public default String getMessage(ValidationResult vr) {
// // give translated messages higher prio than message-keys
// if (vr.getTranslatedMessage() != null) {
// return vr.getTranslatedMessage();
// } else
// if (vr.getMessage() != null) {
// return(String.format(this.getSafeMessage(
// vr.getMessage()
// ), vr.getErrorVals()));
//
// } else {
// throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text");
// }
// }
//
// }
//
// Path: src/main/java/de/jformchecker/request/SessionGet.java
// @FunctionalInterface
// public interface SessionGet {
// public Object getAttribute(String name);
// }
//
// Path: src/main/java/de/jformchecker/request/SessionSet.java
// @FunctionalInterface
// public interface SessionSet {
// public void setAttribute(String name, Object o);
// }
|
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import de.jformchecker.message.MessageSource;
import de.jformchecker.request.SessionGet;
import de.jformchecker.request.SessionSet;
|
package de.jformchecker;
// holds a collection of form-Elements that can be rendered by formchecker
public abstract class FormCheckerForm {
List<FormCheckerElement> elements = new ArrayList<>();
List<FormValidator> validators = new ArrayList<>();
private Map<String, FormCheckerElement> fastAccess = new LinkedHashMap<>();
String submitLabel = "OK";
private MessageSource messageSource;
boolean protectedAgainstCSRF = false;
boolean showSubmitButton = true;
|
// Path: src/main/java/de/jformchecker/message/MessageSource.java
// @FunctionalInterface
// public interface MessageSource {
//
// public String getMessage(String key);
//
// public default String getSafeMessage(String key) {
// try {
// String msg = this.getMessage(key);
// return msg;
// } catch (Exception e) {
// return "??" + key + "??";
// }
// }
//
//
// public default String getMessage(ValidationResult vr) {
// // give translated messages higher prio than message-keys
// if (vr.getTranslatedMessage() != null) {
// return vr.getTranslatedMessage();
// } else
// if (vr.getMessage() != null) {
// return(String.format(this.getSafeMessage(
// vr.getMessage()
// ), vr.getErrorVals()));
//
// } else {
// throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text");
// }
// }
//
// }
//
// Path: src/main/java/de/jformchecker/request/SessionGet.java
// @FunctionalInterface
// public interface SessionGet {
// public Object getAttribute(String name);
// }
//
// Path: src/main/java/de/jformchecker/request/SessionSet.java
// @FunctionalInterface
// public interface SessionSet {
// public void setAttribute(String name, Object o);
// }
// Path: src/main/java/de/jformchecker/FormCheckerForm.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import de.jformchecker.message.MessageSource;
import de.jformchecker.request.SessionGet;
import de.jformchecker.request.SessionSet;
package de.jformchecker;
// holds a collection of form-Elements that can be rendered by formchecker
public abstract class FormCheckerForm {
List<FormCheckerElement> elements = new ArrayList<>();
List<FormValidator> validators = new ArrayList<>();
private Map<String, FormCheckerElement> fastAccess = new LinkedHashMap<>();
String submitLabel = "OK";
private MessageSource messageSource;
boolean protectedAgainstCSRF = false;
boolean showSubmitButton = true;
|
SessionSet sessionSet;
|
jochen777/jFormchecker
|
src/main/java/de/jformchecker/FormCheckerForm.java
|
// Path: src/main/java/de/jformchecker/message/MessageSource.java
// @FunctionalInterface
// public interface MessageSource {
//
// public String getMessage(String key);
//
// public default String getSafeMessage(String key) {
// try {
// String msg = this.getMessage(key);
// return msg;
// } catch (Exception e) {
// return "??" + key + "??";
// }
// }
//
//
// public default String getMessage(ValidationResult vr) {
// // give translated messages higher prio than message-keys
// if (vr.getTranslatedMessage() != null) {
// return vr.getTranslatedMessage();
// } else
// if (vr.getMessage() != null) {
// return(String.format(this.getSafeMessage(
// vr.getMessage()
// ), vr.getErrorVals()));
//
// } else {
// throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text");
// }
// }
//
// }
//
// Path: src/main/java/de/jformchecker/request/SessionGet.java
// @FunctionalInterface
// public interface SessionGet {
// public Object getAttribute(String name);
// }
//
// Path: src/main/java/de/jformchecker/request/SessionSet.java
// @FunctionalInterface
// public interface SessionSet {
// public void setAttribute(String name, Object o);
// }
|
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import de.jformchecker.message.MessageSource;
import de.jformchecker.request.SessionGet;
import de.jformchecker.request.SessionSet;
|
package de.jformchecker;
// holds a collection of form-Elements that can be rendered by formchecker
public abstract class FormCheckerForm {
List<FormCheckerElement> elements = new ArrayList<>();
List<FormValidator> validators = new ArrayList<>();
private Map<String, FormCheckerElement> fastAccess = new LinkedHashMap<>();
String submitLabel = "OK";
private MessageSource messageSource;
boolean protectedAgainstCSRF = false;
boolean showSubmitButton = true;
SessionSet sessionSet;
|
// Path: src/main/java/de/jformchecker/message/MessageSource.java
// @FunctionalInterface
// public interface MessageSource {
//
// public String getMessage(String key);
//
// public default String getSafeMessage(String key) {
// try {
// String msg = this.getMessage(key);
// return msg;
// } catch (Exception e) {
// return "??" + key + "??";
// }
// }
//
//
// public default String getMessage(ValidationResult vr) {
// // give translated messages higher prio than message-keys
// if (vr.getTranslatedMessage() != null) {
// return vr.getTranslatedMessage();
// } else
// if (vr.getMessage() != null) {
// return(String.format(this.getSafeMessage(
// vr.getMessage()
// ), vr.getErrorVals()));
//
// } else {
// throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text");
// }
// }
//
// }
//
// Path: src/main/java/de/jformchecker/request/SessionGet.java
// @FunctionalInterface
// public interface SessionGet {
// public Object getAttribute(String name);
// }
//
// Path: src/main/java/de/jformchecker/request/SessionSet.java
// @FunctionalInterface
// public interface SessionSet {
// public void setAttribute(String name, Object o);
// }
// Path: src/main/java/de/jformchecker/FormCheckerForm.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import de.jformchecker.message.MessageSource;
import de.jformchecker.request.SessionGet;
import de.jformchecker.request.SessionSet;
package de.jformchecker;
// holds a collection of form-Elements that can be rendered by formchecker
public abstract class FormCheckerForm {
List<FormCheckerElement> elements = new ArrayList<>();
List<FormValidator> validators = new ArrayList<>();
private Map<String, FormCheckerElement> fastAccess = new LinkedHashMap<>();
String submitLabel = "OK";
private MessageSource messageSource;
boolean protectedAgainstCSRF = false;
boolean showSubmitButton = true;
SessionSet sessionSet;
|
SessionGet sessionGet;
|
seven332/Nimingban
|
app/src/main/java/com/hippo/preference/DialogPreference.java
|
// Path: app/src/main/java/com/hippo/nimingban/preference/PreferenceUtils.java
// public final class PreferenceUtils {
// private PreferenceUtils() {}
//
// private static final Method mRegisterOnActivityDestroyListener;
// private static final Method mUnregisterOnActivityDestroyListener;
//
// static {
// Method method;
// Class<?> clazz = PreferenceManager.class;
//
// method = null;
// try {
// method = clazz.getDeclaredMethod("registerOnActivityDestroyListener",
// PreferenceManager.OnActivityDestroyListener.class);
// if (null != method) {
// method.setAccessible(true);
// }
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// }
// mRegisterOnActivityDestroyListener = method;
//
// method = null;
// try {
// method = clazz.getDeclaredMethod("unregisterOnActivityDestroyListener",
// PreferenceManager.OnActivityDestroyListener.class);
// if (null != method) {
// method.setAccessible(true);
// }
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// }
// mUnregisterOnActivityDestroyListener = method;
// }
//
// @SuppressWarnings("TryWithIdenticalCatches")
// public static void registerOnActivityDestroyListener(Preference preference,
// PreferenceManager.OnActivityDestroyListener listener) {
// if (null == mRegisterOnActivityDestroyListener || null == preference || null == listener) {
// return;
// }
// PreferenceManager preferenceManager = preference.getPreferenceManager();
// if (null == preferenceManager) {
// return;
// }
//
// try {
// mRegisterOnActivityDestroyListener.invoke(preferenceManager, listener);
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// }
// }
//
// @SuppressWarnings("TryWithIdenticalCatches")
// public static void unregisterOnActivityDestroyListener(Preference preference,
// PreferenceManager.OnActivityDestroyListener listener) {
// if (null == mUnregisterOnActivityDestroyListener || null == preference || null == listener) {
// return;
// }
// PreferenceManager preferenceManager = preference.getPreferenceManager();
// if (null == preferenceManager) {
// return;
// }
//
// try {
// mUnregisterOnActivityDestroyListener.invoke(preferenceManager, listener);
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// }
// }
// }
|
import android.view.WindowManager;
import com.hippo.nimingban.preference.PreferenceUtils;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import android.view.AbsSavedState;
import android.view.Window;
|
/*
* Copyright 2019 Hippo Seven
*
* 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 com.hippo.preference;
/**
* A base class for {@link Preference} objects that are
* dialog-based. These preferences will, when clicked, open a dialog showing the
* actual preference controls.
*/
public abstract class DialogPreference extends Preference implements
DialogInterface.OnClickListener, DialogInterface.OnDismissListener,
PreferenceManager.OnActivityDestroyListener {
/** The dialog, if it is showing. */
private AlertDialog mDialog;
/** Which button was clicked. */
private int mWhichButtonClicked;
public DialogPreference(Context context) {
super(context);
}
public DialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DialogPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* Prepares the dialog builder to be shown when the preference is clicked.
* Use this to set custom properties on the dialog.
* <p>
* Do not {@link AlertDialog.Builder#create()} or
* {@link AlertDialog.Builder#show()}.
*/
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
}
@Override
protected void onClick() {
if (mDialog != null && mDialog.isShowing()) return;
showDialog(null);
}
/**
* Shows the dialog associated with this Preference. This is normally initiated
* automatically on clicking on the preference. Call this method if you need to
* show the dialog on some other event.
*
* @param state Optional instance state to restore on the dialog
*/
protected void showDialog(Bundle state) {
mWhichButtonClicked = DialogInterface.BUTTON_NEGATIVE;
|
// Path: app/src/main/java/com/hippo/nimingban/preference/PreferenceUtils.java
// public final class PreferenceUtils {
// private PreferenceUtils() {}
//
// private static final Method mRegisterOnActivityDestroyListener;
// private static final Method mUnregisterOnActivityDestroyListener;
//
// static {
// Method method;
// Class<?> clazz = PreferenceManager.class;
//
// method = null;
// try {
// method = clazz.getDeclaredMethod("registerOnActivityDestroyListener",
// PreferenceManager.OnActivityDestroyListener.class);
// if (null != method) {
// method.setAccessible(true);
// }
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// }
// mRegisterOnActivityDestroyListener = method;
//
// method = null;
// try {
// method = clazz.getDeclaredMethod("unregisterOnActivityDestroyListener",
// PreferenceManager.OnActivityDestroyListener.class);
// if (null != method) {
// method.setAccessible(true);
// }
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// }
// mUnregisterOnActivityDestroyListener = method;
// }
//
// @SuppressWarnings("TryWithIdenticalCatches")
// public static void registerOnActivityDestroyListener(Preference preference,
// PreferenceManager.OnActivityDestroyListener listener) {
// if (null == mRegisterOnActivityDestroyListener || null == preference || null == listener) {
// return;
// }
// PreferenceManager preferenceManager = preference.getPreferenceManager();
// if (null == preferenceManager) {
// return;
// }
//
// try {
// mRegisterOnActivityDestroyListener.invoke(preferenceManager, listener);
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// }
// }
//
// @SuppressWarnings("TryWithIdenticalCatches")
// public static void unregisterOnActivityDestroyListener(Preference preference,
// PreferenceManager.OnActivityDestroyListener listener) {
// if (null == mUnregisterOnActivityDestroyListener || null == preference || null == listener) {
// return;
// }
// PreferenceManager preferenceManager = preference.getPreferenceManager();
// if (null == preferenceManager) {
// return;
// }
//
// try {
// mUnregisterOnActivityDestroyListener.invoke(preferenceManager, listener);
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// }
// }
// }
// Path: app/src/main/java/com/hippo/preference/DialogPreference.java
import android.view.WindowManager;
import com.hippo.nimingban.preference.PreferenceUtils;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import android.view.AbsSavedState;
import android.view.Window;
/*
* Copyright 2019 Hippo Seven
*
* 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 com.hippo.preference;
/**
* A base class for {@link Preference} objects that are
* dialog-based. These preferences will, when clicked, open a dialog showing the
* actual preference controls.
*/
public abstract class DialogPreference extends Preference implements
DialogInterface.OnClickListener, DialogInterface.OnDismissListener,
PreferenceManager.OnActivityDestroyListener {
/** The dialog, if it is showing. */
private AlertDialog mDialog;
/** Which button was clicked. */
private int mWhichButtonClicked;
public DialogPreference(Context context) {
super(context);
}
public DialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DialogPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* Prepares the dialog builder to be shown when the preference is clicked.
* Use this to set custom properties on the dialog.
* <p>
* Do not {@link AlertDialog.Builder#create()} or
* {@link AlertDialog.Builder#show()}.
*/
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
}
@Override
protected void onClick() {
if (mDialog != null && mDialog.isShowing()) return;
showDialog(null);
}
/**
* Shows the dialog associated with this Preference. This is normally initiated
* automatically on clicking on the preference. Call this method if you need to
* show the dialog on some other event.
*
* @param state Optional instance state to restore on the dialog
*/
protected void showDialog(Bundle state) {
mWhichButtonClicked = DialogInterface.BUTTON_NEGATIVE;
|
PreferenceUtils.registerOnActivityDestroyListener(this, this);
|
seven332/Nimingban
|
app/src/main/java/com/hippo/nimingban/widget/ContentLayout.java
|
// Path: app/src/main/java/com/hippo/util/ExceptionUtils.java
// public final class ExceptionUtils {
//
// private static final String TAG = ExceptionUtils.class.getSimpleName();
//
// @NonNull
// public static String getReadableString(@NonNull Context context, @NonNull Exception e) {
// if (e instanceof ConnectTimeoutException ||
// e instanceof SocketTimeoutException) {
// return context.getString(R.string.em_timeout);
// } else if (e instanceof UnknownHostException) {
// return context.getString(R.string.em_unknown_host);
// } else if (e instanceof ResponseCodeException) {
// ResponseCodeException responseCodeException = (ResponseCodeException) e;
// String error = context.getString(R.string.em_response_code, responseCodeException.getResponseCode());
// if (responseCodeException.isIdentifiedResponseCode()) {
// error += ", " + responseCodeException.getMessage();
// }
// return error;
// } else if (e instanceof ProtocolException && e.getMessage().startsWith("Too many follow-up requests:")) {
// return context.getString(R.string.em_redirection);
// } else if (e instanceof SocketException) {
// return context.getString(R.string.em_socket);
// } else if (e instanceof NMBException) {
// return e.getMessage();
// } else {
// Say.d(TAG, "Can't recognize this Exception", e);
// return context.getString(R.string.em_unknown);
// }
// }
//
// public static @Nullable String getReasonString(Context context, Exception e) {
// /*
// if (e instanceof UnknownHostException) {
// return context.getString(R.string.erm_unknown_host);
// } else {
// return null;
// }
// */
// return null;
// }
// }
|
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.FastScroller;
import com.hippo.easyrecyclerview.HandlerDrawable;
import com.hippo.easyrecyclerview.LayoutManagerUtils;
import com.hippo.effect.ViewTransition;
import com.hippo.nimingban.R;
import com.hippo.refreshlayout.RefreshLayout;
import com.hippo.util.ExceptionUtils;
import com.hippo.widget.ProgressView;
import com.hippo.yorozuya.IntIdGenerator;
import com.hippo.yorozuya.IntList;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.Say;
import java.util.ArrayList;
import java.util.List;
|
int newIndexEnd = newIndexStart + data.size();
mData.addAll(oldIndexStart, data);
notifyDataSetChanged();
for (int i = mCurrentTaskPage - mStartPage, n = mPageDivider.size(); i < n; i++) {
mPageDivider.set(i, mPageDivider.get(i) - oldIndexEnd + newIndexEnd);
}
if (newIndexEnd > oldIndexEnd && newIndexEnd > 0) {
mRecyclerView.stopScroll();
LayoutManagerUtils.scrollToPositionWithOffset(mRecyclerView.getLayoutManager(), newIndexEnd - 1, 0);
onScrollToPosition();
}
break;
}
}
mRefreshLayout.setHeaderRefreshing(false);
mRefreshLayout.setFooterRefreshing(false);
}
public void onGetExpection(int taskId, Exception e) {
if (mCurrentTaskId == taskId) {
if (e != null) {
e.printStackTrace();
}
mRefreshLayout.setHeaderRefreshing(false);
mRefreshLayout.setFooterRefreshing(false);
Say.d(TAG, "Get page data failed " + e.getClass().getName() + " " + e.getMessage());
|
// Path: app/src/main/java/com/hippo/util/ExceptionUtils.java
// public final class ExceptionUtils {
//
// private static final String TAG = ExceptionUtils.class.getSimpleName();
//
// @NonNull
// public static String getReadableString(@NonNull Context context, @NonNull Exception e) {
// if (e instanceof ConnectTimeoutException ||
// e instanceof SocketTimeoutException) {
// return context.getString(R.string.em_timeout);
// } else if (e instanceof UnknownHostException) {
// return context.getString(R.string.em_unknown_host);
// } else if (e instanceof ResponseCodeException) {
// ResponseCodeException responseCodeException = (ResponseCodeException) e;
// String error = context.getString(R.string.em_response_code, responseCodeException.getResponseCode());
// if (responseCodeException.isIdentifiedResponseCode()) {
// error += ", " + responseCodeException.getMessage();
// }
// return error;
// } else if (e instanceof ProtocolException && e.getMessage().startsWith("Too many follow-up requests:")) {
// return context.getString(R.string.em_redirection);
// } else if (e instanceof SocketException) {
// return context.getString(R.string.em_socket);
// } else if (e instanceof NMBException) {
// return e.getMessage();
// } else {
// Say.d(TAG, "Can't recognize this Exception", e);
// return context.getString(R.string.em_unknown);
// }
// }
//
// public static @Nullable String getReasonString(Context context, Exception e) {
// /*
// if (e instanceof UnknownHostException) {
// return context.getString(R.string.erm_unknown_host);
// } else {
// return null;
// }
// */
// return null;
// }
// }
// Path: app/src/main/java/com/hippo/nimingban/widget/ContentLayout.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.FastScroller;
import com.hippo.easyrecyclerview.HandlerDrawable;
import com.hippo.easyrecyclerview.LayoutManagerUtils;
import com.hippo.effect.ViewTransition;
import com.hippo.nimingban.R;
import com.hippo.refreshlayout.RefreshLayout;
import com.hippo.util.ExceptionUtils;
import com.hippo.widget.ProgressView;
import com.hippo.yorozuya.IntIdGenerator;
import com.hippo.yorozuya.IntList;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.Say;
import java.util.ArrayList;
import java.util.List;
int newIndexEnd = newIndexStart + data.size();
mData.addAll(oldIndexStart, data);
notifyDataSetChanged();
for (int i = mCurrentTaskPage - mStartPage, n = mPageDivider.size(); i < n; i++) {
mPageDivider.set(i, mPageDivider.get(i) - oldIndexEnd + newIndexEnd);
}
if (newIndexEnd > oldIndexEnd && newIndexEnd > 0) {
mRecyclerView.stopScroll();
LayoutManagerUtils.scrollToPositionWithOffset(mRecyclerView.getLayoutManager(), newIndexEnd - 1, 0);
onScrollToPosition();
}
break;
}
}
mRefreshLayout.setHeaderRefreshing(false);
mRefreshLayout.setFooterRefreshing(false);
}
public void onGetExpection(int taskId, Exception e) {
if (mCurrentTaskId == taskId) {
if (e != null) {
e.printStackTrace();
}
mRefreshLayout.setHeaderRefreshing(false);
mRefreshLayout.setFooterRefreshing(false);
Say.d(TAG, "Get page data failed " + e.getClass().getName() + " " + e.getMessage());
|
String readableError = ExceptionUtils.getReadableString(getContext(), e);
|
seven332/Nimingban
|
app/src/main/java/com/hippo/nimingban/util/ForumAutoSortingUtils.java
|
// Path: app/src/main/java/com/hippo/nimingban/client/data/Forum.java
// public abstract class Forum {
//
// public abstract Site getNMBSite();
//
// public abstract String getNMBId();
//
// public abstract CharSequence getNMBDisplayname();
//
// public abstract String getNMBMsg();
// }
|
import com.hippo.nimingban.client.data.Forum;
import com.hippo.nimingban.dao.ACForumRaw;
import de.greenrobot.dao.query.LazyList;
|
boolean pinned = isPinned(freq);
int result = pinned ? setUnpinned(freq) : freq;
if (result + 1 < FREQUENCY_UPPER_BOUND) { // make sure freq be in bound
result++;
}
if (pinned) {
result = setPinned(result);
}
return result;
}
private static Integer decrementFrequency(Integer freq) {
if (freq == null) {
return 0;
}
boolean pinned = isPinned(freq);
int result = pinned ? setUnpinned(freq) : freq;
if (result > 1) { // bypass freq == 1 so that visited forums are always before unvisited ones.
result /= 2;
}
if (pinned) {
result = setPinned(result);
}
return result;
}
|
// Path: app/src/main/java/com/hippo/nimingban/client/data/Forum.java
// public abstract class Forum {
//
// public abstract Site getNMBSite();
//
// public abstract String getNMBId();
//
// public abstract CharSequence getNMBDisplayname();
//
// public abstract String getNMBMsg();
// }
// Path: app/src/main/java/com/hippo/nimingban/util/ForumAutoSortingUtils.java
import com.hippo.nimingban.client.data.Forum;
import com.hippo.nimingban.dao.ACForumRaw;
import de.greenrobot.dao.query.LazyList;
boolean pinned = isPinned(freq);
int result = pinned ? setUnpinned(freq) : freq;
if (result + 1 < FREQUENCY_UPPER_BOUND) { // make sure freq be in bound
result++;
}
if (pinned) {
result = setPinned(result);
}
return result;
}
private static Integer decrementFrequency(Integer freq) {
if (freq == null) {
return 0;
}
boolean pinned = isPinned(freq);
int result = pinned ? setUnpinned(freq) : freq;
if (result > 1) { // bypass freq == 1 so that visited forums are always before unvisited ones.
result /= 2;
}
if (pinned) {
result = setPinned(result);
}
return result;
}
|
public static void addACForumFrequency(Forum forum) {
|
seven332/Nimingban
|
app/src/main/java/com/hippo/nimingban/client/UpdateEngine.java
|
// Path: app/src/main/java/com/hippo/nimingban/client/data/UpdateStatus.java
// public class UpdateStatus {
//
// public int versionCode;
// public String versionName;
// public String info;
// public long size;
// public String apkUrl;
// public LinkedHashMap<String, String> discUrls;
// public String failedUrl;
//
// @Override
// public String toString() {
// return "versionCode = " + versionCode + ", versionName = " + versionName + ", info = " + info +
// ", size = " + size + ", apkUrl = " + apkUrl + ", discUrls = " + discUrls + ", failedUrl = " + failedUrl;
// }
// }
|
import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.hippo.nimingban.client.data.UpdateStatus;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
|
/*
* Copyright 2015 Hippo Seven
*
* 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 com.hippo.nimingban.client;
public final class UpdateEngine {
private static final String TAG = UpdateEngine.class.getSimpleName();
private static final String UPDATE_URL = "http://cover.acfunwiki.org/nimingban-update.json";
public static Call prepareUpdate(OkHttpClient okHttpClient) {
String url = UPDATE_URL;
Log.d(TAG, url);
Request request = new Request.Builder().url(url).build();
return okHttpClient.newCall(request);
}
|
// Path: app/src/main/java/com/hippo/nimingban/client/data/UpdateStatus.java
// public class UpdateStatus {
//
// public int versionCode;
// public String versionName;
// public String info;
// public long size;
// public String apkUrl;
// public LinkedHashMap<String, String> discUrls;
// public String failedUrl;
//
// @Override
// public String toString() {
// return "versionCode = " + versionCode + ", versionName = " + versionName + ", info = " + info +
// ", size = " + size + ", apkUrl = " + apkUrl + ", discUrls = " + discUrls + ", failedUrl = " + failedUrl;
// }
// }
// Path: app/src/main/java/com/hippo/nimingban/client/UpdateEngine.java
import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.hippo.nimingban.client.data.UpdateStatus;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/*
* Copyright 2015 Hippo Seven
*
* 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 com.hippo.nimingban.client;
public final class UpdateEngine {
private static final String TAG = UpdateEngine.class.getSimpleName();
private static final String UPDATE_URL = "http://cover.acfunwiki.org/nimingban-update.json";
public static Call prepareUpdate(OkHttpClient okHttpClient) {
String url = UPDATE_URL;
Log.d(TAG, url);
Request request = new Request.Builder().url(url).build();
return okHttpClient.newCall(request);
}
|
public static UpdateStatus doUpdate(Call call) throws Exception {
|
wzgiceman/RxjavaRetrofitDemo-master
|
app/src/main/java/com/example/retrofit/HttpPostService.java
|
// Path: app/src/main/java/com/example/retrofit/entity/resulte/RetrofitEntity.java
// public class RetrofitEntity {
// private int ret;
// private String msg;
// private List<SubjectResulte> data;
//
// public int getRet() {
// return ret;
// }
//
// public void setRet(int ret) {
// this.ret = ret;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public List<SubjectResulte> getData() {
// return data;
// }
//
// public void setData(List<SubjectResulte> data) {
// this.data = data;
// }
// }
//
// Path: app/src/main/java/com/example/retrofit/entity/resulte/SubjectResulte.java
// public class SubjectResulte {
// private int id;
// private String name;
// private String title;
//
// @Override
// public String toString() {
// return "name->"+name+"\n";
//
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
// }
//
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/Api/BaseResultEntity.java
// public class BaseResultEntity<T> {
// // 判断标示
// private int ret;
// // 提示信息
// private String msg;
// //显示数据(用户需要关心的数据)
// private T data;
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
//
// public int getRet() {
// return ret;
// }
//
// public void setRet(int ret) {
// this.ret = ret;
// }
// }
|
import com.example.retrofit.entity.resulte.RetrofitEntity;
import com.example.retrofit.entity.resulte.SubjectResulte;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseResultEntity;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
import rx.Observable;
|
package com.example.retrofit;
/**
* 测试接口service-post相关
* Created by WZG on 2016/12/19.
*/
public interface HttpPostService {
@POST("AppFiftyToneGraph/videoLink")
|
// Path: app/src/main/java/com/example/retrofit/entity/resulte/RetrofitEntity.java
// public class RetrofitEntity {
// private int ret;
// private String msg;
// private List<SubjectResulte> data;
//
// public int getRet() {
// return ret;
// }
//
// public void setRet(int ret) {
// this.ret = ret;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public List<SubjectResulte> getData() {
// return data;
// }
//
// public void setData(List<SubjectResulte> data) {
// this.data = data;
// }
// }
//
// Path: app/src/main/java/com/example/retrofit/entity/resulte/SubjectResulte.java
// public class SubjectResulte {
// private int id;
// private String name;
// private String title;
//
// @Override
// public String toString() {
// return "name->"+name+"\n";
//
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
// }
//
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/Api/BaseResultEntity.java
// public class BaseResultEntity<T> {
// // 判断标示
// private int ret;
// // 提示信息
// private String msg;
// //显示数据(用户需要关心的数据)
// private T data;
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
//
// public int getRet() {
// return ret;
// }
//
// public void setRet(int ret) {
// this.ret = ret;
// }
// }
// Path: app/src/main/java/com/example/retrofit/HttpPostService.java
import com.example.retrofit.entity.resulte.RetrofitEntity;
import com.example.retrofit.entity.resulte.SubjectResulte;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseResultEntity;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
import rx.Observable;
package com.example.retrofit;
/**
* 测试接口service-post相关
* Created by WZG on 2016/12/19.
*/
public interface HttpPostService {
@POST("AppFiftyToneGraph/videoLink")
|
Call<RetrofitEntity> getAllVedio(@Body boolean once_no);
|
wzgiceman/RxjavaRetrofitDemo-master
|
app/src/main/java/com/example/retrofit/HttpPostService.java
|
// Path: app/src/main/java/com/example/retrofit/entity/resulte/RetrofitEntity.java
// public class RetrofitEntity {
// private int ret;
// private String msg;
// private List<SubjectResulte> data;
//
// public int getRet() {
// return ret;
// }
//
// public void setRet(int ret) {
// this.ret = ret;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public List<SubjectResulte> getData() {
// return data;
// }
//
// public void setData(List<SubjectResulte> data) {
// this.data = data;
// }
// }
//
// Path: app/src/main/java/com/example/retrofit/entity/resulte/SubjectResulte.java
// public class SubjectResulte {
// private int id;
// private String name;
// private String title;
//
// @Override
// public String toString() {
// return "name->"+name+"\n";
//
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
// }
//
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/Api/BaseResultEntity.java
// public class BaseResultEntity<T> {
// // 判断标示
// private int ret;
// // 提示信息
// private String msg;
// //显示数据(用户需要关心的数据)
// private T data;
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
//
// public int getRet() {
// return ret;
// }
//
// public void setRet(int ret) {
// this.ret = ret;
// }
// }
|
import com.example.retrofit.entity.resulte.RetrofitEntity;
import com.example.retrofit.entity.resulte.SubjectResulte;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseResultEntity;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
import rx.Observable;
|
package com.example.retrofit;
/**
* 测试接口service-post相关
* Created by WZG on 2016/12/19.
*/
public interface HttpPostService {
@POST("AppFiftyToneGraph/videoLink")
Call<RetrofitEntity> getAllVedio(@Body boolean once_no);
@POST("AppFiftyToneGraph/videoLink")
Observable<RetrofitEntity> getAllVedioBy(@Body boolean once_no);
@FormUrlEncoded
@POST("AppFiftyToneGraph/videoLink")
|
// Path: app/src/main/java/com/example/retrofit/entity/resulte/RetrofitEntity.java
// public class RetrofitEntity {
// private int ret;
// private String msg;
// private List<SubjectResulte> data;
//
// public int getRet() {
// return ret;
// }
//
// public void setRet(int ret) {
// this.ret = ret;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public List<SubjectResulte> getData() {
// return data;
// }
//
// public void setData(List<SubjectResulte> data) {
// this.data = data;
// }
// }
//
// Path: app/src/main/java/com/example/retrofit/entity/resulte/SubjectResulte.java
// public class SubjectResulte {
// private int id;
// private String name;
// private String title;
//
// @Override
// public String toString() {
// return "name->"+name+"\n";
//
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
// }
//
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/Api/BaseResultEntity.java
// public class BaseResultEntity<T> {
// // 判断标示
// private int ret;
// // 提示信息
// private String msg;
// //显示数据(用户需要关心的数据)
// private T data;
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
//
// public int getRet() {
// return ret;
// }
//
// public void setRet(int ret) {
// this.ret = ret;
// }
// }
// Path: app/src/main/java/com/example/retrofit/HttpPostService.java
import com.example.retrofit.entity.resulte.RetrofitEntity;
import com.example.retrofit.entity.resulte.SubjectResulte;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseResultEntity;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
import rx.Observable;
package com.example.retrofit;
/**
* 测试接口service-post相关
* Created by WZG on 2016/12/19.
*/
public interface HttpPostService {
@POST("AppFiftyToneGraph/videoLink")
Call<RetrofitEntity> getAllVedio(@Body boolean once_no);
@POST("AppFiftyToneGraph/videoLink")
Observable<RetrofitEntity> getAllVedioBy(@Body boolean once_no);
@FormUrlEncoded
@POST("AppFiftyToneGraph/videoLink")
|
Observable<BaseResultEntity<List<SubjectResulte>>> getAllVedioBys(@Field("once") boolean once_no);
|
wzgiceman/RxjavaRetrofitDemo-master
|
app/src/main/java/com/example/retrofit/HttpPostService.java
|
// Path: app/src/main/java/com/example/retrofit/entity/resulte/RetrofitEntity.java
// public class RetrofitEntity {
// private int ret;
// private String msg;
// private List<SubjectResulte> data;
//
// public int getRet() {
// return ret;
// }
//
// public void setRet(int ret) {
// this.ret = ret;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public List<SubjectResulte> getData() {
// return data;
// }
//
// public void setData(List<SubjectResulte> data) {
// this.data = data;
// }
// }
//
// Path: app/src/main/java/com/example/retrofit/entity/resulte/SubjectResulte.java
// public class SubjectResulte {
// private int id;
// private String name;
// private String title;
//
// @Override
// public String toString() {
// return "name->"+name+"\n";
//
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
// }
//
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/Api/BaseResultEntity.java
// public class BaseResultEntity<T> {
// // 判断标示
// private int ret;
// // 提示信息
// private String msg;
// //显示数据(用户需要关心的数据)
// private T data;
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
//
// public int getRet() {
// return ret;
// }
//
// public void setRet(int ret) {
// this.ret = ret;
// }
// }
|
import com.example.retrofit.entity.resulte.RetrofitEntity;
import com.example.retrofit.entity.resulte.SubjectResulte;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseResultEntity;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
import rx.Observable;
|
package com.example.retrofit;
/**
* 测试接口service-post相关
* Created by WZG on 2016/12/19.
*/
public interface HttpPostService {
@POST("AppFiftyToneGraph/videoLink")
Call<RetrofitEntity> getAllVedio(@Body boolean once_no);
@POST("AppFiftyToneGraph/videoLink")
Observable<RetrofitEntity> getAllVedioBy(@Body boolean once_no);
@FormUrlEncoded
@POST("AppFiftyToneGraph/videoLink")
|
// Path: app/src/main/java/com/example/retrofit/entity/resulte/RetrofitEntity.java
// public class RetrofitEntity {
// private int ret;
// private String msg;
// private List<SubjectResulte> data;
//
// public int getRet() {
// return ret;
// }
//
// public void setRet(int ret) {
// this.ret = ret;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public List<SubjectResulte> getData() {
// return data;
// }
//
// public void setData(List<SubjectResulte> data) {
// this.data = data;
// }
// }
//
// Path: app/src/main/java/com/example/retrofit/entity/resulte/SubjectResulte.java
// public class SubjectResulte {
// private int id;
// private String name;
// private String title;
//
// @Override
// public String toString() {
// return "name->"+name+"\n";
//
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
// }
//
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/Api/BaseResultEntity.java
// public class BaseResultEntity<T> {
// // 判断标示
// private int ret;
// // 提示信息
// private String msg;
// //显示数据(用户需要关心的数据)
// private T data;
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
//
// public int getRet() {
// return ret;
// }
//
// public void setRet(int ret) {
// this.ret = ret;
// }
// }
// Path: app/src/main/java/com/example/retrofit/HttpPostService.java
import com.example.retrofit.entity.resulte.RetrofitEntity;
import com.example.retrofit.entity.resulte.SubjectResulte;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseResultEntity;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
import rx.Observable;
package com.example.retrofit;
/**
* 测试接口service-post相关
* Created by WZG on 2016/12/19.
*/
public interface HttpPostService {
@POST("AppFiftyToneGraph/videoLink")
Call<RetrofitEntity> getAllVedio(@Body boolean once_no);
@POST("AppFiftyToneGraph/videoLink")
Observable<RetrofitEntity> getAllVedioBy(@Body boolean once_no);
@FormUrlEncoded
@POST("AppFiftyToneGraph/videoLink")
|
Observable<BaseResultEntity<List<SubjectResulte>>> getAllVedioBys(@Field("once") boolean once_no);
|
wzgiceman/RxjavaRetrofitDemo-master
|
rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/download/DownInfo.java
|
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpDownOnNextListener.java
// public abstract class HttpDownOnNextListener<T> {
// /**
// * 成功后回调方法
// * @param t
// */
// public abstract void onNext(T t);
//
// /**
// * 开始下载
// */
// public abstract void onStart();
//
// /**
// * 完成下载
// */
// public abstract void onComplete();
//
//
//
// /**
// * 下载进度
// * @param readLength
// * @param countLength
// */
// public abstract void updateProgress(long readLength, long countLength);
//
// /**
// * 失败或者错误方法
// * 主动调用,更加灵活
// * @param e
// */
// public void onError(Throwable e){
//
// }
//
// /**
// * 暂停下载
// */
// public void onPuase(){
//
// }
//
// /**
// * 停止下载销毁
// */
// public void onStop(){
//
// }
// }
|
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpDownOnNextListener;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Keep;
import org.greenrobot.greendao.annotation.Transient;
import org.greenrobot.greendao.annotation.Generated;
|
package com.wzgiceman.rxretrofitlibrary.retrofit_rx.download;
/**
* apk下载请求数据基础类
* Created by WZG on 2016/10/20.
*/
@Entity
public class DownInfo{
@Id
private long id;
/*存储位置*/
private String savePath;
/*文件总长度*/
private long countLength;
/*下载长度*/
private long readLength;
/*下载唯一的HttpService*/
@Transient
private HttpDownService service;
/*回调监听*/
@Transient
|
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpDownOnNextListener.java
// public abstract class HttpDownOnNextListener<T> {
// /**
// * 成功后回调方法
// * @param t
// */
// public abstract void onNext(T t);
//
// /**
// * 开始下载
// */
// public abstract void onStart();
//
// /**
// * 完成下载
// */
// public abstract void onComplete();
//
//
//
// /**
// * 下载进度
// * @param readLength
// * @param countLength
// */
// public abstract void updateProgress(long readLength, long countLength);
//
// /**
// * 失败或者错误方法
// * 主动调用,更加灵活
// * @param e
// */
// public void onError(Throwable e){
//
// }
//
// /**
// * 暂停下载
// */
// public void onPuase(){
//
// }
//
// /**
// * 停止下载销毁
// */
// public void onStop(){
//
// }
// }
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/download/DownInfo.java
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpDownOnNextListener;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Keep;
import org.greenrobot.greendao.annotation.Transient;
import org.greenrobot.greendao.annotation.Generated;
package com.wzgiceman.rxretrofitlibrary.retrofit_rx.download;
/**
* apk下载请求数据基础类
* Created by WZG on 2016/10/20.
*/
@Entity
public class DownInfo{
@Id
private long id;
/*存储位置*/
private String savePath;
/*文件总长度*/
private long countLength;
/*下载长度*/
private long readLength;
/*下载唯一的HttpService*/
@Transient
private HttpDownService service;
/*回调监听*/
@Transient
|
private HttpDownOnNextListener listener;
|
wzgiceman/RxjavaRetrofitDemo-master
|
rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/Api/BaseApi.java
|
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/HttpTimeException.java
// public class HttpTimeException extends RuntimeException {
//
// public static final int NO_DATA = 0x2;
//
// public HttpTimeException(int resultCode) {
// this(getApiExceptionMessage(resultCode));
// }
//
// public HttpTimeException(String detailMessage) {
// super(detailMessage);
// }
//
// /**
// * 转换错误数据
// *
// * @param code
// * @return
// */
// private static String getApiExceptionMessage(int code) {
// String message = "";
// switch (code) {
// case NO_DATA:
// message = "无数据";
// break;
// default:
// message = "error";
// break;
//
// }
// return message;
// }
// }
//
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java
// public abstract class HttpOnNextListener<T> {
// /**
// * 成功后回调方法
// * @param t
// */
// public abstract void onNext(T t);
//
// /**
// * 緩存回調結果
// * @param string
// */
// public void onCacheNext(String string){
//
// }
//
// /**
// * 成功后的ober返回,扩展链接式调用
// * @param observable
// */
// public void onNext(Observable observable){
//
// }
//
// /**
// * 失败或者错误方法
// * 主动调用,更加灵活
// * @param e
// */
// public void onError(Throwable e){
//
// }
//
// /**
// * 取消回調
// */
// public void onCancel(){
//
// }
//
//
// }
|
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.HttpTimeException;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import java.lang.ref.SoftReference;
import retrofit2.Retrofit;
import rx.Observable;
import rx.functions.Func1;
|
package com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api;
/**
* 请求数据统一封装类
* Created by WZG on 2016/7/16.
*/
public abstract class BaseApi<T> implements Func1<BaseResultEntity<T>, T> {
//rx生命周期管理
private SoftReference<RxAppCompatActivity> rxAppCompatActivity;
/*回调*/
|
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/HttpTimeException.java
// public class HttpTimeException extends RuntimeException {
//
// public static final int NO_DATA = 0x2;
//
// public HttpTimeException(int resultCode) {
// this(getApiExceptionMessage(resultCode));
// }
//
// public HttpTimeException(String detailMessage) {
// super(detailMessage);
// }
//
// /**
// * 转换错误数据
// *
// * @param code
// * @return
// */
// private static String getApiExceptionMessage(int code) {
// String message = "";
// switch (code) {
// case NO_DATA:
// message = "无数据";
// break;
// default:
// message = "error";
// break;
//
// }
// return message;
// }
// }
//
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java
// public abstract class HttpOnNextListener<T> {
// /**
// * 成功后回调方法
// * @param t
// */
// public abstract void onNext(T t);
//
// /**
// * 緩存回調結果
// * @param string
// */
// public void onCacheNext(String string){
//
// }
//
// /**
// * 成功后的ober返回,扩展链接式调用
// * @param observable
// */
// public void onNext(Observable observable){
//
// }
//
// /**
// * 失败或者错误方法
// * 主动调用,更加灵活
// * @param e
// */
// public void onError(Throwable e){
//
// }
//
// /**
// * 取消回調
// */
// public void onCancel(){
//
// }
//
//
// }
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/Api/BaseApi.java
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.HttpTimeException;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import java.lang.ref.SoftReference;
import retrofit2.Retrofit;
import rx.Observable;
import rx.functions.Func1;
package com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api;
/**
* 请求数据统一封装类
* Created by WZG on 2016/7/16.
*/
public abstract class BaseApi<T> implements Func1<BaseResultEntity<T>, T> {
//rx生命周期管理
private SoftReference<RxAppCompatActivity> rxAppCompatActivity;
/*回调*/
|
private SoftReference<HttpOnNextListener> listener;
|
wzgiceman/RxjavaRetrofitDemo-master
|
rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/Api/BaseApi.java
|
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/HttpTimeException.java
// public class HttpTimeException extends RuntimeException {
//
// public static final int NO_DATA = 0x2;
//
// public HttpTimeException(int resultCode) {
// this(getApiExceptionMessage(resultCode));
// }
//
// public HttpTimeException(String detailMessage) {
// super(detailMessage);
// }
//
// /**
// * 转换错误数据
// *
// * @param code
// * @return
// */
// private static String getApiExceptionMessage(int code) {
// String message = "";
// switch (code) {
// case NO_DATA:
// message = "无数据";
// break;
// default:
// message = "error";
// break;
//
// }
// return message;
// }
// }
//
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java
// public abstract class HttpOnNextListener<T> {
// /**
// * 成功后回调方法
// * @param t
// */
// public abstract void onNext(T t);
//
// /**
// * 緩存回調結果
// * @param string
// */
// public void onCacheNext(String string){
//
// }
//
// /**
// * 成功后的ober返回,扩展链接式调用
// * @param observable
// */
// public void onNext(Observable observable){
//
// }
//
// /**
// * 失败或者错误方法
// * 主动调用,更加灵活
// * @param e
// */
// public void onError(Throwable e){
//
// }
//
// /**
// * 取消回調
// */
// public void onCancel(){
//
// }
//
//
// }
|
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.HttpTimeException;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import java.lang.ref.SoftReference;
import retrofit2.Retrofit;
import rx.Observable;
import rx.functions.Func1;
|
this.retryCount = retryCount;
}
public long getRetryDelay() {
return retryDelay;
}
public void setRetryDelay(long retryDelay) {
this.retryDelay = retryDelay;
}
public long getRetryIncreaseDelay() {
return retryIncreaseDelay;
}
public void setRetryIncreaseDelay(long retryIncreaseDelay) {
this.retryIncreaseDelay = retryIncreaseDelay;
}
/*
* 获取当前rx生命周期
* @return
*/
public RxAppCompatActivity getRxAppCompatActivity() {
return rxAppCompatActivity.get();
}
@Override
public T call(BaseResultEntity<T> httpResult) {
if (httpResult.getRet() == 0) {
|
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/HttpTimeException.java
// public class HttpTimeException extends RuntimeException {
//
// public static final int NO_DATA = 0x2;
//
// public HttpTimeException(int resultCode) {
// this(getApiExceptionMessage(resultCode));
// }
//
// public HttpTimeException(String detailMessage) {
// super(detailMessage);
// }
//
// /**
// * 转换错误数据
// *
// * @param code
// * @return
// */
// private static String getApiExceptionMessage(int code) {
// String message = "";
// switch (code) {
// case NO_DATA:
// message = "无数据";
// break;
// default:
// message = "error";
// break;
//
// }
// return message;
// }
// }
//
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java
// public abstract class HttpOnNextListener<T> {
// /**
// * 成功后回调方法
// * @param t
// */
// public abstract void onNext(T t);
//
// /**
// * 緩存回調結果
// * @param string
// */
// public void onCacheNext(String string){
//
// }
//
// /**
// * 成功后的ober返回,扩展链接式调用
// * @param observable
// */
// public void onNext(Observable observable){
//
// }
//
// /**
// * 失败或者错误方法
// * 主动调用,更加灵活
// * @param e
// */
// public void onError(Throwable e){
//
// }
//
// /**
// * 取消回調
// */
// public void onCancel(){
//
// }
//
//
// }
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/Api/BaseApi.java
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.HttpTimeException;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import java.lang.ref.SoftReference;
import retrofit2.Retrofit;
import rx.Observable;
import rx.functions.Func1;
this.retryCount = retryCount;
}
public long getRetryDelay() {
return retryDelay;
}
public void setRetryDelay(long retryDelay) {
this.retryDelay = retryDelay;
}
public long getRetryIncreaseDelay() {
return retryIncreaseDelay;
}
public void setRetryIncreaseDelay(long retryIncreaseDelay) {
this.retryIncreaseDelay = retryIncreaseDelay;
}
/*
* 获取当前rx生命周期
* @return
*/
public RxAppCompatActivity getRxAppCompatActivity() {
return rxAppCompatActivity.get();
}
@Override
public T call(BaseResultEntity<T> httpResult) {
if (httpResult.getRet() == 0) {
|
throw new HttpTimeException(httpResult.getMsg());
|
wzgiceman/RxjavaRetrofitDemo-master
|
rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/http/cookie/CacheInterceptor.java
|
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/utils/AppUtil.java
// public class AppUtil {
// /**
// * 描述:判断网络是否有效.
// *
// * @return true, if is network available
// */
// public static boolean isNetworkAvailable(Context context) {
// try {
// ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// if (connectivity != null) {
// NetworkInfo info = connectivity.getActiveNetworkInfo();
// if (info != null && info.isConnected()) {
// if (info.getState() == NetworkInfo.State.CONNECTED) {
// return true;
// }
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// return false;
// }
//
//
// /**
// * 读取baseurl
// * @param url
// * @return
// */
// public static String getBasUrl(String url) {
// String head = "";
// int index = url.indexOf("://");
// if (index != -1) {
// head = url.substring(0, index + 3);
// url = url.substring(index + 3);
// }
// index = url.indexOf("/");
// if (index != -1) {
// url = url.substring(0, index + 1);
// }
// return head + url;
// }
// }
|
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.RxRetrofitApp;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.utils.AppUtil;
import java.io.IOException;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
|
package com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.cookie;
/**
* get缓存方式拦截器
* Created by WZG on 2016/10/26.
*/
public class CacheInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
|
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/utils/AppUtil.java
// public class AppUtil {
// /**
// * 描述:判断网络是否有效.
// *
// * @return true, if is network available
// */
// public static boolean isNetworkAvailable(Context context) {
// try {
// ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// if (connectivity != null) {
// NetworkInfo info = connectivity.getActiveNetworkInfo();
// if (info != null && info.isConnected()) {
// if (info.getState() == NetworkInfo.State.CONNECTED) {
// return true;
// }
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// return false;
// }
//
//
// /**
// * 读取baseurl
// * @param url
// * @return
// */
// public static String getBasUrl(String url) {
// String head = "";
// int index = url.indexOf("://");
// if (index != -1) {
// head = url.substring(0, index + 3);
// url = url.substring(index + 3);
// }
// index = url.indexOf("/");
// if (index != -1) {
// url = url.substring(0, index + 1);
// }
// return head + url;
// }
// }
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/http/cookie/CacheInterceptor.java
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.RxRetrofitApp;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.utils.AppUtil;
import java.io.IOException;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
package com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.cookie;
/**
* get缓存方式拦截器
* Created by WZG on 2016/10/26.
*/
public class CacheInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
|
if (!AppUtil.isNetworkAvailable(RxRetrofitApp.getApplication())) {//没网强制从缓存读取(必须得写,不然断网状态下,退出应用,或者等待一分钟后,就获取不到缓存)
|
timeforcoffee/timeforcoffee-android
|
api/src/test/java/ch/liip/timeforcoffee/api/DepartureDeserializationTest.java
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Departure.java
// public class Departure {
//
// private int id;
// private String name;
// private String platform;
// private String to;
// private boolean accessible;
// private Color colors;
// private Time departure;
// private Time arrival;
//
// public Departure() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() { return name; }
//
// public String getPlatform() {
// return platform;
// }
//
// public String getTo() { return to; }
//
// public boolean isAccessible() {
// return accessible;
// }
//
// public Color getColors() {
// return colors;
// }
//
// public Time getDeparture() {
// return departure;
// }
//
// public Time getArrival() {
// return arrival;
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Departures.java
// public class Departures {
//
// private List<Departure> departures;
//
// private Meta meta;
//
// public Departures() {}
//
// public List<Departure> getDepartures() {
// return departures;
// }
//
// public Meta getMeta() { return meta; }
// }
|
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Departure;
import ch.liip.timeforcoffee.backend.Departures;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
|
package ch.liip.timeforcoffee.api;
public class DepartureDeserializationTest {
private final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private final Gson gson = new GsonBuilder()
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Departure.java
// public class Departure {
//
// private int id;
// private String name;
// private String platform;
// private String to;
// private boolean accessible;
// private Color colors;
// private Time departure;
// private Time arrival;
//
// public Departure() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() { return name; }
//
// public String getPlatform() {
// return platform;
// }
//
// public String getTo() { return to; }
//
// public boolean isAccessible() {
// return accessible;
// }
//
// public Color getColors() {
// return colors;
// }
//
// public Time getDeparture() {
// return departure;
// }
//
// public Time getArrival() {
// return arrival;
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Departures.java
// public class Departures {
//
// private List<Departure> departures;
//
// private Meta meta;
//
// public Departures() {}
//
// public List<Departure> getDepartures() {
// return departures;
// }
//
// public Meta getMeta() { return meta; }
// }
// Path: api/src/test/java/ch/liip/timeforcoffee/api/DepartureDeserializationTest.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Departure;
import ch.liip.timeforcoffee.backend.Departures;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
package ch.liip.timeforcoffee.api;
public class DepartureDeserializationTest {
private final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private final Gson gson = new GsonBuilder()
|
.registerTypeAdapter(Date.class, new DateDeserializer())
|
timeforcoffee/timeforcoffee-android
|
api/src/test/java/ch/liip/timeforcoffee/api/DepartureDeserializationTest.java
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Departure.java
// public class Departure {
//
// private int id;
// private String name;
// private String platform;
// private String to;
// private boolean accessible;
// private Color colors;
// private Time departure;
// private Time arrival;
//
// public Departure() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() { return name; }
//
// public String getPlatform() {
// return platform;
// }
//
// public String getTo() { return to; }
//
// public boolean isAccessible() {
// return accessible;
// }
//
// public Color getColors() {
// return colors;
// }
//
// public Time getDeparture() {
// return departure;
// }
//
// public Time getArrival() {
// return arrival;
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Departures.java
// public class Departures {
//
// private List<Departure> departures;
//
// private Meta meta;
//
// public Departures() {}
//
// public List<Departure> getDepartures() {
// return departures;
// }
//
// public Meta getMeta() { return meta; }
// }
|
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Departure;
import ch.liip.timeforcoffee.backend.Departures;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
|
package ch.liip.timeforcoffee.api;
public class DepartureDeserializationTest {
private final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
@Test
public void departuresDeserialization_Works() throws UnsupportedEncodingException {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("departures.json");
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Departure.java
// public class Departure {
//
// private int id;
// private String name;
// private String platform;
// private String to;
// private boolean accessible;
// private Color colors;
// private Time departure;
// private Time arrival;
//
// public Departure() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() { return name; }
//
// public String getPlatform() {
// return platform;
// }
//
// public String getTo() { return to; }
//
// public boolean isAccessible() {
// return accessible;
// }
//
// public Color getColors() {
// return colors;
// }
//
// public Time getDeparture() {
// return departure;
// }
//
// public Time getArrival() {
// return arrival;
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Departures.java
// public class Departures {
//
// private List<Departure> departures;
//
// private Meta meta;
//
// public Departures() {}
//
// public List<Departure> getDepartures() {
// return departures;
// }
//
// public Meta getMeta() { return meta; }
// }
// Path: api/src/test/java/ch/liip/timeforcoffee/api/DepartureDeserializationTest.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Departure;
import ch.liip.timeforcoffee.backend.Departures;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
package ch.liip.timeforcoffee.api;
public class DepartureDeserializationTest {
private final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
@Test
public void departuresDeserialization_Works() throws UnsupportedEncodingException {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("departures.json");
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
|
Departures departures = gson.fromJson(reader, Departures.class);
|
timeforcoffee/timeforcoffee-android
|
api/src/test/java/ch/liip/timeforcoffee/api/DepartureDeserializationTest.java
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Departure.java
// public class Departure {
//
// private int id;
// private String name;
// private String platform;
// private String to;
// private boolean accessible;
// private Color colors;
// private Time departure;
// private Time arrival;
//
// public Departure() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() { return name; }
//
// public String getPlatform() {
// return platform;
// }
//
// public String getTo() { return to; }
//
// public boolean isAccessible() {
// return accessible;
// }
//
// public Color getColors() {
// return colors;
// }
//
// public Time getDeparture() {
// return departure;
// }
//
// public Time getArrival() {
// return arrival;
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Departures.java
// public class Departures {
//
// private List<Departure> departures;
//
// private Meta meta;
//
// public Departures() {}
//
// public List<Departure> getDepartures() {
// return departures;
// }
//
// public Meta getMeta() { return meta; }
// }
|
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Departure;
import ch.liip.timeforcoffee.backend.Departures;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
|
package ch.liip.timeforcoffee.api;
public class DepartureDeserializationTest {
private final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
@Test
public void departuresDeserialization_Works() throws UnsupportedEncodingException {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("departures.json");
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
Departures departures = gson.fromJson(reader, Departures.class);
assertEquals(3, departures.getDepartures().size());
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Departure.java
// public class Departure {
//
// private int id;
// private String name;
// private String platform;
// private String to;
// private boolean accessible;
// private Color colors;
// private Time departure;
// private Time arrival;
//
// public Departure() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() { return name; }
//
// public String getPlatform() {
// return platform;
// }
//
// public String getTo() { return to; }
//
// public boolean isAccessible() {
// return accessible;
// }
//
// public Color getColors() {
// return colors;
// }
//
// public Time getDeparture() {
// return departure;
// }
//
// public Time getArrival() {
// return arrival;
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Departures.java
// public class Departures {
//
// private List<Departure> departures;
//
// private Meta meta;
//
// public Departures() {}
//
// public List<Departure> getDepartures() {
// return departures;
// }
//
// public Meta getMeta() { return meta; }
// }
// Path: api/src/test/java/ch/liip/timeforcoffee/api/DepartureDeserializationTest.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Departure;
import ch.liip.timeforcoffee.backend.Departures;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
package ch.liip.timeforcoffee.api;
public class DepartureDeserializationTest {
private final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
@Test
public void departuresDeserialization_Works() throws UnsupportedEncodingException {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("departures.json");
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
Departures departures = gson.fromJson(reader, Departures.class);
assertEquals(3, departures.getDepartures().size());
|
Departure departure1 = departures.getDepartures().get(0);
|
timeforcoffee/timeforcoffee-android
|
api/src/test/java/ch/liip/timeforcoffee/api/ConnectionDeserializationTest.java
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Connection.java
// public class Connection {
//
// private int id;
// private String name;
// private ConnectionLocation location;
// private Time departure;
// private Time arrival;
//
// public Connection() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public ConnectionLocation getLocation() {
// return location;
// }
//
// public Time getDeparture() { return departure; }
//
// public Time getArrival() { return arrival; }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Connections.java
// public class Connections {
//
// private List<List<Connection>> passlist;
//
// public Connections() {}
//
// public List<List<Connection>> getConnections() {
// return passlist;
// }
// }
|
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Connection;
import ch.liip.timeforcoffee.backend.Connections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
|
package ch.liip.timeforcoffee.api;
public class ConnectionDeserializationTest {
private final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private final Gson gson = new GsonBuilder()
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Connection.java
// public class Connection {
//
// private int id;
// private String name;
// private ConnectionLocation location;
// private Time departure;
// private Time arrival;
//
// public Connection() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public ConnectionLocation getLocation() {
// return location;
// }
//
// public Time getDeparture() { return departure; }
//
// public Time getArrival() { return arrival; }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Connections.java
// public class Connections {
//
// private List<List<Connection>> passlist;
//
// public Connections() {}
//
// public List<List<Connection>> getConnections() {
// return passlist;
// }
// }
// Path: api/src/test/java/ch/liip/timeforcoffee/api/ConnectionDeserializationTest.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Connection;
import ch.liip.timeforcoffee.backend.Connections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
package ch.liip.timeforcoffee.api;
public class ConnectionDeserializationTest {
private final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private final Gson gson = new GsonBuilder()
|
.registerTypeAdapter(Date.class, new DateDeserializer())
|
timeforcoffee/timeforcoffee-android
|
api/src/test/java/ch/liip/timeforcoffee/api/ConnectionDeserializationTest.java
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Connection.java
// public class Connection {
//
// private int id;
// private String name;
// private ConnectionLocation location;
// private Time departure;
// private Time arrival;
//
// public Connection() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public ConnectionLocation getLocation() {
// return location;
// }
//
// public Time getDeparture() { return departure; }
//
// public Time getArrival() { return arrival; }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Connections.java
// public class Connections {
//
// private List<List<Connection>> passlist;
//
// public Connections() {}
//
// public List<List<Connection>> getConnections() {
// return passlist;
// }
// }
|
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Connection;
import ch.liip.timeforcoffee.backend.Connections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
|
package ch.liip.timeforcoffee.api;
public class ConnectionDeserializationTest {
private final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
@Test
public void connectionsDeserialization_Works() throws UnsupportedEncodingException {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("connections.json");
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Connection.java
// public class Connection {
//
// private int id;
// private String name;
// private ConnectionLocation location;
// private Time departure;
// private Time arrival;
//
// public Connection() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public ConnectionLocation getLocation() {
// return location;
// }
//
// public Time getDeparture() { return departure; }
//
// public Time getArrival() { return arrival; }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Connections.java
// public class Connections {
//
// private List<List<Connection>> passlist;
//
// public Connections() {}
//
// public List<List<Connection>> getConnections() {
// return passlist;
// }
// }
// Path: api/src/test/java/ch/liip/timeforcoffee/api/ConnectionDeserializationTest.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Connection;
import ch.liip.timeforcoffee.backend.Connections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
package ch.liip.timeforcoffee.api;
public class ConnectionDeserializationTest {
private final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
@Test
public void connectionsDeserialization_Works() throws UnsupportedEncodingException {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("connections.json");
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
|
Connections connections = gson.fromJson(reader, Connections.class);
|
timeforcoffee/timeforcoffee-android
|
api/src/test/java/ch/liip/timeforcoffee/api/ConnectionDeserializationTest.java
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Connection.java
// public class Connection {
//
// private int id;
// private String name;
// private ConnectionLocation location;
// private Time departure;
// private Time arrival;
//
// public Connection() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public ConnectionLocation getLocation() {
// return location;
// }
//
// public Time getDeparture() { return departure; }
//
// public Time getArrival() { return arrival; }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Connections.java
// public class Connections {
//
// private List<List<Connection>> passlist;
//
// public Connections() {}
//
// public List<List<Connection>> getConnections() {
// return passlist;
// }
// }
|
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Connection;
import ch.liip.timeforcoffee.backend.Connections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
|
package ch.liip.timeforcoffee.api;
public class ConnectionDeserializationTest {
private final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
@Test
public void connectionsDeserialization_Works() throws UnsupportedEncodingException {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("connections.json");
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
Connections connections = gson.fromJson(reader, Connections.class);
assertEquals(1, connections.getConnections().size());
assertEquals(5, connections.getConnections().get(0).size());
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Connection.java
// public class Connection {
//
// private int id;
// private String name;
// private ConnectionLocation location;
// private Time departure;
// private Time arrival;
//
// public Connection() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public ConnectionLocation getLocation() {
// return location;
// }
//
// public Time getDeparture() { return departure; }
//
// public Time getArrival() { return arrival; }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Connections.java
// public class Connections {
//
// private List<List<Connection>> passlist;
//
// public Connections() {}
//
// public List<List<Connection>> getConnections() {
// return passlist;
// }
// }
// Path: api/src/test/java/ch/liip/timeforcoffee/api/ConnectionDeserializationTest.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Connection;
import ch.liip.timeforcoffee.backend.Connections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
package ch.liip.timeforcoffee.api;
public class ConnectionDeserializationTest {
private final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
@Test
public void connectionsDeserialization_Works() throws UnsupportedEncodingException {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("connections.json");
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
Connections connections = gson.fromJson(reader, Connections.class);
assertEquals(1, connections.getConnections().size());
assertEquals(5, connections.getConnections().get(0).size());
|
Connection connection1 = connections.getConnections().get(0).get(0);
|
timeforcoffee/timeforcoffee-android
|
api/src/test/java/ch/liip/timeforcoffee/api/StationDeserializationTest.java
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Station.java
// public class Station {
//
// private int id;
// private String name;
// private Location coordinate;
//
// public Station() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public Location getCoordinate() {
// return coordinate;
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Stations.java
// public class Stations {
//
// private List<Station> stations;
//
// public Stations() {}
//
// public List<Station> getStations() {
// return stations;
// }
// }
|
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Station;
import ch.liip.timeforcoffee.backend.Stations;
import static org.junit.Assert.assertEquals;
|
package ch.liip.timeforcoffee.api;
public class StationDeserializationTest {
private final Gson gson = new GsonBuilder()
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Station.java
// public class Station {
//
// private int id;
// private String name;
// private Location coordinate;
//
// public Station() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public Location getCoordinate() {
// return coordinate;
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Stations.java
// public class Stations {
//
// private List<Station> stations;
//
// public Stations() {}
//
// public List<Station> getStations() {
// return stations;
// }
// }
// Path: api/src/test/java/ch/liip/timeforcoffee/api/StationDeserializationTest.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Station;
import ch.liip.timeforcoffee.backend.Stations;
import static org.junit.Assert.assertEquals;
package ch.liip.timeforcoffee.api;
public class StationDeserializationTest {
private final Gson gson = new GsonBuilder()
|
.registerTypeAdapter(Date.class, new DateDeserializer())
|
timeforcoffee/timeforcoffee-android
|
api/src/test/java/ch/liip/timeforcoffee/api/StationDeserializationTest.java
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Station.java
// public class Station {
//
// private int id;
// private String name;
// private Location coordinate;
//
// public Station() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public Location getCoordinate() {
// return coordinate;
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Stations.java
// public class Stations {
//
// private List<Station> stations;
//
// public Stations() {}
//
// public List<Station> getStations() {
// return stations;
// }
// }
|
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Station;
import ch.liip.timeforcoffee.backend.Stations;
import static org.junit.Assert.assertEquals;
|
package ch.liip.timeforcoffee.api;
public class StationDeserializationTest {
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
@Test
public void stationsForLocationDeserialization_Works() throws UnsupportedEncodingException {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("stations_for_location.json");
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Station.java
// public class Station {
//
// private int id;
// private String name;
// private Location coordinate;
//
// public Station() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public Location getCoordinate() {
// return coordinate;
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Stations.java
// public class Stations {
//
// private List<Station> stations;
//
// public Stations() {}
//
// public List<Station> getStations() {
// return stations;
// }
// }
// Path: api/src/test/java/ch/liip/timeforcoffee/api/StationDeserializationTest.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Station;
import ch.liip.timeforcoffee.backend.Stations;
import static org.junit.Assert.assertEquals;
package ch.liip.timeforcoffee.api;
public class StationDeserializationTest {
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
@Test
public void stationsForLocationDeserialization_Works() throws UnsupportedEncodingException {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("stations_for_location.json");
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
|
Stations stations = gson.fromJson(reader, Stations.class);
|
timeforcoffee/timeforcoffee-android
|
api/src/test/java/ch/liip/timeforcoffee/api/StationDeserializationTest.java
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Station.java
// public class Station {
//
// private int id;
// private String name;
// private Location coordinate;
//
// public Station() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public Location getCoordinate() {
// return coordinate;
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Stations.java
// public class Stations {
//
// private List<Station> stations;
//
// public Stations() {}
//
// public List<Station> getStations() {
// return stations;
// }
// }
|
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Station;
import ch.liip.timeforcoffee.backend.Stations;
import static org.junit.Assert.assertEquals;
|
package ch.liip.timeforcoffee.api;
public class StationDeserializationTest {
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
@Test
public void stationsForLocationDeserialization_Works() throws UnsupportedEncodingException {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("stations_for_location.json");
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
Stations stations = gson.fromJson(reader, Stations.class);
assertEquals(4, stations.getStations().size());
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/deserializers/DateDeserializer.java
// public class DateDeserializer implements JsonDeserializer<Date> {
//
// private final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ssZ" };
//
// @Override
// public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
// for (String format : DATE_FORMATS) {
// try {
// return new SimpleDateFormat(format).parse(jsonElement.getAsString());
// } catch (ParseException e) { }
// }
//
// throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Station.java
// public class Station {
//
// private int id;
// private String name;
// private Location coordinate;
//
// public Station() {}
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public Location getCoordinate() {
// return coordinate;
// }
// }
//
// Path: backend/src/main/java/ch/liip/timeforcoffee/backend/Stations.java
// public class Stations {
//
// private List<Station> stations;
//
// public Stations() {}
//
// public List<Station> getStations() {
// return stations;
// }
// }
// Path: api/src/test/java/ch/liip/timeforcoffee/api/StationDeserializationTest.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import ch.liip.timeforcoffee.api.deserializers.DateDeserializer;
import ch.liip.timeforcoffee.backend.Station;
import ch.liip.timeforcoffee.backend.Stations;
import static org.junit.Assert.assertEquals;
package ch.liip.timeforcoffee.api;
public class StationDeserializationTest {
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
@Test
public void stationsForLocationDeserialization_Works() throws UnsupportedEncodingException {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("stations_for_location.json");
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
Stations stations = gson.fromJson(reader, Stations.class);
assertEquals(4, stations.getStations().size());
|
Station station1 = stations.getStations().get(0);
|
timeforcoffee/timeforcoffee-android
|
mobile/src/main/java/ch/liip/timeforcoffee/adapter/StationListAdapter.java
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/models/Station.java
// public class Station {
//
// private final int id;
// private final String name;
// private final Location location;
// private final float distance;
// private boolean isFavorite;
//
// public Station(int id, String name, float distance, Location location, boolean isFavorite) {
// this.id = id;
// this.name = name;
// this.location = location;
// this.distance = distance;
// this.isFavorite = isFavorite;
// }
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public Location getLocation() {
// return location;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public boolean getIsFavorite() {
// return isFavorite;
// }
//
// public void setIsFavorite(boolean isFavorite) {
// this.isFavorite = isFavorite;
// }
//
// public String getDistanceForDisplay(Location userLocation) {
//
// if (userLocation != null) {
// int directDistance = getDistanceInMeter(userLocation);
//
// if (directDistance > 5000) {
// int km = (int) (Math.round((double) (directDistance) / 1000));
// return km + " km";
// } else {
// return directDistance + " m";
// }
// }
// return null;
// }
//
// private int getDistanceInMeter(Location userLocation) {
// if (userLocation != null) {
// return (int) userLocation.distanceTo(location);
// }
// return 0;
// }
//
// @Override
// public boolean equals(Object object) {
// boolean sameName = false;
//
// if (object instanceof Station) {
// sameName = this.name.equals(((Station) object).getName());
// }
//
// return sameName;
// }
// }
//
// Path: mobile/src/main/java/ch/liip/timeforcoffee/widget/FavoriteButton.java
// public class FavoriteButton extends ImageSwitcher implements View.OnClickListener, ViewSwitcher.ViewFactory
// {
// private boolean mIsFavorite = false;
//
// private OnClickListener clickListener;
//
// private void init() {
// setFactory(this);
// setOnClickListener(this);
// if(mIsFavorite) {
// setImageResource(R.drawable.shape_star);
// } else {
// setImageResource(R.drawable.shape_place);
// }
// Animation inAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.grow);
// Animation outAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.shrink);
// setInAnimation(inAnimation);
// setOutAnimation(outAnimation);
// }
//
// public void setIsFavorite(boolean isFavorite)
// {
// this.mIsFavorite = isFavorite;
//
// if(mIsFavorite) {
// setImageResource(R.drawable.shape_star);
// } else {
// setImageResource(R.drawable.shape_place);
// }
// }
//
// public FavoriteButton(Context context) {
// super(context);
// init();
// }
//
// public FavoriteButton(Context context, AttributeSet attrs) {
// super(context, attrs);
// init();
// }
//
// @Override
// public void setOnClickListener(OnClickListener l) {
// if (l == this) {
// super.setOnClickListener(l);
// } else {
// clickListener = l;
// }
// }
//
// @Override
// public void onClick(View v) {
//
// mIsFavorite = !mIsFavorite;
//
// if(mIsFavorite) {
// setImageResource(R.drawable.shape_star);
// } else {
// setImageResource(R.drawable.shape_place);
// }
//
// if (clickListener != null) {
// clickListener.onClick(this);
// }
// }
//
// @Override
// public View makeView() {
// ImageView view = new ImageView(getContext());
// view.setScaleType(ImageView.ScaleType.FIT_CENTER);
// view.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.
// MATCH_PARENT,LayoutParams.MATCH_PARENT));
// return view;
// }
// }
|
import android.content.Context;
import android.location.Location;
import android.os.Build;
import androidx.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import ch.liip.timeforcoffee.R;
import ch.liip.timeforcoffee.api.models.Station;
import ch.liip.timeforcoffee.widget.FavoriteButton;
import io.nlopez.smartlocation.SmartLocation;
|
}
public Station getStation(int position) {
return this.mStations.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public Station getItem(int position) {
return this.mStations.get(position);
}
@Override
public int getCount() {
return this.mStations.size();
}
public void setStations(List<Station> stations) {
this.mStations.clear();
this.mStations.addAll(stations);
notifyDataSetChanged();
}
private static class StationViewHolder {
TextView nameTextView;
TextView distanceTextView;
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/models/Station.java
// public class Station {
//
// private final int id;
// private final String name;
// private final Location location;
// private final float distance;
// private boolean isFavorite;
//
// public Station(int id, String name, float distance, Location location, boolean isFavorite) {
// this.id = id;
// this.name = name;
// this.location = location;
// this.distance = distance;
// this.isFavorite = isFavorite;
// }
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public Location getLocation() {
// return location;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public boolean getIsFavorite() {
// return isFavorite;
// }
//
// public void setIsFavorite(boolean isFavorite) {
// this.isFavorite = isFavorite;
// }
//
// public String getDistanceForDisplay(Location userLocation) {
//
// if (userLocation != null) {
// int directDistance = getDistanceInMeter(userLocation);
//
// if (directDistance > 5000) {
// int km = (int) (Math.round((double) (directDistance) / 1000));
// return km + " km";
// } else {
// return directDistance + " m";
// }
// }
// return null;
// }
//
// private int getDistanceInMeter(Location userLocation) {
// if (userLocation != null) {
// return (int) userLocation.distanceTo(location);
// }
// return 0;
// }
//
// @Override
// public boolean equals(Object object) {
// boolean sameName = false;
//
// if (object instanceof Station) {
// sameName = this.name.equals(((Station) object).getName());
// }
//
// return sameName;
// }
// }
//
// Path: mobile/src/main/java/ch/liip/timeforcoffee/widget/FavoriteButton.java
// public class FavoriteButton extends ImageSwitcher implements View.OnClickListener, ViewSwitcher.ViewFactory
// {
// private boolean mIsFavorite = false;
//
// private OnClickListener clickListener;
//
// private void init() {
// setFactory(this);
// setOnClickListener(this);
// if(mIsFavorite) {
// setImageResource(R.drawable.shape_star);
// } else {
// setImageResource(R.drawable.shape_place);
// }
// Animation inAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.grow);
// Animation outAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.shrink);
// setInAnimation(inAnimation);
// setOutAnimation(outAnimation);
// }
//
// public void setIsFavorite(boolean isFavorite)
// {
// this.mIsFavorite = isFavorite;
//
// if(mIsFavorite) {
// setImageResource(R.drawable.shape_star);
// } else {
// setImageResource(R.drawable.shape_place);
// }
// }
//
// public FavoriteButton(Context context) {
// super(context);
// init();
// }
//
// public FavoriteButton(Context context, AttributeSet attrs) {
// super(context, attrs);
// init();
// }
//
// @Override
// public void setOnClickListener(OnClickListener l) {
// if (l == this) {
// super.setOnClickListener(l);
// } else {
// clickListener = l;
// }
// }
//
// @Override
// public void onClick(View v) {
//
// mIsFavorite = !mIsFavorite;
//
// if(mIsFavorite) {
// setImageResource(R.drawable.shape_star);
// } else {
// setImageResource(R.drawable.shape_place);
// }
//
// if (clickListener != null) {
// clickListener.onClick(this);
// }
// }
//
// @Override
// public View makeView() {
// ImageView view = new ImageView(getContext());
// view.setScaleType(ImageView.ScaleType.FIT_CENTER);
// view.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.
// MATCH_PARENT,LayoutParams.MATCH_PARENT));
// return view;
// }
// }
// Path: mobile/src/main/java/ch/liip/timeforcoffee/adapter/StationListAdapter.java
import android.content.Context;
import android.location.Location;
import android.os.Build;
import androidx.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import ch.liip.timeforcoffee.R;
import ch.liip.timeforcoffee.api.models.Station;
import ch.liip.timeforcoffee.widget.FavoriteButton;
import io.nlopez.smartlocation.SmartLocation;
}
public Station getStation(int position) {
return this.mStations.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public Station getItem(int position) {
return this.mStations.get(position);
}
@Override
public int getCount() {
return this.mStations.size();
}
public void setStations(List<Station> stations) {
this.mStations.clear();
this.mStations.addAll(stations);
notifyDataSetChanged();
}
private static class StationViewHolder {
TextView nameTextView;
TextView distanceTextView;
|
FavoriteButton favoriteButton;
|
timeforcoffee/timeforcoffee-android
|
wear/src/main/java/ch/liip/timeforcoffee/adapter/StationListAdapter.java
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/models/Station.java
// public class Station {
//
// private final int id;
// private final String name;
// private final Location location;
// private final float distance;
// private boolean isFavorite;
//
// public Station(int id, String name, float distance, Location location, boolean isFavorite) {
// this.id = id;
// this.name = name;
// this.location = location;
// this.distance = distance;
// this.isFavorite = isFavorite;
// }
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public Location getLocation() {
// return location;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public boolean getIsFavorite() {
// return isFavorite;
// }
//
// public void setIsFavorite(boolean isFavorite) {
// this.isFavorite = isFavorite;
// }
//
// public String getDistanceForDisplay(Location userLocation) {
//
// if (userLocation != null) {
// int directDistance = getDistanceInMeter(userLocation);
//
// if (directDistance > 5000) {
// int km = (int) (Math.round((double) (directDistance) / 1000));
// return km + " km";
// } else {
// return directDistance + " m";
// }
// }
// return null;
// }
//
// private int getDistanceInMeter(Location userLocation) {
// if (userLocation != null) {
// return (int) userLocation.distanceTo(location);
// }
// return 0;
// }
//
// @Override
// public boolean equals(Object object) {
// boolean sameName = false;
//
// if (object instanceof Station) {
// sameName = this.name.equals(((Station) object).getName());
// }
//
// return sameName;
// }
// }
//
// Path: wear/src/main/java/ch/liip/timeforcoffee/view/StationItemView.java
// public final class StationItemView extends FrameLayout implements WearableListView.OnCenterProximityListener {
//
// final TextView mName;
// final ImageView mImage;
//
// public StationItemView(Context context) {
// super(context);
// View.inflate(context, R.layout.station_item, this);
// mName = (TextView) findViewById(R.id.name);
// mImage = (ImageView) findViewById(R.id.place);
// }
//
// @Override
// public void onCenterPosition(boolean b) {
// mImage.setAlpha(1f);
// mImage.setAlpha(1f);
// }
//
// @Override
// public void onNonCenterPosition(boolean b) {
// mImage.setAlpha(0.6f);
// mImage.setAlpha(0.6f);
// }
// }
|
import android.content.Context;
import android.support.wearable.view.WearableListView;
import android.view.ViewGroup;
import android.widget.TextView;
import ch.liip.timeforcoffee.R;
import ch.liip.timeforcoffee.api.models.Station;
import ch.liip.timeforcoffee.view.StationItemView;
import java.util.List;
|
package ch.liip.timeforcoffee.adapter;
/**
* Created by fsantschi on 08/03/15.
*/
public class StationListAdapter extends WearableListView.Adapter {
private List<Station> mStations;
private Context mContext;
public StationListAdapter(Context context, List<Station> stations) {
mStations = stations;
mContext = context;
}
@Override
public WearableListView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/models/Station.java
// public class Station {
//
// private final int id;
// private final String name;
// private final Location location;
// private final float distance;
// private boolean isFavorite;
//
// public Station(int id, String name, float distance, Location location, boolean isFavorite) {
// this.id = id;
// this.name = name;
// this.location = location;
// this.distance = distance;
// this.isFavorite = isFavorite;
// }
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public Location getLocation() {
// return location;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public boolean getIsFavorite() {
// return isFavorite;
// }
//
// public void setIsFavorite(boolean isFavorite) {
// this.isFavorite = isFavorite;
// }
//
// public String getDistanceForDisplay(Location userLocation) {
//
// if (userLocation != null) {
// int directDistance = getDistanceInMeter(userLocation);
//
// if (directDistance > 5000) {
// int km = (int) (Math.round((double) (directDistance) / 1000));
// return km + " km";
// } else {
// return directDistance + " m";
// }
// }
// return null;
// }
//
// private int getDistanceInMeter(Location userLocation) {
// if (userLocation != null) {
// return (int) userLocation.distanceTo(location);
// }
// return 0;
// }
//
// @Override
// public boolean equals(Object object) {
// boolean sameName = false;
//
// if (object instanceof Station) {
// sameName = this.name.equals(((Station) object).getName());
// }
//
// return sameName;
// }
// }
//
// Path: wear/src/main/java/ch/liip/timeforcoffee/view/StationItemView.java
// public final class StationItemView extends FrameLayout implements WearableListView.OnCenterProximityListener {
//
// final TextView mName;
// final ImageView mImage;
//
// public StationItemView(Context context) {
// super(context);
// View.inflate(context, R.layout.station_item, this);
// mName = (TextView) findViewById(R.id.name);
// mImage = (ImageView) findViewById(R.id.place);
// }
//
// @Override
// public void onCenterPosition(boolean b) {
// mImage.setAlpha(1f);
// mImage.setAlpha(1f);
// }
//
// @Override
// public void onNonCenterPosition(boolean b) {
// mImage.setAlpha(0.6f);
// mImage.setAlpha(0.6f);
// }
// }
// Path: wear/src/main/java/ch/liip/timeforcoffee/adapter/StationListAdapter.java
import android.content.Context;
import android.support.wearable.view.WearableListView;
import android.view.ViewGroup;
import android.widget.TextView;
import ch.liip.timeforcoffee.R;
import ch.liip.timeforcoffee.api.models.Station;
import ch.liip.timeforcoffee.view.StationItemView;
import java.util.List;
package ch.liip.timeforcoffee.adapter;
/**
* Created by fsantschi on 08/03/15.
*/
public class StationListAdapter extends WearableListView.Adapter {
private List<Station> mStations;
private Context mContext;
public StationListAdapter(Context context, List<Station> stations) {
mStations = stations;
mContext = context;
}
@Override
public WearableListView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
|
return new WearableListView.ViewHolder(new StationItemView(mContext));
|
timeforcoffee/timeforcoffee-android
|
mobile/src/main/java/ch/liip/timeforcoffee/helper/FavoritesDatabaseHelper.java
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/models/Station.java
// public class Station {
//
// private final int id;
// private final String name;
// private final Location location;
// private final float distance;
// private boolean isFavorite;
//
// public Station(int id, String name, float distance, Location location, boolean isFavorite) {
// this.id = id;
// this.name = name;
// this.location = location;
// this.distance = distance;
// this.isFavorite = isFavorite;
// }
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public Location getLocation() {
// return location;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public boolean getIsFavorite() {
// return isFavorite;
// }
//
// public void setIsFavorite(boolean isFavorite) {
// this.isFavorite = isFavorite;
// }
//
// public String getDistanceForDisplay(Location userLocation) {
//
// if (userLocation != null) {
// int directDistance = getDistanceInMeter(userLocation);
//
// if (directDistance > 5000) {
// int km = (int) (Math.round((double) (directDistance) / 1000));
// return km + " km";
// } else {
// return directDistance + " m";
// }
// }
// return null;
// }
//
// private int getDistanceInMeter(Location userLocation) {
// if (userLocation != null) {
// return (int) userLocation.distanceTo(location);
// }
// return 0;
// }
//
// @Override
// public boolean equals(Object object) {
// boolean sameName = false;
//
// if (object instanceof Station) {
// sameName = this.name.equals(((Station) object).getName());
// }
//
// return sameName;
// }
// }
|
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.location.Location;
import android.provider.BaseColumns;
import java.util.ArrayList;
import java.util.List;
import ch.liip.timeforcoffee.api.models.Station;
|
private static final String SQL_CREATE_STATION_TABLE =
"CREATE TABLE " + FavoriteStationColumn.TABLE_NAME + " (" +
FavoriteStationColumn.COLUMN_ID + " INTEGER PRIMARY KEY," +
FavoriteStationColumn.COLUMN_STATION_ID + INT_TYPE + COMMA_SEP +
FavoriteStationColumn.COLUMN_NAME + TEXT_TYPE + COMMA_SEP +
FavoriteStationColumn.COLUMN_LATITUDE + DOUBLE_TYPE + COMMA_SEP +
FavoriteStationColumn.COLUMN_LONGITUDE + DOUBLE_TYPE + " )";
private static final String SQL_CREATE_LINE_TABLE =
"CREATE TABLE " + FavoriteLineColumn.TABLE_NAME + " (" +
FavoriteLineColumn.COLUMN_ID + " INTEGER PRIMARY KEY," +
FavoriteLineColumn.COLUMN_NAME + TEXT_TYPE + COMMA_SEP +
FavoriteLineColumn.COLUMN_DESTINATION_ID + INT_TYPE + " )";
private static final String SQL_DELETE_STATION_TABLE = "DROP TABLE IF EXISTS " + FavoriteStationColumn.TABLE_NAME;
private static final String SQL_DELETE_OLD_STATION_TABLE = "DROP TABLE IF EXISTS " + FavoriteStationColumn.OLD_TABLE_NAME;
private static final String SQL_DELETE_LINE_TABLE = "DROP TABLE IF EXISTS " + FavoriteLineColumn.TABLE_NAME;
public FavoritesDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_STATION_TABLE);
db.execSQL(SQL_CREATE_LINE_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(oldVersion == 1 && newVersion == 2) {
// get old favorite stations
|
// Path: api/src/main/java/ch/liip/timeforcoffee/api/models/Station.java
// public class Station {
//
// private final int id;
// private final String name;
// private final Location location;
// private final float distance;
// private boolean isFavorite;
//
// public Station(int id, String name, float distance, Location location, boolean isFavorite) {
// this.id = id;
// this.name = name;
// this.location = location;
// this.distance = distance;
// this.isFavorite = isFavorite;
// }
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public Location getLocation() {
// return location;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public boolean getIsFavorite() {
// return isFavorite;
// }
//
// public void setIsFavorite(boolean isFavorite) {
// this.isFavorite = isFavorite;
// }
//
// public String getDistanceForDisplay(Location userLocation) {
//
// if (userLocation != null) {
// int directDistance = getDistanceInMeter(userLocation);
//
// if (directDistance > 5000) {
// int km = (int) (Math.round((double) (directDistance) / 1000));
// return km + " km";
// } else {
// return directDistance + " m";
// }
// }
// return null;
// }
//
// private int getDistanceInMeter(Location userLocation) {
// if (userLocation != null) {
// return (int) userLocation.distanceTo(location);
// }
// return 0;
// }
//
// @Override
// public boolean equals(Object object) {
// boolean sameName = false;
//
// if (object instanceof Station) {
// sameName = this.name.equals(((Station) object).getName());
// }
//
// return sameName;
// }
// }
// Path: mobile/src/main/java/ch/liip/timeforcoffee/helper/FavoritesDatabaseHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.location.Location;
import android.provider.BaseColumns;
import java.util.ArrayList;
import java.util.List;
import ch.liip.timeforcoffee.api.models.Station;
private static final String SQL_CREATE_STATION_TABLE =
"CREATE TABLE " + FavoriteStationColumn.TABLE_NAME + " (" +
FavoriteStationColumn.COLUMN_ID + " INTEGER PRIMARY KEY," +
FavoriteStationColumn.COLUMN_STATION_ID + INT_TYPE + COMMA_SEP +
FavoriteStationColumn.COLUMN_NAME + TEXT_TYPE + COMMA_SEP +
FavoriteStationColumn.COLUMN_LATITUDE + DOUBLE_TYPE + COMMA_SEP +
FavoriteStationColumn.COLUMN_LONGITUDE + DOUBLE_TYPE + " )";
private static final String SQL_CREATE_LINE_TABLE =
"CREATE TABLE " + FavoriteLineColumn.TABLE_NAME + " (" +
FavoriteLineColumn.COLUMN_ID + " INTEGER PRIMARY KEY," +
FavoriteLineColumn.COLUMN_NAME + TEXT_TYPE + COMMA_SEP +
FavoriteLineColumn.COLUMN_DESTINATION_ID + INT_TYPE + " )";
private static final String SQL_DELETE_STATION_TABLE = "DROP TABLE IF EXISTS " + FavoriteStationColumn.TABLE_NAME;
private static final String SQL_DELETE_OLD_STATION_TABLE = "DROP TABLE IF EXISTS " + FavoriteStationColumn.OLD_TABLE_NAME;
private static final String SQL_DELETE_LINE_TABLE = "DROP TABLE IF EXISTS " + FavoriteLineColumn.TABLE_NAME;
public FavoritesDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_STATION_TABLE);
db.execSQL(SQL_CREATE_LINE_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(oldVersion == 1 && newVersion == 2) {
// get old favorite stations
|
List<Station> oldFavoriteStations = new ArrayList<>();
|
timeforcoffee/timeforcoffee-android
|
mobile/src/main/java/ch/liip/timeforcoffee/helper/PermissionsChecker.java
|
// Path: mobile/src/main/java/ch/liip/timeforcoffee/widget/SnackBars.java
// public class SnackBars {
//
// public static void showNetworkError(Activity activity, View.OnClickListener listener) {
// Snackbar snackbar = Snackbar
// .make(activity.findViewById(R.id.content), activity.getResources().getString(R.string.network_error), Snackbar.LENGTH_INDEFINITE)
// .setAction(activity.getResources().getString(R.string.retry), listener);
//
// snackbar.show();
// }
//
// public static void showLocalisationServiceOff(final Activity activity) {
// Snackbar snackbar = Snackbar
// .make(activity.findViewById(R.id.content), activity.getResources().getString(R.string.location_service_off), Snackbar.LENGTH_INDEFINITE)
// .setAction(activity.getResources().getString(R.string.activate), new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// activity.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
// }
// });
//
// snackbar.show();
// }
//
// public static void showLocalisationServiceSetToDeviceOnly(final Activity activity) {
// Snackbar snackbar = Snackbar
// .make(activity.findViewById(R.id.content), activity.getResources().getString(R.string.location_service_gps_only), Snackbar.LENGTH_INDEFINITE)
// .setAction(activity.getResources().getString(R.string.location_service_gps_only_settings), new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// activity.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
// }
// });
//
// snackbar.show();
// }
//
// public static void showLocalisationSettings(final Activity activity) {
// Snackbar snackbar = Snackbar
// .make(activity.findViewById(R.id.content), activity.getResources().getString(R.string.permission_no_location), Snackbar.LENGTH_INDEFINITE)
// .setAction(activity.getResources().getString(R.string.grant), new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Intent intent = new Intent();
// intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
// Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
// intent.setData(uri);
// activity.startActivity(intent);
// }
// });
//
// snackbar.show();
// }
// }
|
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import ch.liip.timeforcoffee.R;
import ch.liip.timeforcoffee.widget.SnackBars;
|
package ch.liip.timeforcoffee.helper;
/**
* Created by nicolas on 06/03/16.
*/
public class PermissionsChecker {
Context context;
public PermissionsChecker(Context context) {
this.context = context;
}
public boolean LacksPermission(String permission) {
return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_DENIED;
}
public void RequestPermission(final Activity activity, final String permission, final int requestCode, String message) {
//Returns true if the app has requested this permission previously and the user denied the request.
//Return false if first time that permission is request or user checked "never ask again"
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.AppCompatAlertDialogStyle);
builder.setMessage(message);
builder.setPositiveButton(activity.getResources().getString(R.string.permission_allow), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode);
}
});
builder.setNegativeButton(activity.getResources().getString(R.string.permission_dont_allow), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
|
// Path: mobile/src/main/java/ch/liip/timeforcoffee/widget/SnackBars.java
// public class SnackBars {
//
// public static void showNetworkError(Activity activity, View.OnClickListener listener) {
// Snackbar snackbar = Snackbar
// .make(activity.findViewById(R.id.content), activity.getResources().getString(R.string.network_error), Snackbar.LENGTH_INDEFINITE)
// .setAction(activity.getResources().getString(R.string.retry), listener);
//
// snackbar.show();
// }
//
// public static void showLocalisationServiceOff(final Activity activity) {
// Snackbar snackbar = Snackbar
// .make(activity.findViewById(R.id.content), activity.getResources().getString(R.string.location_service_off), Snackbar.LENGTH_INDEFINITE)
// .setAction(activity.getResources().getString(R.string.activate), new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// activity.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
// }
// });
//
// snackbar.show();
// }
//
// public static void showLocalisationServiceSetToDeviceOnly(final Activity activity) {
// Snackbar snackbar = Snackbar
// .make(activity.findViewById(R.id.content), activity.getResources().getString(R.string.location_service_gps_only), Snackbar.LENGTH_INDEFINITE)
// .setAction(activity.getResources().getString(R.string.location_service_gps_only_settings), new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// activity.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
// }
// });
//
// snackbar.show();
// }
//
// public static void showLocalisationSettings(final Activity activity) {
// Snackbar snackbar = Snackbar
// .make(activity.findViewById(R.id.content), activity.getResources().getString(R.string.permission_no_location), Snackbar.LENGTH_INDEFINITE)
// .setAction(activity.getResources().getString(R.string.grant), new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Intent intent = new Intent();
// intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
// Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
// intent.setData(uri);
// activity.startActivity(intent);
// }
// });
//
// snackbar.show();
// }
// }
// Path: mobile/src/main/java/ch/liip/timeforcoffee/helper/PermissionsChecker.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import ch.liip.timeforcoffee.R;
import ch.liip.timeforcoffee.widget.SnackBars;
package ch.liip.timeforcoffee.helper;
/**
* Created by nicolas on 06/03/16.
*/
public class PermissionsChecker {
Context context;
public PermissionsChecker(Context context) {
this.context = context;
}
public boolean LacksPermission(String permission) {
return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_DENIED;
}
public void RequestPermission(final Activity activity, final String permission, final int requestCode, String message) {
//Returns true if the app has requested this permission previously and the user denied the request.
//Return false if first time that permission is request or user checked "never ask again"
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.AppCompatAlertDialogStyle);
builder.setMessage(message);
builder.setPositiveButton(activity.getResources().getString(R.string.permission_allow), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode);
}
});
builder.setNegativeButton(activity.getResources().getString(R.string.permission_dont_allow), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
|
SnackBars.showLocalisationSettings(activity);
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/Utils.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/exceptions/CPException.java
// public class CPException extends Exception{
//
// private static final long serialVersionUID = 1L;
// private String message;
//
// public CPException(String string) {
// message = string;
// }
//
// public String getMessage(){
// return message;
// }
// }
//
// Path: openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/exceptions/ExtParamException.java
// public class ExtParamException extends Exception{
//
// private static final long serialVersionUID = 1L;
// private String message;
//
// public ExtParamException(String string){
// message = string;
// }
//
// public String getMessage(){
// return message;
// }
// }
|
import android.util.Log;
import java.util.List;
import java.util.Vector;
import org.opencv.calib3d.Calib3d;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.MatOfPoint3f;
import org.opencv.core.Point;
import org.opencv.core.Point3;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.utils.Converters;
import es.ava.aruco.exceptions.CPException;
import es.ava.aruco.exceptions.ExtParamException;
|
// get the matrix corresponding to the rotation vector
Mat R = new Mat(3,3,CvType.CV_64FC1);
Calib3d.Rodrigues(rotation, R);
// create the matrix to rotate 90° around the X axis
// 1, 0, 0
// 0 cos -sin
// 0 sin cos
double[] rot = {
1, 0, 0,
0, 0, -1,
0, 1, 0
};
// multiply both matrix
Mat res = new Mat(3,3, CvType.CV_64FC1);
double[] prod = new double[9];
double[] a = new double[9];
R.get(0, 0, a);
for(int i=0;i<3;i++)
for(int j=0;j<3;j++){
prod[3*i+j] = 0;
for(int k=0;k<3;k++){
prod[3*i+j] += a[3*i+k]*rot[3*k+j];
}
}
// convert the matrix to a vector with rodrigues back
res.put(0, 0, prod);
Calib3d.Rodrigues(res, rotation);
}
|
// Path: openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/exceptions/CPException.java
// public class CPException extends Exception{
//
// private static final long serialVersionUID = 1L;
// private String message;
//
// public CPException(String string) {
// message = string;
// }
//
// public String getMessage(){
// return message;
// }
// }
//
// Path: openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/exceptions/ExtParamException.java
// public class ExtParamException extends Exception{
//
// private static final long serialVersionUID = 1L;
// private String message;
//
// public ExtParamException(String string){
// message = string;
// }
//
// public String getMessage(){
// return message;
// }
// }
// Path: openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/Utils.java
import android.util.Log;
import java.util.List;
import java.util.Vector;
import org.opencv.calib3d.Calib3d;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.MatOfPoint3f;
import org.opencv.core.Point;
import org.opencv.core.Point3;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.utils.Converters;
import es.ava.aruco.exceptions.CPException;
import es.ava.aruco.exceptions.ExtParamException;
// get the matrix corresponding to the rotation vector
Mat R = new Mat(3,3,CvType.CV_64FC1);
Calib3d.Rodrigues(rotation, R);
// create the matrix to rotate 90° around the X axis
// 1, 0, 0
// 0 cos -sin
// 0 sin cos
double[] rot = {
1, 0, 0,
0, 0, -1,
0, 1, 0
};
// multiply both matrix
Mat res = new Mat(3,3, CvType.CV_64FC1);
double[] prod = new double[9];
double[] a = new double[9];
R.get(0, 0, a);
for(int i=0;i<3;i++)
for(int j=0;j<3;j++){
prod[3*i+j] = 0;
for(int k=0;k<3;k++){
prod[3*i+j] += a[3*i+k]*rot[3*k+j];
}
}
// convert the matrix to a vector with rodrigues back
res.put(0, 0, prod);
Calib3d.Rodrigues(res, rotation);
}
|
protected static void glGetModelViewMatrix(double[] modelview_matrix, Mat Rvec, Mat Tvec)throws ExtParamException{
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/Utils.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/exceptions/CPException.java
// public class CPException extends Exception{
//
// private static final long serialVersionUID = 1L;
// private String message;
//
// public CPException(String string) {
// message = string;
// }
//
// public String getMessage(){
// return message;
// }
// }
//
// Path: openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/exceptions/ExtParamException.java
// public class ExtParamException extends Exception{
//
// private static final long serialVersionUID = 1L;
// private String message;
//
// public ExtParamException(String string){
// message = string;
// }
//
// public String getMessage(){
// return message;
// }
// }
|
import android.util.Log;
import java.util.List;
import java.util.Vector;
import org.opencv.calib3d.Calib3d;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.MatOfPoint3f;
import org.opencv.core.Point;
import org.opencv.core.Point3;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.utils.Converters;
import es.ava.aruco.exceptions.CPException;
import es.ava.aruco.exceptions.ExtParamException;
|
modelview_matrix[2 + 0*4] = -para[2][0];
modelview_matrix[2 + 1*4] = -para[2][1];
modelview_matrix[2 + 2*4] = -para[2][2];
modelview_matrix[2 + 3*4] = -para[2][3];
modelview_matrix[3 + 0*4] = 0.0f;
modelview_matrix[3 + 1*4] = 0.0f;
modelview_matrix[3 + 2*4] = 0.0f;
modelview_matrix[3 + 3*4] = 1.0f;
if (scale != 0.0)
{
modelview_matrix[12] *= scale;
modelview_matrix[13] *= scale;
modelview_matrix[14] *= scale;
}
// rotate 90º around the x axis
// rotating around x axis in OpenGL is equivalent to
// multiply the model matrix by the matrix:
// 1, 0, 0, 0, 0, cos(a), sin(a), 0, 0, -sin(a), cos(a), 0, 0, 0, 0, 1
// double[] auxRotMat = new double[]{
// 1, 0, 0, 0,
// 0, 0, 1, 0,
// 0, -1, 0, 0,
// 0, 0, 0, 1
// };
// Utils.matrixProduct(modelview_matrix1, auxRotMat, modelview_matrix);
}
public static void myProjectionMatrix(CameraParameters cp, Size size,
|
// Path: openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/exceptions/CPException.java
// public class CPException extends Exception{
//
// private static final long serialVersionUID = 1L;
// private String message;
//
// public CPException(String string) {
// message = string;
// }
//
// public String getMessage(){
// return message;
// }
// }
//
// Path: openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/exceptions/ExtParamException.java
// public class ExtParamException extends Exception{
//
// private static final long serialVersionUID = 1L;
// private String message;
//
// public ExtParamException(String string){
// message = string;
// }
//
// public String getMessage(){
// return message;
// }
// }
// Path: openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/Utils.java
import android.util.Log;
import java.util.List;
import java.util.Vector;
import org.opencv.calib3d.Calib3d;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.MatOfPoint3f;
import org.opencv.core.Point;
import org.opencv.core.Point3;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.utils.Converters;
import es.ava.aruco.exceptions.CPException;
import es.ava.aruco.exceptions.ExtParamException;
modelview_matrix[2 + 0*4] = -para[2][0];
modelview_matrix[2 + 1*4] = -para[2][1];
modelview_matrix[2 + 2*4] = -para[2][2];
modelview_matrix[2 + 3*4] = -para[2][3];
modelview_matrix[3 + 0*4] = 0.0f;
modelview_matrix[3 + 1*4] = 0.0f;
modelview_matrix[3 + 2*4] = 0.0f;
modelview_matrix[3 + 3*4] = 1.0f;
if (scale != 0.0)
{
modelview_matrix[12] *= scale;
modelview_matrix[13] *= scale;
modelview_matrix[14] *= scale;
}
// rotate 90º around the x axis
// rotating around x axis in OpenGL is equivalent to
// multiply the model matrix by the matrix:
// 1, 0, 0, 0, 0, cos(a), sin(a), 0, 0, -sin(a), cos(a), 0, 0, 0, 0, 1
// double[] auxRotMat = new double[]{
// 1, 0, 0, 0,
// 0, 0, 1, 0,
// 0, -1, 0, 0,
// 0, 0, 0, 1
// };
// Utils.matrixProduct(modelview_matrix1, auxRotMat, modelview_matrix);
}
public static void myProjectionMatrix(CameraParameters cp, Size size,
|
double proj_matrix[], double gnear, double gfar) throws CPException, ExtParamException{
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/min3d/core/RendererActivity.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Shared.java
// public class Shared
// {
// private static Context _context;
// private static MyRenderer _renderer;
// private static TextureManager _textureManager;
//
//
// public static Context context()
// {
// return _context;
// }
// public static void context(Context $c)
// {
// _context = $c;
// }
//
// public static MyRenderer renderer()
// {
// return _renderer;
// }
// public static void renderer(MyRenderer $r)
// {
// _renderer = $r;
// }
//
// /**
// * You must access the TextureManager instance through this accessor
// */
// public static TextureManager textureManager()
// {
// return _textureManager;
// }
// public static void textureManager(TextureManager $bm)
// {
// _textureManager = $bm;
// }
// }
|
import javax.microedition.khronos.opengles.GL;
import min3d.interfaces.ISceneController;
import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Handler;
import aruco.min3d.Shared;
|
package min3d.core;
/**
* Extend this class when creating your min3d-based Activity.
* Then, override initScene() and updateScene() for your main
* 3D logic.
*
* Override onCreateSetContentView() to change layout, if desired.
*
* To update 3d scene-related variables from within the the main UI thread,
* override onUpdateScene() and onUpdateScene() as needed.
*/
public abstract class RendererActivity extends Activity implements ISceneController
{
public Scene scene;
protected GLSurfaceView _glSurfaceView;
protected Handler _initSceneHander;
protected Handler _updateSceneHander;
private boolean _renderContinuously;
final Runnable _initSceneRunnable = new Runnable()
{
public void run() {
onInitScene();
}
};
final Runnable _updateSceneRunnable = new Runnable()
{
public void run() {
onUpdateScene();
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
_initSceneHander = new Handler();
_updateSceneHander = new Handler();
//
// These 4 lines are important.
//
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Shared.java
// public class Shared
// {
// private static Context _context;
// private static MyRenderer _renderer;
// private static TextureManager _textureManager;
//
//
// public static Context context()
// {
// return _context;
// }
// public static void context(Context $c)
// {
// _context = $c;
// }
//
// public static MyRenderer renderer()
// {
// return _renderer;
// }
// public static void renderer(MyRenderer $r)
// {
// _renderer = $r;
// }
//
// /**
// * You must access the TextureManager instance through this accessor
// */
// public static TextureManager textureManager()
// {
// return _textureManager;
// }
// public static void textureManager(TextureManager $bm)
// {
// _textureManager = $bm;
// }
// }
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/core/RendererActivity.java
import javax.microedition.khronos.opengles.GL;
import min3d.interfaces.ISceneController;
import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Handler;
import aruco.min3d.Shared;
package min3d.core;
/**
* Extend this class when creating your min3d-based Activity.
* Then, override initScene() and updateScene() for your main
* 3D logic.
*
* Override onCreateSetContentView() to change layout, if desired.
*
* To update 3d scene-related variables from within the the main UI thread,
* override onUpdateScene() and onUpdateScene() as needed.
*/
public abstract class RendererActivity extends Activity implements ISceneController
{
public Scene scene;
protected GLSurfaceView _glSurfaceView;
protected Handler _initSceneHander;
protected Handler _updateSceneHander;
private boolean _renderContinuously;
final Runnable _initSceneRunnable = new Runnable()
{
public void run() {
onInitScene();
}
};
final Runnable _updateSceneRunnable = new Runnable()
{
public void run() {
onUpdateScene();
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
_initSceneHander = new Handler();
_updateSceneHander = new Handler();
//
// These 4 lines are important.
//
|
Shared.context(this);
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/min3d/vos/Color4Managed.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Utils.java
// public class Utils
// {
// public static final float DEG = (float)(Math.PI / 180f);
//
// private static final int BYTES_PER_FLOAT = 4;
//
// /**
// * Convenience method to create a Bitmap given a Context's drawable resource ID.
// */
// public static Bitmap makeBitmapFromResourceId(Context $context, int $id)
// {
// InputStream is = $context.getResources().openRawResource($id);
//
// Bitmap bitmap;
// try {
// bitmap = BitmapFactory.decodeStream(is);
// } finally {
// try {
// is.close();
// } catch(IOException e) {
// // Ignore.
// }
// }
//
// return bitmap;
// }
//
// /**
// * Convenience method to create a Bitmap given a drawable resource ID from the application Context.
// */
// public static Bitmap makeBitmapFromResourceId(int $id)
// {
// return makeBitmapFromResourceId(Shared.context(), $id);
// }
//
// /**
// * Add two triangles to the Object3d's faces using the supplied indices
// */
// public static void addQuad(Object3d $o, int $upperLeft, int $upperRight, int $lowerRight, int $lowerLeft)
// {
// $o.faces().add((short)$upperLeft, (short)$lowerRight, (short)$upperRight);
// $o.faces().add((short)$upperLeft, (short)$lowerLeft, (short)$lowerRight);
// }
//
// public static FloatBuffer makeFloatBuffer3(float $a, float $b, float $c)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(3 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.position(0);
// return buffer;
// }
//
// public static FloatBuffer makeFloatBuffer4(float $a, float $b, float $c, float $d)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(4 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.put($d);
// buffer.position(0);
// return buffer;
// }
// }
|
import java.nio.FloatBuffer;
import min3d.interfaces.IDirtyParent;
import aruco.min3d.Utils;
|
{
_g = $g;
setDirtyFlag();
}
public short b()
{
return _b;
}
public void b(short $b)
{
_b = $b;
setDirtyFlag();
}
public short a()
{
return _a;
}
public void a(short $a)
{
_a = $a;
setDirtyFlag();
}
/**
* Convenience method
*/
public FloatBuffer toFloatBuffer()
{
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Utils.java
// public class Utils
// {
// public static final float DEG = (float)(Math.PI / 180f);
//
// private static final int BYTES_PER_FLOAT = 4;
//
// /**
// * Convenience method to create a Bitmap given a Context's drawable resource ID.
// */
// public static Bitmap makeBitmapFromResourceId(Context $context, int $id)
// {
// InputStream is = $context.getResources().openRawResource($id);
//
// Bitmap bitmap;
// try {
// bitmap = BitmapFactory.decodeStream(is);
// } finally {
// try {
// is.close();
// } catch(IOException e) {
// // Ignore.
// }
// }
//
// return bitmap;
// }
//
// /**
// * Convenience method to create a Bitmap given a drawable resource ID from the application Context.
// */
// public static Bitmap makeBitmapFromResourceId(int $id)
// {
// return makeBitmapFromResourceId(Shared.context(), $id);
// }
//
// /**
// * Add two triangles to the Object3d's faces using the supplied indices
// */
// public static void addQuad(Object3d $o, int $upperLeft, int $upperRight, int $lowerRight, int $lowerLeft)
// {
// $o.faces().add((short)$upperLeft, (short)$lowerRight, (short)$upperRight);
// $o.faces().add((short)$upperLeft, (short)$lowerLeft, (short)$lowerRight);
// }
//
// public static FloatBuffer makeFloatBuffer3(float $a, float $b, float $c)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(3 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.position(0);
// return buffer;
// }
//
// public static FloatBuffer makeFloatBuffer4(float $a, float $b, float $c, float $d)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(4 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.put($d);
// buffer.position(0);
// return buffer;
// }
// }
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/vos/Color4Managed.java
import java.nio.FloatBuffer;
import min3d.interfaces.IDirtyParent;
import aruco.min3d.Utils;
{
_g = $g;
setDirtyFlag();
}
public short b()
{
return _b;
}
public void b(short $b)
{
_b = $b;
setDirtyFlag();
}
public short a()
{
return _a;
}
public void a(short $a)
{
_a = $a;
setDirtyFlag();
}
/**
* Convenience method
*/
public FloatBuffer toFloatBuffer()
{
|
return Utils.makeFloatBuffer4(
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/CameraParameters.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/exceptions/CPException.java
// public class CPException extends Exception{
//
// private static final long serialVersionUID = 1L;
// private String message;
//
// public CPException(String string) {
// message = string;
// }
//
// public String getMessage(){
// return message;
// }
// }
|
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.StringTokenizer;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDouble;
import org.opencv.core.Size;
import es.ava.aruco.exceptions.CPException;
|
package es.ava.aruco;
/**
* Camera parameters needed to 3d rendering. They will be loaded from a file
* in xml format generated by the OpenCV's calibration algorithm.
* The parameters used are the camera matrix and the distorsion coefficient matrix.
* @author Rafael Ortega
*
*/
public class CameraParameters {
// cameraMatrix will be of the form
// | Fx 0 Cx |
// | 0 Fy Cy |
// | 0 0 1 |
private Mat cameraMatrix;
private MatOfDouble distorsionMatrix;
private Size camSize;
public CameraParameters(){
cameraMatrix = new Mat(3,3,CvType.CV_32FC1);
distorsionMatrix = new MatOfDouble();
}
/**Indicates whether this object is valid
*/
public boolean isValid(){
if(cameraMatrix != null)
return cameraMatrix.rows()!=0 && cameraMatrix.cols()!=0 &&
distorsionMatrix.total() > 0;
else
return false;
}
public Mat getCameraMatrix(){
return cameraMatrix;
}
public MatOfDouble getDistCoeff(){
return distorsionMatrix;
}
|
// Path: openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/exceptions/CPException.java
// public class CPException extends Exception{
//
// private static final long serialVersionUID = 1L;
// private String message;
//
// public CPException(String string) {
// message = string;
// }
//
// public String getMessage(){
// return message;
// }
// }
// Path: openCVTutorial1CameraPreview/src/main/java/es/ava/aruco/CameraParameters.java
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.StringTokenizer;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDouble;
import org.opencv.core.Size;
import es.ava.aruco.exceptions.CPException;
package es.ava.aruco;
/**
* Camera parameters needed to 3d rendering. They will be loaded from a file
* in xml format generated by the OpenCV's calibration algorithm.
* The parameters used are the camera matrix and the distorsion coefficient matrix.
* @author Rafael Ortega
*
*/
public class CameraParameters {
// cameraMatrix will be of the form
// | Fx 0 Cx |
// | 0 Fy Cy |
// | 0 0 1 |
private Mat cameraMatrix;
private MatOfDouble distorsionMatrix;
private Size camSize;
public CameraParameters(){
cameraMatrix = new Mat(3,3,CvType.CV_32FC1);
distorsionMatrix = new MatOfDouble();
}
/**Indicates whether this object is valid
*/
public boolean isValid(){
if(cameraMatrix != null)
return cameraMatrix.rows()!=0 && cameraMatrix.cols()!=0 &&
distorsionMatrix.total() > 0;
else
return false;
}
public Mat getCameraMatrix(){
return cameraMatrix;
}
public MatOfDouble getDistCoeff(){
return distorsionMatrix;
}
|
public void resize(Size size) throws CPException{
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/min3d/core/Number3dBufferList.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/vos/Number3d.java
// public class Number3d
// {
// public float x;
// public float y;
// public float z;
//
// private static Number3d _temp = new Number3d();
//
//
// public Number3d()
// {
// x = 0;
// y = 0;
// z = 0;
// }
//
// public Number3d(float $x, float $y, float $z)
// {
// x = $x;
// y = $y;
// z = $z;
// }
//
// //
//
// public void setAll(float $x, float $y, float $z)
// {
// x = $x;
// y = $y;
// z = $z;
// }
//
// public void setAllFrom(Number3d $n)
// {
// x = $n.x;
// y = $n.y;
// z = $n.z;
// }
//
// public void normalize()
// {
// float mod = (float) Math.sqrt( this.x*this.x + this.y*this.y + this.z*this.z );
//
// if( mod != 0 && mod != 1)
// {
// mod = 1 / mod;
// this.x *= mod;
// this.y *= mod;
// this.z *= mod;
// }
// }
//
// public void add(Number3d n)
// {
// this.x += n.x;
// this.y += n.y;
// this.z += n.z;
// }
//
// public void subtract(Number3d n)
// {
// this.x -= n.x;
// this.y -= n.y;
// this.z -= n.z;
// }
//
// public void multiply(Float f)
// {
// this.x *= f;
// this.y *= f;
// this.z *= f;
// }
//
// public float length()
// {
// return (float) Math.sqrt( this.x*this.x + this.y*this.y + this.z*this.z );
// }
//
// public Number3d clone()
// {
// return new Number3d(x,y,z);
// }
//
// public void rotateX(float angle)
// {
// float cosRY = (float) Math.cos(angle);
// float sinRY = (float) Math.sin(angle);
//
// _temp.setAll(this.x, this.y, this.z);
//
// this.y = (_temp.y*cosRY)-(_temp.z*sinRY);
// this.z = (_temp.y*sinRY)+(_temp.z*cosRY);
// }
//
// public void rotateY(float angle)
// {
// float cosRY = (float) Math.cos(angle);
// float sinRY = (float) Math.sin(angle);
//
// _temp.setAll(this.x, this.y, this.z);
//
// this.x = (_temp.x*cosRY)+(_temp.z*sinRY);
// this.z = (_temp.x*-sinRY)+(_temp.z*cosRY);
// }
//
// public void rotateZ(float angle)
// {
// float cosRY = (float) Math.cos(angle);
// float sinRY = (float) Math.sin(angle);
//
// _temp.setAll(this.x, this.y, this.z);
//
// this.x = (_temp.x*cosRY)-(_temp.y*sinRY);
// this.y = (_temp.x*sinRY)+(_temp.y*cosRY);
// }
//
//
// @Override
// public String toString()
// {
// return x + "," + y + "," + z;
// }
//
// //
//
// public static Number3d add(Number3d a, Number3d b)
// {
// return new Number3d(a.x + b.x, a.y + b.y, a.z + b.z);
// }
//
// public static Number3d subtract(Number3d a, Number3d b)
// {
// return new Number3d(a.x - b.x, a.y - b.y, a.z - b.z);
// }
//
// public static Number3d multiply(Number3d a, Number3d b)
// {
// return new Number3d(a.x * b.x, a.y * b.y, a.z * b.z);
// }
//
// public static Number3d cross(Number3d v, Number3d w)
// {
// return new Number3d((w.y * v.z) - (w.z * v.y), (w.z * v.x) - (w.x * v.z), (w.x * v.y) - (w.y * v.x));
// }
//
// public static float dot(Number3d v, Number3d w)
// {
// return ( v.x * w.x + v.y * w.y + w.z * v.z );
// }
//
// // * Math functions thanks to Papervision3D AS3 library
// // http://code.google.com/p/papervision3d/
// }
|
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import min3d.vos.Number3d;
|
_b = bb.asFloatBuffer();
}
/**
* The number of items in the list.
*/
public int size()
{
return _numElements;
}
/**
* The _maximum_ number of items that the list can hold, as defined on instantiation.
* (Not to be confused with the Buffer's capacity)
*/
public int capacity()
{
return _b.capacity() / PROPERTIES_PER_ELEMENT;
}
/**
* Clear object in preparation for garbage collection
*/
public void clear()
{
_b.clear();
}
//
|
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/vos/Number3d.java
// public class Number3d
// {
// public float x;
// public float y;
// public float z;
//
// private static Number3d _temp = new Number3d();
//
//
// public Number3d()
// {
// x = 0;
// y = 0;
// z = 0;
// }
//
// public Number3d(float $x, float $y, float $z)
// {
// x = $x;
// y = $y;
// z = $z;
// }
//
// //
//
// public void setAll(float $x, float $y, float $z)
// {
// x = $x;
// y = $y;
// z = $z;
// }
//
// public void setAllFrom(Number3d $n)
// {
// x = $n.x;
// y = $n.y;
// z = $n.z;
// }
//
// public void normalize()
// {
// float mod = (float) Math.sqrt( this.x*this.x + this.y*this.y + this.z*this.z );
//
// if( mod != 0 && mod != 1)
// {
// mod = 1 / mod;
// this.x *= mod;
// this.y *= mod;
// this.z *= mod;
// }
// }
//
// public void add(Number3d n)
// {
// this.x += n.x;
// this.y += n.y;
// this.z += n.z;
// }
//
// public void subtract(Number3d n)
// {
// this.x -= n.x;
// this.y -= n.y;
// this.z -= n.z;
// }
//
// public void multiply(Float f)
// {
// this.x *= f;
// this.y *= f;
// this.z *= f;
// }
//
// public float length()
// {
// return (float) Math.sqrt( this.x*this.x + this.y*this.y + this.z*this.z );
// }
//
// public Number3d clone()
// {
// return new Number3d(x,y,z);
// }
//
// public void rotateX(float angle)
// {
// float cosRY = (float) Math.cos(angle);
// float sinRY = (float) Math.sin(angle);
//
// _temp.setAll(this.x, this.y, this.z);
//
// this.y = (_temp.y*cosRY)-(_temp.z*sinRY);
// this.z = (_temp.y*sinRY)+(_temp.z*cosRY);
// }
//
// public void rotateY(float angle)
// {
// float cosRY = (float) Math.cos(angle);
// float sinRY = (float) Math.sin(angle);
//
// _temp.setAll(this.x, this.y, this.z);
//
// this.x = (_temp.x*cosRY)+(_temp.z*sinRY);
// this.z = (_temp.x*-sinRY)+(_temp.z*cosRY);
// }
//
// public void rotateZ(float angle)
// {
// float cosRY = (float) Math.cos(angle);
// float sinRY = (float) Math.sin(angle);
//
// _temp.setAll(this.x, this.y, this.z);
//
// this.x = (_temp.x*cosRY)-(_temp.y*sinRY);
// this.y = (_temp.x*sinRY)+(_temp.y*cosRY);
// }
//
//
// @Override
// public String toString()
// {
// return x + "," + y + "," + z;
// }
//
// //
//
// public static Number3d add(Number3d a, Number3d b)
// {
// return new Number3d(a.x + b.x, a.y + b.y, a.z + b.z);
// }
//
// public static Number3d subtract(Number3d a, Number3d b)
// {
// return new Number3d(a.x - b.x, a.y - b.y, a.z - b.z);
// }
//
// public static Number3d multiply(Number3d a, Number3d b)
// {
// return new Number3d(a.x * b.x, a.y * b.y, a.z * b.z);
// }
//
// public static Number3d cross(Number3d v, Number3d w)
// {
// return new Number3d((w.y * v.z) - (w.z * v.y), (w.z * v.x) - (w.x * v.z), (w.x * v.y) - (w.y * v.x));
// }
//
// public static float dot(Number3d v, Number3d w)
// {
// return ( v.x * w.x + v.y * w.y + w.z * v.z );
// }
//
// // * Math functions thanks to Papervision3D AS3 library
// // http://code.google.com/p/papervision3d/
// }
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/core/Number3dBufferList.java
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import min3d.vos.Number3d;
_b = bb.asFloatBuffer();
}
/**
* The number of items in the list.
*/
public int size()
{
return _numElements;
}
/**
* The _maximum_ number of items that the list can hold, as defined on instantiation.
* (Not to be confused with the Buffer's capacity)
*/
public int capacity()
{
return _b.capacity() / PROPERTIES_PER_ELEMENT;
}
/**
* Clear object in preparation for garbage collection
*/
public void clear()
{
_b.clear();
}
//
|
public Number3d getAsNumber3d(int $index)
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/min3d/core/TextureList.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/vos/TextureVo.java
// public class TextureVo
// {
// /**
// * The texureId in the TextureManager that corresponds to an uploaded Bitmap
// */
// public String textureId;
//
// /**
// * Determines if U and V ("S" and "T" in OpenGL parlance) repeat, or are 'clamped'
// * (Defaults to true, matching OpenGL's default setting)
// */
// public boolean repeatU = true;
// public boolean repeatV = true;
//
// /**
// * The U/V offsets for the texture (rem, normal range of U and V are 0 to 1)
// */
// public float offsetU = 0;
// public float offsetV = 0;
//
// /**
// * A list of TexEnvVo's that define how texture is composited in the output.
// * Normally contains just one element.
// */
// public ArrayList<TexEnvxVo> textureEnvs;
//
// //
//
// public TextureVo(String $textureId, ArrayList<TexEnvxVo> $textureEnvVo)
// {
// textureId = $textureId;
// textureEnvs = $textureEnvVo;
// }
//
// public TextureVo(String $textureId)
// {
// textureId = $textureId;
// textureEnvs = new ArrayList<TexEnvxVo>();
// textureEnvs.add( new TexEnvxVo());
// }
// }
//
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Shared.java
// public class Shared
// {
// private static Context _context;
// private static MyRenderer _renderer;
// private static TextureManager _textureManager;
//
//
// public static Context context()
// {
// return _context;
// }
// public static void context(Context $c)
// {
// _context = $c;
// }
//
// public static MyRenderer renderer()
// {
// return _renderer;
// }
// public static void renderer(MyRenderer $r)
// {
// _renderer = $r;
// }
//
// /**
// * You must access the TextureManager instance through this accessor
// */
// public static TextureManager textureManager()
// {
// return _textureManager;
// }
// public static void textureManager(TextureManager $bm)
// {
// _textureManager = $bm;
// }
// }
|
import java.util.ArrayList;
import min3d.vos.TextureVo;
import aruco.min3d.Shared;
|
package min3d.core;
/**
* Manages a list of TextureVo's used by Object3d's.
* This allows an Object3d to use multiple textures.
*
* If more textures are added than what's supported by the hardware
* running the application, the extra items are ignored by Renderer
*
* Uses a subset of ArrayList's methods.
*/
public class TextureList
{
|
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/vos/TextureVo.java
// public class TextureVo
// {
// /**
// * The texureId in the TextureManager that corresponds to an uploaded Bitmap
// */
// public String textureId;
//
// /**
// * Determines if U and V ("S" and "T" in OpenGL parlance) repeat, or are 'clamped'
// * (Defaults to true, matching OpenGL's default setting)
// */
// public boolean repeatU = true;
// public boolean repeatV = true;
//
// /**
// * The U/V offsets for the texture (rem, normal range of U and V are 0 to 1)
// */
// public float offsetU = 0;
// public float offsetV = 0;
//
// /**
// * A list of TexEnvVo's that define how texture is composited in the output.
// * Normally contains just one element.
// */
// public ArrayList<TexEnvxVo> textureEnvs;
//
// //
//
// public TextureVo(String $textureId, ArrayList<TexEnvxVo> $textureEnvVo)
// {
// textureId = $textureId;
// textureEnvs = $textureEnvVo;
// }
//
// public TextureVo(String $textureId)
// {
// textureId = $textureId;
// textureEnvs = new ArrayList<TexEnvxVo>();
// textureEnvs.add( new TexEnvxVo());
// }
// }
//
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Shared.java
// public class Shared
// {
// private static Context _context;
// private static MyRenderer _renderer;
// private static TextureManager _textureManager;
//
//
// public static Context context()
// {
// return _context;
// }
// public static void context(Context $c)
// {
// _context = $c;
// }
//
// public static MyRenderer renderer()
// {
// return _renderer;
// }
// public static void renderer(MyRenderer $r)
// {
// _renderer = $r;
// }
//
// /**
// * You must access the TextureManager instance through this accessor
// */
// public static TextureManager textureManager()
// {
// return _textureManager;
// }
// public static void textureManager(TextureManager $bm)
// {
// _textureManager = $bm;
// }
// }
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/core/TextureList.java
import java.util.ArrayList;
import min3d.vos.TextureVo;
import aruco.min3d.Shared;
package min3d.core;
/**
* Manages a list of TextureVo's used by Object3d's.
* This allows an Object3d to use multiple textures.
*
* If more textures are added than what's supported by the hardware
* running the application, the extra items are ignored by Renderer
*
* Uses a subset of ArrayList's methods.
*/
public class TextureList
{
|
private ArrayList<TextureVo> _t;
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/min3d/core/TextureList.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/vos/TextureVo.java
// public class TextureVo
// {
// /**
// * The texureId in the TextureManager that corresponds to an uploaded Bitmap
// */
// public String textureId;
//
// /**
// * Determines if U and V ("S" and "T" in OpenGL parlance) repeat, or are 'clamped'
// * (Defaults to true, matching OpenGL's default setting)
// */
// public boolean repeatU = true;
// public boolean repeatV = true;
//
// /**
// * The U/V offsets for the texture (rem, normal range of U and V are 0 to 1)
// */
// public float offsetU = 0;
// public float offsetV = 0;
//
// /**
// * A list of TexEnvVo's that define how texture is composited in the output.
// * Normally contains just one element.
// */
// public ArrayList<TexEnvxVo> textureEnvs;
//
// //
//
// public TextureVo(String $textureId, ArrayList<TexEnvxVo> $textureEnvVo)
// {
// textureId = $textureId;
// textureEnvs = $textureEnvVo;
// }
//
// public TextureVo(String $textureId)
// {
// textureId = $textureId;
// textureEnvs = new ArrayList<TexEnvxVo>();
// textureEnvs.add( new TexEnvxVo());
// }
// }
//
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Shared.java
// public class Shared
// {
// private static Context _context;
// private static MyRenderer _renderer;
// private static TextureManager _textureManager;
//
//
// public static Context context()
// {
// return _context;
// }
// public static void context(Context $c)
// {
// _context = $c;
// }
//
// public static MyRenderer renderer()
// {
// return _renderer;
// }
// public static void renderer(MyRenderer $r)
// {
// _renderer = $r;
// }
//
// /**
// * You must access the TextureManager instance through this accessor
// */
// public static TextureManager textureManager()
// {
// return _textureManager;
// }
// public static void textureManager(TextureManager $bm)
// {
// _textureManager = $bm;
// }
// }
|
import java.util.ArrayList;
import min3d.vos.TextureVo;
import aruco.min3d.Shared;
|
package min3d.core;
/**
* Manages a list of TextureVo's used by Object3d's.
* This allows an Object3d to use multiple textures.
*
* If more textures are added than what's supported by the hardware
* running the application, the extra items are ignored by Renderer
*
* Uses a subset of ArrayList's methods.
*/
public class TextureList
{
private ArrayList<TextureVo> _t;
public TextureList()
{
_t = new ArrayList<TextureVo>();
}
/**
* Adds item to the list
*/
public boolean add(TextureVo $texture)
{
|
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/vos/TextureVo.java
// public class TextureVo
// {
// /**
// * The texureId in the TextureManager that corresponds to an uploaded Bitmap
// */
// public String textureId;
//
// /**
// * Determines if U and V ("S" and "T" in OpenGL parlance) repeat, or are 'clamped'
// * (Defaults to true, matching OpenGL's default setting)
// */
// public boolean repeatU = true;
// public boolean repeatV = true;
//
// /**
// * The U/V offsets for the texture (rem, normal range of U and V are 0 to 1)
// */
// public float offsetU = 0;
// public float offsetV = 0;
//
// /**
// * A list of TexEnvVo's that define how texture is composited in the output.
// * Normally contains just one element.
// */
// public ArrayList<TexEnvxVo> textureEnvs;
//
// //
//
// public TextureVo(String $textureId, ArrayList<TexEnvxVo> $textureEnvVo)
// {
// textureId = $textureId;
// textureEnvs = $textureEnvVo;
// }
//
// public TextureVo(String $textureId)
// {
// textureId = $textureId;
// textureEnvs = new ArrayList<TexEnvxVo>();
// textureEnvs.add( new TexEnvxVo());
// }
// }
//
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Shared.java
// public class Shared
// {
// private static Context _context;
// private static MyRenderer _renderer;
// private static TextureManager _textureManager;
//
//
// public static Context context()
// {
// return _context;
// }
// public static void context(Context $c)
// {
// _context = $c;
// }
//
// public static MyRenderer renderer()
// {
// return _renderer;
// }
// public static void renderer(MyRenderer $r)
// {
// _renderer = $r;
// }
//
// /**
// * You must access the TextureManager instance through this accessor
// */
// public static TextureManager textureManager()
// {
// return _textureManager;
// }
// public static void textureManager(TextureManager $bm)
// {
// _textureManager = $bm;
// }
// }
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/core/TextureList.java
import java.util.ArrayList;
import min3d.vos.TextureVo;
import aruco.min3d.Shared;
package min3d.core;
/**
* Manages a list of TextureVo's used by Object3d's.
* This allows an Object3d to use multiple textures.
*
* If more textures are added than what's supported by the hardware
* running the application, the extra items are ignored by Renderer
*
* Uses a subset of ArrayList's methods.
*/
public class TextureList
{
private ArrayList<TextureVo> _t;
public TextureList()
{
_t = new ArrayList<TextureVo>();
}
/**
* Adds item to the list
*/
public boolean add(TextureVo $texture)
{
|
if (! Shared.textureManager().contains($texture.textureId)) return false;
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/min3d/core/RenderCaps.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Min3d.java
// public class Min3d
// {
// public static final String TAG = "Min3D";
//
// /*
// * Project homepage: http://code.google.com/p/min3d
// * License: MIT
// *
// * Author: Lee Felarca
// * Website: http://www.zeropointnine.com/blog
// *
// * Author: Dennis Ippel
// * Author blog: http://www.rozengain.com/blog/
// */
// }
|
import java.nio.IntBuffer;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import android.util.Log;
import aruco.min3d.Min3d;
|
// Aliased point size range
i = IntBuffer.allocate(2);
$gl.glGetIntegerv(GL10.GL_ALIASED_POINT_SIZE_RANGE, i);
_aliasedPointSizeMin = i.get(0);
_aliasedPointSizeMax = i.get(1);
// Smooth point size range
i = IntBuffer.allocate(2);
$gl.glGetIntegerv(GL10.GL_SMOOTH_POINT_SIZE_RANGE, i);
_smoothPointSizeMin = i.get(0);
_smoothPointSizeMax = i.get(1);
// Aliased line width range
i = IntBuffer.allocate(2);
$gl.glGetIntegerv(GL10.GL_ALIASED_LINE_WIDTH_RANGE, i);
_aliasedLineSizeMin = i.get(0);
_aliasedLineSizeMax = i.get(1);
// Smooth line width range
i = IntBuffer.allocate(2);
$gl.glGetIntegerv(GL10.GL_SMOOTH_LINE_WIDTH_RANGE, i);
_smoothLineSizeMin = i.get(0);
_smoothLineSizeMax = i.get(1);
// Max lights
i = IntBuffer.allocate(1);
$gl.glGetIntegerv(GL10.GL_MAX_LIGHTS, i);
_maxLights = i.get(0);
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Min3d.java
// public class Min3d
// {
// public static final String TAG = "Min3D";
//
// /*
// * Project homepage: http://code.google.com/p/min3d
// * License: MIT
// *
// * Author: Lee Felarca
// * Website: http://www.zeropointnine.com/blog
// *
// * Author: Dennis Ippel
// * Author blog: http://www.rozengain.com/blog/
// */
// }
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/core/RenderCaps.java
import java.nio.IntBuffer;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import android.util.Log;
import aruco.min3d.Min3d;
// Aliased point size range
i = IntBuffer.allocate(2);
$gl.glGetIntegerv(GL10.GL_ALIASED_POINT_SIZE_RANGE, i);
_aliasedPointSizeMin = i.get(0);
_aliasedPointSizeMax = i.get(1);
// Smooth point size range
i = IntBuffer.allocate(2);
$gl.glGetIntegerv(GL10.GL_SMOOTH_POINT_SIZE_RANGE, i);
_smoothPointSizeMin = i.get(0);
_smoothPointSizeMax = i.get(1);
// Aliased line width range
i = IntBuffer.allocate(2);
$gl.glGetIntegerv(GL10.GL_ALIASED_LINE_WIDTH_RANGE, i);
_aliasedLineSizeMin = i.get(0);
_aliasedLineSizeMax = i.get(1);
// Smooth line width range
i = IntBuffer.allocate(2);
$gl.glGetIntegerv(GL10.GL_SMOOTH_LINE_WIDTH_RANGE, i);
_smoothLineSizeMin = i.get(0);
_smoothLineSizeMax = i.get(1);
// Max lights
i = IntBuffer.allocate(1);
$gl.glGetIntegerv(GL10.GL_MAX_LIGHTS, i);
_maxLights = i.get(0);
|
Log.v(Min3d.TAG, "RenderCaps - openGLVersion: " + _openGlVersion);
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/min3d/vos/Light.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Utils.java
// public class Utils
// {
// public static final float DEG = (float)(Math.PI / 180f);
//
// private static final int BYTES_PER_FLOAT = 4;
//
// /**
// * Convenience method to create a Bitmap given a Context's drawable resource ID.
// */
// public static Bitmap makeBitmapFromResourceId(Context $context, int $id)
// {
// InputStream is = $context.getResources().openRawResource($id);
//
// Bitmap bitmap;
// try {
// bitmap = BitmapFactory.decodeStream(is);
// } finally {
// try {
// is.close();
// } catch(IOException e) {
// // Ignore.
// }
// }
//
// return bitmap;
// }
//
// /**
// * Convenience method to create a Bitmap given a drawable resource ID from the application Context.
// */
// public static Bitmap makeBitmapFromResourceId(int $id)
// {
// return makeBitmapFromResourceId(Shared.context(), $id);
// }
//
// /**
// * Add two triangles to the Object3d's faces using the supplied indices
// */
// public static void addQuad(Object3d $o, int $upperLeft, int $upperRight, int $lowerRight, int $lowerLeft)
// {
// $o.faces().add((short)$upperLeft, (short)$lowerRight, (short)$upperRight);
// $o.faces().add((short)$upperLeft, (short)$lowerLeft, (short)$lowerRight);
// }
//
// public static FloatBuffer makeFloatBuffer3(float $a, float $b, float $c)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(3 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.position(0);
// return buffer;
// }
//
// public static FloatBuffer makeFloatBuffer4(float $a, float $b, float $c, float $d)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(4 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.put($d);
// buffer.position(0);
// return buffer;
// }
// }
|
import java.nio.FloatBuffer;
import min3d.interfaces.IDirtyParent;
import aruco.min3d.Utils;
|
package min3d.vos;
/**
* Light must be added to Scene to take effect.
*
* Eg, "scene.lights().add(myLight);"
*/
public class Light extends AbstractDirtyManaged implements IDirtyParent
{
/**
* Position is relative to eye space, not world space.
*/
public Number3dManaged position;
/**
* Direction is a vector and should be normalized.
*/
public Number3dManaged direction;
public Color4Managed ambient;
public Color4Managed diffuse;
public Color4Managed specular;
public Color4Managed emissive;
private LightType _type;
public Light()
{
super(null);
ambient = new Color4Managed(128,128,128, 255, this);
diffuse = new Color4Managed(255,255,255, 255, this);
specular = new Color4Managed(0,0,0,255, this);
emissive = new Color4Managed(0,0,0,255, this);
position = new Number3dManaged(0f, 0f, 1f, this);
direction = new Number3dManaged(0f, 0f, -1f, this);
_spotCutoffAngle = new FloatManaged(180, this);
_spotExponent = new FloatManaged(0f, this);
_attenuation = new Number3dManaged(1f,0f,0f, this);
_type = LightType.DIRECTIONAL;
_isVisible = new BooleanManaged(true, this);
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Utils.java
// public class Utils
// {
// public static final float DEG = (float)(Math.PI / 180f);
//
// private static final int BYTES_PER_FLOAT = 4;
//
// /**
// * Convenience method to create a Bitmap given a Context's drawable resource ID.
// */
// public static Bitmap makeBitmapFromResourceId(Context $context, int $id)
// {
// InputStream is = $context.getResources().openRawResource($id);
//
// Bitmap bitmap;
// try {
// bitmap = BitmapFactory.decodeStream(is);
// } finally {
// try {
// is.close();
// } catch(IOException e) {
// // Ignore.
// }
// }
//
// return bitmap;
// }
//
// /**
// * Convenience method to create a Bitmap given a drawable resource ID from the application Context.
// */
// public static Bitmap makeBitmapFromResourceId(int $id)
// {
// return makeBitmapFromResourceId(Shared.context(), $id);
// }
//
// /**
// * Add two triangles to the Object3d's faces using the supplied indices
// */
// public static void addQuad(Object3d $o, int $upperLeft, int $upperRight, int $lowerRight, int $lowerLeft)
// {
// $o.faces().add((short)$upperLeft, (short)$lowerRight, (short)$upperRight);
// $o.faces().add((short)$upperLeft, (short)$lowerLeft, (short)$lowerRight);
// }
//
// public static FloatBuffer makeFloatBuffer3(float $a, float $b, float $c)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(3 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.position(0);
// return buffer;
// }
//
// public static FloatBuffer makeFloatBuffer4(float $a, float $b, float $c, float $d)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(4 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.put($d);
// buffer.position(0);
// return buffer;
// }
// }
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/vos/Light.java
import java.nio.FloatBuffer;
import min3d.interfaces.IDirtyParent;
import aruco.min3d.Utils;
package min3d.vos;
/**
* Light must be added to Scene to take effect.
*
* Eg, "scene.lights().add(myLight);"
*/
public class Light extends AbstractDirtyManaged implements IDirtyParent
{
/**
* Position is relative to eye space, not world space.
*/
public Number3dManaged position;
/**
* Direction is a vector and should be normalized.
*/
public Number3dManaged direction;
public Color4Managed ambient;
public Color4Managed diffuse;
public Color4Managed specular;
public Color4Managed emissive;
private LightType _type;
public Light()
{
super(null);
ambient = new Color4Managed(128,128,128, 255, this);
diffuse = new Color4Managed(255,255,255, 255, this);
specular = new Color4Managed(0,0,0,255, this);
emissive = new Color4Managed(0,0,0,255, this);
position = new Number3dManaged(0f, 0f, 1f, this);
direction = new Number3dManaged(0f, 0f, -1f, this);
_spotCutoffAngle = new FloatManaged(180, this);
_spotExponent = new FloatManaged(0f, this);
_attenuation = new Number3dManaged(1f,0f,0f, this);
_type = LightType.DIRECTIONAL;
_isVisible = new BooleanManaged(true, this);
|
_positionAndTypeBuffer = Utils.makeFloatBuffer4(0,0,0,0);
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/min3d/core/TextureManager.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Min3d.java
// public class Min3d
// {
// public static final String TAG = "Min3D";
//
// /*
// * Project homepage: http://code.google.com/p/min3d
// * License: MIT
// *
// * Author: Lee Felarca
// * Website: http://www.zeropointnine.com/blog
// *
// * Author: Dennis Ippel
// * Author blog: http://www.rozengain.com/blog/
// */
// }
//
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Shared.java
// public class Shared
// {
// private static Context _context;
// private static MyRenderer _renderer;
// private static TextureManager _textureManager;
//
//
// public static Context context()
// {
// return _context;
// }
// public static void context(Context $c)
// {
// _context = $c;
// }
//
// public static MyRenderer renderer()
// {
// return _renderer;
// }
// public static void renderer(MyRenderer $r)
// {
// _renderer = $r;
// }
//
// /**
// * You must access the TextureManager instance through this accessor
// */
// public static TextureManager textureManager()
// {
// return _textureManager;
// }
// public static void textureManager(TextureManager $bm)
// {
// _textureManager = $bm;
// }
// }
|
import java.util.HashMap;
import java.util.Set;
import android.graphics.Bitmap;
import android.util.Log;
import aruco.min3d.Min3d;
import aruco.min3d.Shared;
|
package min3d.core;
/**
* TextureManager is responsible for managing textures for the whole environment.
* It maintains a list of id's that are mapped to the GL texture names (id's).
*
* You add a Bitmap to the TextureManager, which adds a textureId to its list.
* Then, you assign one or more TextureVo's to your Object3d's using id's that
* exist in the TextureManager.
*
* Note that the _idToTextureName and _idToHasMipMap HashMaps used below
* don't test for exceptions.
*/
public class TextureManager
{
private HashMap<String, Integer> _idToTextureName;
private HashMap<String, Boolean> _idToHasMipMap;
private static int _counter = 1000001;
private static int _atlasId = 0;
public TextureManager()
{
reset();
}
public void reset()
{
// Delete any extant textures
if (_idToTextureName != null)
{
Set<String> s = _idToTextureName.keySet();
Object[] a = s.toArray();
for (int i = 0; i < a.length; i++) {
int glId = getGlTextureId((String)a[i]);
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Min3d.java
// public class Min3d
// {
// public static final String TAG = "Min3D";
//
// /*
// * Project homepage: http://code.google.com/p/min3d
// * License: MIT
// *
// * Author: Lee Felarca
// * Website: http://www.zeropointnine.com/blog
// *
// * Author: Dennis Ippel
// * Author blog: http://www.rozengain.com/blog/
// */
// }
//
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Shared.java
// public class Shared
// {
// private static Context _context;
// private static MyRenderer _renderer;
// private static TextureManager _textureManager;
//
//
// public static Context context()
// {
// return _context;
// }
// public static void context(Context $c)
// {
// _context = $c;
// }
//
// public static MyRenderer renderer()
// {
// return _renderer;
// }
// public static void renderer(MyRenderer $r)
// {
// _renderer = $r;
// }
//
// /**
// * You must access the TextureManager instance through this accessor
// */
// public static TextureManager textureManager()
// {
// return _textureManager;
// }
// public static void textureManager(TextureManager $bm)
// {
// _textureManager = $bm;
// }
// }
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/core/TextureManager.java
import java.util.HashMap;
import java.util.Set;
import android.graphics.Bitmap;
import android.util.Log;
import aruco.min3d.Min3d;
import aruco.min3d.Shared;
package min3d.core;
/**
* TextureManager is responsible for managing textures for the whole environment.
* It maintains a list of id's that are mapped to the GL texture names (id's).
*
* You add a Bitmap to the TextureManager, which adds a textureId to its list.
* Then, you assign one or more TextureVo's to your Object3d's using id's that
* exist in the TextureManager.
*
* Note that the _idToTextureName and _idToHasMipMap HashMaps used below
* don't test for exceptions.
*/
public class TextureManager
{
private HashMap<String, Integer> _idToTextureName;
private HashMap<String, Boolean> _idToHasMipMap;
private static int _counter = 1000001;
private static int _atlasId = 0;
public TextureManager()
{
reset();
}
public void reset()
{
// Delete any extant textures
if (_idToTextureName != null)
{
Set<String> s = _idToTextureName.keySet();
Object[] a = s.toArray();
for (int i = 0; i < a.length; i++) {
int glId = getGlTextureId((String)a[i]);
|
Shared.renderer().deleteTexture(glId);
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/min3d/core/TextureManager.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Min3d.java
// public class Min3d
// {
// public static final String TAG = "Min3D";
//
// /*
// * Project homepage: http://code.google.com/p/min3d
// * License: MIT
// *
// * Author: Lee Felarca
// * Website: http://www.zeropointnine.com/blog
// *
// * Author: Dennis Ippel
// * Author blog: http://www.rozengain.com/blog/
// */
// }
//
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Shared.java
// public class Shared
// {
// private static Context _context;
// private static MyRenderer _renderer;
// private static TextureManager _textureManager;
//
//
// public static Context context()
// {
// return _context;
// }
// public static void context(Context $c)
// {
// _context = $c;
// }
//
// public static MyRenderer renderer()
// {
// return _renderer;
// }
// public static void renderer(MyRenderer $r)
// {
// _renderer = $r;
// }
//
// /**
// * You must access the TextureManager instance through this accessor
// */
// public static TextureManager textureManager()
// {
// return _textureManager;
// }
// public static void textureManager(TextureManager $bm)
// {
// _textureManager = $bm;
// }
// }
|
import java.util.HashMap;
import java.util.Set;
import android.graphics.Bitmap;
import android.util.Log;
import aruco.min3d.Min3d;
import aruco.min3d.Shared;
|
return _idToTextureName.get($textureId);
}
/**
* Used by Renderer
*/
boolean hasMipMap(String $textureId) /*package-private*/
{
return _idToHasMipMap.get($textureId);
}
public boolean contains(String $textureId)
{
return _idToTextureName.containsKey($textureId);
}
private String arrayToString(String[] $a)
{
String s = "";
for (int i = 0; i < $a.length; i++)
{
s += $a[i].toString() + " | ";
}
return s;
}
private void logContents()
{
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Min3d.java
// public class Min3d
// {
// public static final String TAG = "Min3D";
//
// /*
// * Project homepage: http://code.google.com/p/min3d
// * License: MIT
// *
// * Author: Lee Felarca
// * Website: http://www.zeropointnine.com/blog
// *
// * Author: Dennis Ippel
// * Author blog: http://www.rozengain.com/blog/
// */
// }
//
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Shared.java
// public class Shared
// {
// private static Context _context;
// private static MyRenderer _renderer;
// private static TextureManager _textureManager;
//
//
// public static Context context()
// {
// return _context;
// }
// public static void context(Context $c)
// {
// _context = $c;
// }
//
// public static MyRenderer renderer()
// {
// return _renderer;
// }
// public static void renderer(MyRenderer $r)
// {
// _renderer = $r;
// }
//
// /**
// * You must access the TextureManager instance through this accessor
// */
// public static TextureManager textureManager()
// {
// return _textureManager;
// }
// public static void textureManager(TextureManager $bm)
// {
// _textureManager = $bm;
// }
// }
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/core/TextureManager.java
import java.util.HashMap;
import java.util.Set;
import android.graphics.Bitmap;
import android.util.Log;
import aruco.min3d.Min3d;
import aruco.min3d.Shared;
return _idToTextureName.get($textureId);
}
/**
* Used by Renderer
*/
boolean hasMipMap(String $textureId) /*package-private*/
{
return _idToHasMipMap.get($textureId);
}
public boolean contains(String $textureId)
{
return _idToTextureName.containsKey($textureId);
}
private String arrayToString(String[] $a)
{
String s = "";
for (int i = 0; i < $a.length; i++)
{
s += $a[i].toString() + " | ";
}
return s;
}
private void logContents()
{
|
Log.v(Min3d.TAG, "TextureManager contents updated - " + arrayToString( getTextureIds() ) );
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/min3d/vos/Color4.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Utils.java
// public class Utils
// {
// public static final float DEG = (float)(Math.PI / 180f);
//
// private static final int BYTES_PER_FLOAT = 4;
//
// /**
// * Convenience method to create a Bitmap given a Context's drawable resource ID.
// */
// public static Bitmap makeBitmapFromResourceId(Context $context, int $id)
// {
// InputStream is = $context.getResources().openRawResource($id);
//
// Bitmap bitmap;
// try {
// bitmap = BitmapFactory.decodeStream(is);
// } finally {
// try {
// is.close();
// } catch(IOException e) {
// // Ignore.
// }
// }
//
// return bitmap;
// }
//
// /**
// * Convenience method to create a Bitmap given a drawable resource ID from the application Context.
// */
// public static Bitmap makeBitmapFromResourceId(int $id)
// {
// return makeBitmapFromResourceId(Shared.context(), $id);
// }
//
// /**
// * Add two triangles to the Object3d's faces using the supplied indices
// */
// public static void addQuad(Object3d $o, int $upperLeft, int $upperRight, int $lowerRight, int $lowerLeft)
// {
// $o.faces().add((short)$upperLeft, (short)$lowerRight, (short)$upperRight);
// $o.faces().add((short)$upperLeft, (short)$lowerLeft, (short)$lowerRight);
// }
//
// public static FloatBuffer makeFloatBuffer3(float $a, float $b, float $c)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(3 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.position(0);
// return buffer;
// }
//
// public static FloatBuffer makeFloatBuffer4(float $a, float $b, float $c, float $d)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(4 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.put($d);
// buffer.position(0);
// return buffer;
// }
// }
|
import java.nio.FloatBuffer;
import aruco.min3d.Utils;
|
/**
* Convenience method to set all properties in one line.
*/
public void setAll(short $r, short $g, short $b, short $a)
{
r = $r;
g = $g;
b = $b;
a = $a;
}
/**
* Convenience method to set all properties off one 32-bit argb value
*/
public void setAll(long $argb32)
{
a = (short) (($argb32 >> 24) & 0x000000FF);
r = (short) (($argb32 >> 16) & 0x000000FF);
g = (short) (($argb32 >> 8) & 0x000000FF);
b = (short) (($argb32) & 0x000000FF);
}
@Override
public String toString()
{
return "r:" + r + ", g:" + g + ", b:" + b + ", a:" + a;
}
public FloatBuffer toFloatBuffer()
{
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Utils.java
// public class Utils
// {
// public static final float DEG = (float)(Math.PI / 180f);
//
// private static final int BYTES_PER_FLOAT = 4;
//
// /**
// * Convenience method to create a Bitmap given a Context's drawable resource ID.
// */
// public static Bitmap makeBitmapFromResourceId(Context $context, int $id)
// {
// InputStream is = $context.getResources().openRawResource($id);
//
// Bitmap bitmap;
// try {
// bitmap = BitmapFactory.decodeStream(is);
// } finally {
// try {
// is.close();
// } catch(IOException e) {
// // Ignore.
// }
// }
//
// return bitmap;
// }
//
// /**
// * Convenience method to create a Bitmap given a drawable resource ID from the application Context.
// */
// public static Bitmap makeBitmapFromResourceId(int $id)
// {
// return makeBitmapFromResourceId(Shared.context(), $id);
// }
//
// /**
// * Add two triangles to the Object3d's faces using the supplied indices
// */
// public static void addQuad(Object3d $o, int $upperLeft, int $upperRight, int $lowerRight, int $lowerLeft)
// {
// $o.faces().add((short)$upperLeft, (short)$lowerRight, (short)$upperRight);
// $o.faces().add((short)$upperLeft, (short)$lowerLeft, (short)$lowerRight);
// }
//
// public static FloatBuffer makeFloatBuffer3(float $a, float $b, float $c)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(3 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.position(0);
// return buffer;
// }
//
// public static FloatBuffer makeFloatBuffer4(float $a, float $b, float $c, float $d)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(4 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.put($d);
// buffer.position(0);
// return buffer;
// }
// }
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/vos/Color4.java
import java.nio.FloatBuffer;
import aruco.min3d.Utils;
/**
* Convenience method to set all properties in one line.
*/
public void setAll(short $r, short $g, short $b, short $a)
{
r = $r;
g = $g;
b = $b;
a = $a;
}
/**
* Convenience method to set all properties off one 32-bit argb value
*/
public void setAll(long $argb32)
{
a = (short) (($argb32 >> 24) & 0x000000FF);
r = (short) (($argb32 >> 16) & 0x000000FF);
g = (short) (($argb32 >> 8) & 0x000000FF);
b = (short) (($argb32) & 0x000000FF);
}
@Override
public String toString()
{
return "r:" + r + ", g:" + g + ", b:" + b + ", a:" + a;
}
public FloatBuffer toFloatBuffer()
{
|
return Utils.makeFloatBuffer4(r,g,b,a);
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/min3d/core/FacesBufferedList.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/vos/Face.java
// public class Face
// {
// public short a;
// public short b;
// public short c;
//
// public Face(short $a, short $b, short $c)
// {
// a = $a;
// b = $b;
// c = $c;
// }
//
// /**
// * Convenience method to cast int arguments to short's
// */
// public Face(int $a, int $b, int $c)
// {
// a = (short) $a;
// b = (short) $b;
// c = (short) $c;
// }
// }
|
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import min3d.vos.Face;
|
b.order(ByteOrder.nativeOrder());
_b = b.asShortBuffer();
}
/**
* The number of items in the list.
*/
public int size()
{
return _numElements;
}
/**
* The _maximum_ number of items that the list can hold, as defined on instantiation.
* (Not to be confused with the Buffer's capacity)
*/
public int capacity()
{
return _b.capacity() / PROPERTIES_PER_ELEMENT;
}
/**
* Clear object in preparation for garbage collection
*/
public void clear()
{
_b.clear();
}
|
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/vos/Face.java
// public class Face
// {
// public short a;
// public short b;
// public short c;
//
// public Face(short $a, short $b, short $c)
// {
// a = $a;
// b = $b;
// c = $c;
// }
//
// /**
// * Convenience method to cast int arguments to short's
// */
// public Face(int $a, int $b, int $c)
// {
// a = (short) $a;
// b = (short) $b;
// c = (short) $c;
// }
// }
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/core/FacesBufferedList.java
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import min3d.vos.Face;
b.order(ByteOrder.nativeOrder());
_b = b.asShortBuffer();
}
/**
* The number of items in the list.
*/
public int size()
{
return _numElements;
}
/**
* The _maximum_ number of items that the list can hold, as defined on instantiation.
* (Not to be confused with the Buffer's capacity)
*/
public int capacity()
{
return _b.capacity() / PROPERTIES_PER_ELEMENT;
}
/**
* Clear object in preparation for garbage collection
*/
public void clear()
{
_b.clear();
}
|
public Face get(int $index)
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/min3d/core/Color4BufferList.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/vos/Color4.java
// public class Color4
// {
// public short r;
// public short g;
// public short b;
// public short a;
//
//
// public Color4()
// {
// r = (short)255;
// g = (short)255;
// b = (short)255;
// a = (short)255;
// }
//
// public Color4(short $r, short $g, short $b, short $a)
// {
// r = $r;
// g = $g;
// b = $b;
// a = $a;
// }
//
// /**
// * Convenience method which casts the int arguments to short for you.
// */
// public Color4(int $r, int $g, int $b, int $a)
// {
// r = (short)$r;
// g = (short)$g;
// b = (short)$b;
// a = (short)$a;
// }
//
// /**
// * Convenience method which casts the float arguments to short for you.
// */
// public Color4(float $r, float $g, float $b, float $a)
// {
// r = (short)$r;
// g = (short)$g;
// b = (short)$b;
// a = (short)$a;
// }
//
// /**
// * Convenience method to set all properties in one line.
// */
// public void setAll(short $r, short $g, short $b, short $a)
// {
// r = $r;
// g = $g;
// b = $b;
// a = $a;
// }
//
// /**
// * Convenience method to set all properties off one 32-bit argb value
// */
// public void setAll(long $argb32)
// {
// a = (short) (($argb32 >> 24) & 0x000000FF);
// r = (short) (($argb32 >> 16) & 0x000000FF);
// g = (short) (($argb32 >> 8) & 0x000000FF);
// b = (short) (($argb32) & 0x000000FF);
// }
//
// @Override
// public String toString()
// {
// return "r:" + r + ", g:" + g + ", b:" + b + ", a:" + a;
// }
//
// public FloatBuffer toFloatBuffer()
// {
// return Utils.makeFloatBuffer4(r,g,b,a);
// }
//
// public void toFloatBuffer(FloatBuffer $floatBuffer)
// {
// $floatBuffer.position(0);
// $floatBuffer.put((float)r / 255f);
// $floatBuffer.put((float)g / 255f);
// $floatBuffer.put((float)b / 255f);
// $floatBuffer.put((float)a / 255f);
// }
// }
|
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import min3d.vos.Color4;
|
int numBytes = $maxElements * PROPERTIES_PER_ELEMENT * BYTES_PER_PROPERTY;
_b = ByteBuffer.allocateDirect(numBytes);
_b.order(ByteOrder.nativeOrder());
}
/**
* The number of items in the list.
*/
public int size()
{
return _numElements;
}
/**
* The _maximum_ number of items that the list can hold, as defined on instantiation.
* (Not to be confused with the Buffer's capacity)
*/
public int capacity()
{
return _b.capacity() / PROPERTIES_PER_ELEMENT;
}
/**
* Clear object in preparation for garbage collection
*/
public void clear()
{
_b.clear();
}
|
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/vos/Color4.java
// public class Color4
// {
// public short r;
// public short g;
// public short b;
// public short a;
//
//
// public Color4()
// {
// r = (short)255;
// g = (short)255;
// b = (short)255;
// a = (short)255;
// }
//
// public Color4(short $r, short $g, short $b, short $a)
// {
// r = $r;
// g = $g;
// b = $b;
// a = $a;
// }
//
// /**
// * Convenience method which casts the int arguments to short for you.
// */
// public Color4(int $r, int $g, int $b, int $a)
// {
// r = (short)$r;
// g = (short)$g;
// b = (short)$b;
// a = (short)$a;
// }
//
// /**
// * Convenience method which casts the float arguments to short for you.
// */
// public Color4(float $r, float $g, float $b, float $a)
// {
// r = (short)$r;
// g = (short)$g;
// b = (short)$b;
// a = (short)$a;
// }
//
// /**
// * Convenience method to set all properties in one line.
// */
// public void setAll(short $r, short $g, short $b, short $a)
// {
// r = $r;
// g = $g;
// b = $b;
// a = $a;
// }
//
// /**
// * Convenience method to set all properties off one 32-bit argb value
// */
// public void setAll(long $argb32)
// {
// a = (short) (($argb32 >> 24) & 0x000000FF);
// r = (short) (($argb32 >> 16) & 0x000000FF);
// g = (short) (($argb32 >> 8) & 0x000000FF);
// b = (short) (($argb32) & 0x000000FF);
// }
//
// @Override
// public String toString()
// {
// return "r:" + r + ", g:" + g + ", b:" + b + ", a:" + a;
// }
//
// public FloatBuffer toFloatBuffer()
// {
// return Utils.makeFloatBuffer4(r,g,b,a);
// }
//
// public void toFloatBuffer(FloatBuffer $floatBuffer)
// {
// $floatBuffer.position(0);
// $floatBuffer.put((float)r / 255f);
// $floatBuffer.put((float)g / 255f);
// $floatBuffer.put((float)b / 255f);
// $floatBuffer.put((float)a / 255f);
// }
// }
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/core/Color4BufferList.java
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import min3d.vos.Color4;
int numBytes = $maxElements * PROPERTIES_PER_ELEMENT * BYTES_PER_PROPERTY;
_b = ByteBuffer.allocateDirect(numBytes);
_b.order(ByteOrder.nativeOrder());
}
/**
* The number of items in the list.
*/
public int size()
{
return _numElements;
}
/**
* The _maximum_ number of items that the list can hold, as defined on instantiation.
* (Not to be confused with the Buffer's capacity)
*/
public int capacity()
{
return _b.capacity() / PROPERTIES_PER_ELEMENT;
}
/**
* Clear object in preparation for garbage collection
*/
public void clear()
{
_b.clear();
}
|
public Color4 getAsColor4(int $index)
|
jsmith613/Aruco-Marker-Tracking-Android
|
openCVTutorial1CameraPreview/src/main/java/min3d/vos/Number3dManaged.java
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Utils.java
// public class Utils
// {
// public static final float DEG = (float)(Math.PI / 180f);
//
// private static final int BYTES_PER_FLOAT = 4;
//
// /**
// * Convenience method to create a Bitmap given a Context's drawable resource ID.
// */
// public static Bitmap makeBitmapFromResourceId(Context $context, int $id)
// {
// InputStream is = $context.getResources().openRawResource($id);
//
// Bitmap bitmap;
// try {
// bitmap = BitmapFactory.decodeStream(is);
// } finally {
// try {
// is.close();
// } catch(IOException e) {
// // Ignore.
// }
// }
//
// return bitmap;
// }
//
// /**
// * Convenience method to create a Bitmap given a drawable resource ID from the application Context.
// */
// public static Bitmap makeBitmapFromResourceId(int $id)
// {
// return makeBitmapFromResourceId(Shared.context(), $id);
// }
//
// /**
// * Add two triangles to the Object3d's faces using the supplied indices
// */
// public static void addQuad(Object3d $o, int $upperLeft, int $upperRight, int $lowerRight, int $lowerLeft)
// {
// $o.faces().add((short)$upperLeft, (short)$lowerRight, (short)$upperRight);
// $o.faces().add((short)$upperLeft, (short)$lowerLeft, (short)$lowerRight);
// }
//
// public static FloatBuffer makeFloatBuffer3(float $a, float $b, float $c)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(3 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.position(0);
// return buffer;
// }
//
// public static FloatBuffer makeFloatBuffer4(float $a, float $b, float $c, float $d)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(4 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.put($d);
// buffer.position(0);
// return buffer;
// }
// }
|
import java.nio.FloatBuffer;
import min3d.interfaces.IDirtyParent;
import aruco.min3d.Utils;
|
_x = $n.x;
_y = $n.y;
_z = $n.z;
setDirtyFlag();
}
public void setAllFrom(Number3dManaged $n)
{
_x = $n.getX();
_y = $n.getY();
_z = $n.getZ();
setDirtyFlag();
}
public Number3d toNumber3d()
{
return new Number3d(_x,_y,_z);
}
@Override
public String toString()
{
return _x + "," + _y + "," + _z;
}
/**
* Convenience method
*/
public FloatBuffer toFloatBuffer()
{
|
// Path: openCVTutorial1CameraPreview/src/main/java/aruco/min3d/Utils.java
// public class Utils
// {
// public static final float DEG = (float)(Math.PI / 180f);
//
// private static final int BYTES_PER_FLOAT = 4;
//
// /**
// * Convenience method to create a Bitmap given a Context's drawable resource ID.
// */
// public static Bitmap makeBitmapFromResourceId(Context $context, int $id)
// {
// InputStream is = $context.getResources().openRawResource($id);
//
// Bitmap bitmap;
// try {
// bitmap = BitmapFactory.decodeStream(is);
// } finally {
// try {
// is.close();
// } catch(IOException e) {
// // Ignore.
// }
// }
//
// return bitmap;
// }
//
// /**
// * Convenience method to create a Bitmap given a drawable resource ID from the application Context.
// */
// public static Bitmap makeBitmapFromResourceId(int $id)
// {
// return makeBitmapFromResourceId(Shared.context(), $id);
// }
//
// /**
// * Add two triangles to the Object3d's faces using the supplied indices
// */
// public static void addQuad(Object3d $o, int $upperLeft, int $upperRight, int $lowerRight, int $lowerLeft)
// {
// $o.faces().add((short)$upperLeft, (short)$lowerRight, (short)$upperRight);
// $o.faces().add((short)$upperLeft, (short)$lowerLeft, (short)$lowerRight);
// }
//
// public static FloatBuffer makeFloatBuffer3(float $a, float $b, float $c)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(3 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.position(0);
// return buffer;
// }
//
// public static FloatBuffer makeFloatBuffer4(float $a, float $b, float $c, float $d)
// {
// ByteBuffer b = ByteBuffer.allocateDirect(4 * BYTES_PER_FLOAT);
// b.order(ByteOrder.nativeOrder());
// FloatBuffer buffer = b.asFloatBuffer();
// buffer.put($a);
// buffer.put($b);
// buffer.put($c);
// buffer.put($d);
// buffer.position(0);
// return buffer;
// }
// }
// Path: openCVTutorial1CameraPreview/src/main/java/min3d/vos/Number3dManaged.java
import java.nio.FloatBuffer;
import min3d.interfaces.IDirtyParent;
import aruco.min3d.Utils;
_x = $n.x;
_y = $n.y;
_z = $n.z;
setDirtyFlag();
}
public void setAllFrom(Number3dManaged $n)
{
_x = $n.getX();
_y = $n.getY();
_z = $n.getZ();
setDirtyFlag();
}
public Number3d toNumber3d()
{
return new Number3d(_x,_y,_z);
}
@Override
public String toString()
{
return _x + "," + _y + "," + _z;
}
/**
* Convenience method
*/
public FloatBuffer toFloatBuffer()
{
|
return Utils.makeFloatBuffer3(_x, _y, _z);
|
DhruvKumar/iot-lab
|
part1/src/main/java/com/hortonworks/lab/Lab.java
|
// Path: common-sources/src/main/java/com/hortonworks/labutils/PropertyParser.java
// public class PropertyParser {
//
// private static final Logger LOG = LoggerFactory.getLogger(PropertyParser.class);
//
// public Properties props = new Properties();
// private String propFileName;
//
// public PropertyParser(String propFileName) {
// this.propFileName = propFileName;
// }
//
// public String getPropFileName() {
// return propFileName;
// }
//
// public void setPropFileName(String propFileName) {
// this.propFileName = propFileName;
// }
//
// public String getProperty(String key) {
// return props.get(key).toString();
// }
//
// public void parsePropsFile() throws IOException {
//
// InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
//
// try {
// if (null != inputStream) {
// props.load(inputStream);
// } else {
// throw new IOException("Could not load property file from the resources directory, trying local");
// }
// } catch(IOException e) {
// LOG.error(e.getMessage());
// e.printStackTrace();
// try {
// inputStream = new FileInputStream(new File(propFileName).getAbsolutePath());
// props.load(inputStream);
// } catch (IOException ex) {
// LOG.error("Could not load property file at " + new File(propFileName).getAbsolutePath());
// ex.printStackTrace();
// throw ex;
// }
// }
// }
// }
|
import com.github.sakserv.minicluster.config.ConfigVars;
import com.github.sakserv.minicluster.impl.KafkaLocalBroker;
import com.github.sakserv.minicluster.impl.ZookeeperLocalCluster;
import com.hortonworks.labutils.PropertyParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Launcher;
import java.io.IOException;
import java.util.Properties;
|
package com.hortonworks.lab;
/**
* In this first lab we show how to set up the dev environment and use the Hadoop Mini Clusters project. We'll
* configure Zookeeper and Kafka and start them in a local mode. Next, we'll generate events using the Akka library
* and send them to Kafka.
*/
public class Lab {
private static final Logger LOG = LoggerFactory.getLogger(Lab.class);
|
// Path: common-sources/src/main/java/com/hortonworks/labutils/PropertyParser.java
// public class PropertyParser {
//
// private static final Logger LOG = LoggerFactory.getLogger(PropertyParser.class);
//
// public Properties props = new Properties();
// private String propFileName;
//
// public PropertyParser(String propFileName) {
// this.propFileName = propFileName;
// }
//
// public String getPropFileName() {
// return propFileName;
// }
//
// public void setPropFileName(String propFileName) {
// this.propFileName = propFileName;
// }
//
// public String getProperty(String key) {
// return props.get(key).toString();
// }
//
// public void parsePropsFile() throws IOException {
//
// InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
//
// try {
// if (null != inputStream) {
// props.load(inputStream);
// } else {
// throw new IOException("Could not load property file from the resources directory, trying local");
// }
// } catch(IOException e) {
// LOG.error(e.getMessage());
// e.printStackTrace();
// try {
// inputStream = new FileInputStream(new File(propFileName).getAbsolutePath());
// props.load(inputStream);
// } catch (IOException ex) {
// LOG.error("Could not load property file at " + new File(propFileName).getAbsolutePath());
// ex.printStackTrace();
// throw ex;
// }
// }
// }
// }
// Path: part1/src/main/java/com/hortonworks/lab/Lab.java
import com.github.sakserv.minicluster.config.ConfigVars;
import com.github.sakserv.minicluster.impl.KafkaLocalBroker;
import com.github.sakserv.minicluster.impl.ZookeeperLocalCluster;
import com.hortonworks.labutils.PropertyParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Launcher;
import java.io.IOException;
import java.util.Properties;
package com.hortonworks.lab;
/**
* In this first lab we show how to set up the dev environment and use the Hadoop Mini Clusters project. We'll
* configure Zookeeper and Kafka and start them in a local mode. Next, we'll generate events using the Akka library
* and send them to Kafka.
*/
public class Lab {
private static final Logger LOG = LoggerFactory.getLogger(Lab.class);
|
private static PropertyParser propertyParser;
|
DhruvKumar/iot-lab
|
common-sources/src/main/java/com/hortonworks/simulator/impl/domain/transport/TruckConfiguration.java
|
// Path: common-sources/src/main/java/com/hortonworks/simulator/impl/domain/transport/route/Route.java
// public interface Route {
// List<Location> getLocations();
// Location getNextLocation();
// Location getStartingPoint();
// boolean routeEnded();
// int getRouteId();
// String getRouteName();
// }
|
import com.hortonworks.simulator.datagenerator.DataGeneratorUtils;
import com.hortonworks.simulator.impl.domain.transport.route.Route;
import com.hortonworks.simulator.impl.domain.transport.route.TruckRoutesParser;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
|
package com.hortonworks.simulator.impl.domain.transport;
public class TruckConfiguration {
private static Logger LOGGER = Logger.getLogger(TruckConfiguration.class);
public static final long END_ROUTE_AFTER_METERS = 120000; // 75 miles
private static final int TRUCK_FLEET_SIZE=100;
private static final int TRUCK_ID_START = 10;
public static final int MAX_ROUTE_TRAVERSAL_COUNT = 10;
private static Map<Integer, Driver> drivers;
public static ConcurrentLinkedQueue<Integer> freeTruckPool = null;
|
// Path: common-sources/src/main/java/com/hortonworks/simulator/impl/domain/transport/route/Route.java
// public interface Route {
// List<Location> getLocations();
// Location getNextLocation();
// Location getStartingPoint();
// boolean routeEnded();
// int getRouteId();
// String getRouteName();
// }
// Path: common-sources/src/main/java/com/hortonworks/simulator/impl/domain/transport/TruckConfiguration.java
import com.hortonworks.simulator.datagenerator.DataGeneratorUtils;
import com.hortonworks.simulator.impl.domain.transport.route.Route;
import com.hortonworks.simulator.impl.domain.transport.route.TruckRoutesParser;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
package com.hortonworks.simulator.impl.domain.transport;
public class TruckConfiguration {
private static Logger LOGGER = Logger.getLogger(TruckConfiguration.class);
public static final long END_ROUTE_AFTER_METERS = 120000; // 75 miles
private static final int TRUCK_FLEET_SIZE=100;
private static final int TRUCK_ID_START = 10;
public static final int MAX_ROUTE_TRAVERSAL_COUNT = 10;
private static Map<Integer, Driver> drivers;
public static ConcurrentLinkedQueue<Integer> freeTruckPool = null;
|
public static ConcurrentLinkedQueue<Route> freeRoutePool = null;
|
DhruvKumar/iot-lab
|
common-sources/src/main/java/com/hortonworks/simulator/impl/domain/rental/RentalService.java
|
// Path: common-sources/src/main/java/com/hortonworks/simulator/impl/domain/Event.java
// public class Event {
// @Override
// public String toString() {
// return new ToStringBuilder(this).toString();
// }
// }
|
import akka.actor.ActorSelection;
import com.hortonworks.simulator.impl.domain.AbstractEventEmitter;
import com.hortonworks.simulator.impl.domain.Event;
import org.apache.log4j.Logger;
import java.util.HashMap;
import java.util.Random;
|
package com.hortonworks.simulator.impl.domain.rental;
public class RentalService extends AbstractEventEmitter {
private static final long serialVersionUID = -7707647735283442703L;
private String rentalServiceId = new String();
private HashMap<String, String> rentalServiceConfig = null;
private Random rand = new Random();
private int numberOfEvents = 0;
private Logger logger = Logger.getLogger(RentalService.class);
public RentalService(String rentalServiceId,
HashMap<String, String> rentalServiceConfig) {
this.rentalServiceId = rentalServiceId;
this.rentalServiceConfig = rentalServiceConfig;
}
@Override
|
// Path: common-sources/src/main/java/com/hortonworks/simulator/impl/domain/Event.java
// public class Event {
// @Override
// public String toString() {
// return new ToStringBuilder(this).toString();
// }
// }
// Path: common-sources/src/main/java/com/hortonworks/simulator/impl/domain/rental/RentalService.java
import akka.actor.ActorSelection;
import com.hortonworks.simulator.impl.domain.AbstractEventEmitter;
import com.hortonworks.simulator.impl.domain.Event;
import org.apache.log4j.Logger;
import java.util.HashMap;
import java.util.Random;
package com.hortonworks.simulator.impl.domain.rental;
public class RentalService extends AbstractEventEmitter {
private static final long serialVersionUID = -7707647735283442703L;
private String rentalServiceId = new String();
private HashMap<String, String> rentalServiceConfig = null;
private Random rand = new Random();
private int numberOfEvents = 0;
private Logger logger = Logger.getLogger(RentalService.class);
public RentalService(String rentalServiceId,
HashMap<String, String> rentalServiceConfig) {
this.rentalServiceId = rentalServiceId;
this.rentalServiceConfig = rentalServiceConfig;
}
@Override
|
public Event generateEvent() {
|
DhruvKumar/iot-lab
|
common-sources/src/main/java/com/hortonworks/simulator/impl/domain/transport/Driver.java
|
// Path: common-sources/src/main/java/com/hortonworks/simulator/impl/domain/transport/route/Route.java
// public interface Route {
// List<Location> getLocations();
// Location getNextLocation();
// Location getStartingPoint();
// boolean routeEnded();
// int getRouteId();
// String getRouteName();
// }
|
import com.hortonworks.simulator.impl.domain.transport.route.Route;
import com.hortonworks.simulator.interfaces.DomainObject;
|
package com.hortonworks.simulator.impl.domain.transport;
public class Driver implements DomainObject {
private static final long serialVersionUID = 6113264533619087412L;
private int driverId;
private int riskFactor;
|
// Path: common-sources/src/main/java/com/hortonworks/simulator/impl/domain/transport/route/Route.java
// public interface Route {
// List<Location> getLocations();
// Location getNextLocation();
// Location getStartingPoint();
// boolean routeEnded();
// int getRouteId();
// String getRouteName();
// }
// Path: common-sources/src/main/java/com/hortonworks/simulator/impl/domain/transport/Driver.java
import com.hortonworks.simulator.impl.domain.transport.route.Route;
import com.hortonworks.simulator.interfaces.DomainObject;
package com.hortonworks.simulator.impl.domain.transport;
public class Driver implements DomainObject {
private static final long serialVersionUID = 6113264533619087412L;
private int driverId;
private int riskFactor;
|
private Route route;
|
DhruvKumar/iot-lab
|
common-sources/src/main/java/com/hortonworks/simulator/masters/SimulationMaster.java
|
// Path: common-sources/src/main/java/com/hortonworks/simulator/impl/messages/StartSimulation.java
// public class StartSimulation {
//
// }
|
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.routing.RoundRobinRouter;
import com.hortonworks.simulator.impl.messages.EmitEvent;
import com.hortonworks.simulator.impl.messages.StartSimulation;
import com.hortonworks.simulator.impl.messages.StopSimulation;
import com.hortonworks.simulator.results.SimulationResultsSummary;
import org.apache.log4j.Logger;
|
package com.hortonworks.simulator.masters;
@SuppressWarnings("rawtypes")
public class SimulationMaster extends UntypedActor {
private int numberOfEventEmitters = 1;
private int numberOfEvents = 1;
private Class eventEmitterClass;
private ActorRef eventEmitterRouter;
private ActorRef listener;
private int eventCount = 0;
private Logger logger = Logger.getLogger(SimulationMaster.class);
@SuppressWarnings("unchecked")
public SimulationMaster(int numberOfEventEmitters, Class eventEmitterClass,
ActorRef listener, int numberOfEvents, long demoId, int messageDelay) {
logger.info("Starting simulation with " + numberOfEventEmitters
+ " of " + eventEmitterClass + " Event Emitters -- "
+ eventEmitterClass.toString());
this.listener = listener;
this.numberOfEventEmitters = numberOfEventEmitters;
this.eventEmitterClass = eventEmitterClass;
eventEmitterRouter = this.getContext().actorOf(
Props.create(eventEmitterClass, numberOfEvents, demoId, messageDelay).withRouter(
new RoundRobinRouter(numberOfEventEmitters)),
"eventEmitterRouter");
}
@Override
public void onReceive(Object message) throws Exception {
|
// Path: common-sources/src/main/java/com/hortonworks/simulator/impl/messages/StartSimulation.java
// public class StartSimulation {
//
// }
// Path: common-sources/src/main/java/com/hortonworks/simulator/masters/SimulationMaster.java
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.routing.RoundRobinRouter;
import com.hortonworks.simulator.impl.messages.EmitEvent;
import com.hortonworks.simulator.impl.messages.StartSimulation;
import com.hortonworks.simulator.impl.messages.StopSimulation;
import com.hortonworks.simulator.results.SimulationResultsSummary;
import org.apache.log4j.Logger;
package com.hortonworks.simulator.masters;
@SuppressWarnings("rawtypes")
public class SimulationMaster extends UntypedActor {
private int numberOfEventEmitters = 1;
private int numberOfEvents = 1;
private Class eventEmitterClass;
private ActorRef eventEmitterRouter;
private ActorRef listener;
private int eventCount = 0;
private Logger logger = Logger.getLogger(SimulationMaster.class);
@SuppressWarnings("unchecked")
public SimulationMaster(int numberOfEventEmitters, Class eventEmitterClass,
ActorRef listener, int numberOfEvents, long demoId, int messageDelay) {
logger.info("Starting simulation with " + numberOfEventEmitters
+ " of " + eventEmitterClass + " Event Emitters -- "
+ eventEmitterClass.toString());
this.listener = listener;
this.numberOfEventEmitters = numberOfEventEmitters;
this.eventEmitterClass = eventEmitterClass;
eventEmitterRouter = this.getContext().actorOf(
Props.create(eventEmitterClass, numberOfEvents, demoId, messageDelay).withRouter(
new RoundRobinRouter(numberOfEventEmitters)),
"eventEmitterRouter");
}
@Override
public void onReceive(Object message) throws Exception {
|
if (message instanceof StartSimulation) {
|
Techjar/VivecraftForgeExtensions
|
src/main/java/com/techjar/vivecraftforge/network/VivecraftForgePacketHandler.java
|
// Path: src/main/java/com/techjar/vivecraftforge/VivecraftForge.java
// @Mod(modid = "VivecraftForge", name = "Vivecraft Forge Extensions", version = "@VERSION@", dependencies = "required-after:Forge@[10.13.4.1558,)", acceptableRemoteVersions = "@RAW_VERSION@.*")
// public class VivecraftForge {
// @Instance("VivecraftForge")
// public static VivecraftForge instance;
//
// @SidedProxy(clientSide = "com.techjar.vivecraftforge.proxy.ProxyClient", serverSide = "com.techjar.vivecraftforge.proxy.ProxyServer")
// public static ProxyCommon proxy;
//
// public static SimpleNetworkWrapper networkVersion;
// //public static SimpleNetworkWrapper networkFreeMove; // currently not used
// public static SimpleNetworkWrapper networkLegacy;
// public static SimpleNetworkWrapper networkOK;
//
// public static VivecraftForgeChannelHandler packetPipeline;
//
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// config.load();
// Config.vrCreeperSwellDistance = config.get(Configuration.CATEGORY_GENERAL, "vrCreeperSwellDistance", 1.75, "Distance at which creepers swell and explode for VR players. Default: 1.75").getDouble(1.75D);
// if (config.hasChanged()) config.save();
// }
//
// @EventHandler
// public void load(FMLInitializationEvent event) {
// packetPipeline = VivecraftForgeChannelHandler.init();
// proxy.registerNetworkChannels();
// proxy.registerEventHandlers();
// proxy.registerEntities();
// proxy.registerRenderers();
// }
//
// @EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// // Stub Method
// }
// }
//
// Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java
// public class VivecraftForgeLog {
// public static void info(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data);
// }
//
// public static void warning(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data);
// }
//
// public static void severe(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data);
// }
//
// public static void debug(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data);
// }
// }
|
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetHandler;
import com.techjar.vivecraftforge.VivecraftForge;
import com.techjar.vivecraftforge.util.VivecraftForgeLog;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
|
package com.techjar.vivecraftforge.network;
@Sharable
public class VivecraftForgePacketHandler extends SimpleChannelInboundHandler<IPacket> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, IPacket msg) throws Exception {
INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();
|
// Path: src/main/java/com/techjar/vivecraftforge/VivecraftForge.java
// @Mod(modid = "VivecraftForge", name = "Vivecraft Forge Extensions", version = "@VERSION@", dependencies = "required-after:Forge@[10.13.4.1558,)", acceptableRemoteVersions = "@RAW_VERSION@.*")
// public class VivecraftForge {
// @Instance("VivecraftForge")
// public static VivecraftForge instance;
//
// @SidedProxy(clientSide = "com.techjar.vivecraftforge.proxy.ProxyClient", serverSide = "com.techjar.vivecraftforge.proxy.ProxyServer")
// public static ProxyCommon proxy;
//
// public static SimpleNetworkWrapper networkVersion;
// //public static SimpleNetworkWrapper networkFreeMove; // currently not used
// public static SimpleNetworkWrapper networkLegacy;
// public static SimpleNetworkWrapper networkOK;
//
// public static VivecraftForgeChannelHandler packetPipeline;
//
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// config.load();
// Config.vrCreeperSwellDistance = config.get(Configuration.CATEGORY_GENERAL, "vrCreeperSwellDistance", 1.75, "Distance at which creepers swell and explode for VR players. Default: 1.75").getDouble(1.75D);
// if (config.hasChanged()) config.save();
// }
//
// @EventHandler
// public void load(FMLInitializationEvent event) {
// packetPipeline = VivecraftForgeChannelHandler.init();
// proxy.registerNetworkChannels();
// proxy.registerEventHandlers();
// proxy.registerEntities();
// proxy.registerRenderers();
// }
//
// @EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// // Stub Method
// }
// }
//
// Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java
// public class VivecraftForgeLog {
// public static void info(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data);
// }
//
// public static void warning(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data);
// }
//
// public static void severe(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data);
// }
//
// public static void debug(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data);
// }
// }
// Path: src/main/java/com/techjar/vivecraftforge/network/VivecraftForgePacketHandler.java
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetHandler;
import com.techjar.vivecraftforge.VivecraftForge;
import com.techjar.vivecraftforge.util.VivecraftForgeLog;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
package com.techjar.vivecraftforge.network;
@Sharable
public class VivecraftForgePacketHandler extends SimpleChannelInboundHandler<IPacket> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, IPacket msg) throws Exception {
INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();
|
EntityPlayer player = VivecraftForge.proxy.getPlayerFromNetHandler(netHandler);
|
Techjar/VivecraftForgeExtensions
|
src/main/java/com/techjar/vivecraftforge/network/VivecraftForgePacketHandler.java
|
// Path: src/main/java/com/techjar/vivecraftforge/VivecraftForge.java
// @Mod(modid = "VivecraftForge", name = "Vivecraft Forge Extensions", version = "@VERSION@", dependencies = "required-after:Forge@[10.13.4.1558,)", acceptableRemoteVersions = "@RAW_VERSION@.*")
// public class VivecraftForge {
// @Instance("VivecraftForge")
// public static VivecraftForge instance;
//
// @SidedProxy(clientSide = "com.techjar.vivecraftforge.proxy.ProxyClient", serverSide = "com.techjar.vivecraftforge.proxy.ProxyServer")
// public static ProxyCommon proxy;
//
// public static SimpleNetworkWrapper networkVersion;
// //public static SimpleNetworkWrapper networkFreeMove; // currently not used
// public static SimpleNetworkWrapper networkLegacy;
// public static SimpleNetworkWrapper networkOK;
//
// public static VivecraftForgeChannelHandler packetPipeline;
//
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// config.load();
// Config.vrCreeperSwellDistance = config.get(Configuration.CATEGORY_GENERAL, "vrCreeperSwellDistance", 1.75, "Distance at which creepers swell and explode for VR players. Default: 1.75").getDouble(1.75D);
// if (config.hasChanged()) config.save();
// }
//
// @EventHandler
// public void load(FMLInitializationEvent event) {
// packetPipeline = VivecraftForgeChannelHandler.init();
// proxy.registerNetworkChannels();
// proxy.registerEventHandlers();
// proxy.registerEntities();
// proxy.registerRenderers();
// }
//
// @EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// // Stub Method
// }
// }
//
// Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java
// public class VivecraftForgeLog {
// public static void info(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data);
// }
//
// public static void warning(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data);
// }
//
// public static void severe(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data);
// }
//
// public static void debug(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data);
// }
// }
|
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetHandler;
import com.techjar.vivecraftforge.VivecraftForge;
import com.techjar.vivecraftforge.util.VivecraftForgeLog;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
|
package com.techjar.vivecraftforge.network;
@Sharable
public class VivecraftForgePacketHandler extends SimpleChannelInboundHandler<IPacket> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, IPacket msg) throws Exception {
INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();
EntityPlayer player = VivecraftForge.proxy.getPlayerFromNetHandler(netHandler);
switch (FMLCommonHandler.instance().getEffectiveSide()) {
case CLIENT:
msg.handleClient(player);
break;
case SERVER:
msg.handleServer(player);
break;
default:
|
// Path: src/main/java/com/techjar/vivecraftforge/VivecraftForge.java
// @Mod(modid = "VivecraftForge", name = "Vivecraft Forge Extensions", version = "@VERSION@", dependencies = "required-after:Forge@[10.13.4.1558,)", acceptableRemoteVersions = "@RAW_VERSION@.*")
// public class VivecraftForge {
// @Instance("VivecraftForge")
// public static VivecraftForge instance;
//
// @SidedProxy(clientSide = "com.techjar.vivecraftforge.proxy.ProxyClient", serverSide = "com.techjar.vivecraftforge.proxy.ProxyServer")
// public static ProxyCommon proxy;
//
// public static SimpleNetworkWrapper networkVersion;
// //public static SimpleNetworkWrapper networkFreeMove; // currently not used
// public static SimpleNetworkWrapper networkLegacy;
// public static SimpleNetworkWrapper networkOK;
//
// public static VivecraftForgeChannelHandler packetPipeline;
//
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// config.load();
// Config.vrCreeperSwellDistance = config.get(Configuration.CATEGORY_GENERAL, "vrCreeperSwellDistance", 1.75, "Distance at which creepers swell and explode for VR players. Default: 1.75").getDouble(1.75D);
// if (config.hasChanged()) config.save();
// }
//
// @EventHandler
// public void load(FMLInitializationEvent event) {
// packetPipeline = VivecraftForgeChannelHandler.init();
// proxy.registerNetworkChannels();
// proxy.registerEventHandlers();
// proxy.registerEntities();
// proxy.registerRenderers();
// }
//
// @EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// // Stub Method
// }
// }
//
// Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java
// public class VivecraftForgeLog {
// public static void info(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data);
// }
//
// public static void warning(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data);
// }
//
// public static void severe(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data);
// }
//
// public static void debug(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data);
// }
// }
// Path: src/main/java/com/techjar/vivecraftforge/network/VivecraftForgePacketHandler.java
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetHandler;
import com.techjar.vivecraftforge.VivecraftForge;
import com.techjar.vivecraftforge.util.VivecraftForgeLog;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
package com.techjar.vivecraftforge.network;
@Sharable
public class VivecraftForgePacketHandler extends SimpleChannelInboundHandler<IPacket> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, IPacket msg) throws Exception {
INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();
EntityPlayer player = VivecraftForge.proxy.getPlayerFromNetHandler(netHandler);
switch (FMLCommonHandler.instance().getEffectiveSide()) {
case CLIENT:
msg.handleClient(player);
break;
case SERVER:
msg.handleServer(player);
break;
default:
|
VivecraftForgeLog.severe("Impossible scenario encountered! Effective side is neither server nor client!");
|
Techjar/VivecraftForgeExtensions
|
src/main/java/com/techjar/vivecraftforge/network/ViveMessage.java
|
// Path: src/main/java/com/techjar/vivecraftforge/VivecraftForge.java
// @Mod(modid = "VivecraftForge", name = "Vivecraft Forge Extensions", version = "@VERSION@", dependencies = "required-after:Forge@[10.13.4.1558,)", acceptableRemoteVersions = "@RAW_VERSION@.*")
// public class VivecraftForge {
// @Instance("VivecraftForge")
// public static VivecraftForge instance;
//
// @SidedProxy(clientSide = "com.techjar.vivecraftforge.proxy.ProxyClient", serverSide = "com.techjar.vivecraftforge.proxy.ProxyServer")
// public static ProxyCommon proxy;
//
// public static SimpleNetworkWrapper networkVersion;
// //public static SimpleNetworkWrapper networkFreeMove; // currently not used
// public static SimpleNetworkWrapper networkLegacy;
// public static SimpleNetworkWrapper networkOK;
//
// public static VivecraftForgeChannelHandler packetPipeline;
//
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// config.load();
// Config.vrCreeperSwellDistance = config.get(Configuration.CATEGORY_GENERAL, "vrCreeperSwellDistance", 1.75, "Distance at which creepers swell and explode for VR players. Default: 1.75").getDouble(1.75D);
// if (config.hasChanged()) config.save();
// }
//
// @EventHandler
// public void load(FMLInitializationEvent event) {
// packetPipeline = VivecraftForgeChannelHandler.init();
// proxy.registerNetworkChannels();
// proxy.registerEventHandlers();
// proxy.registerEntities();
// proxy.registerRenderers();
// }
//
// @EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// // Stub Method
// }
// }
|
import com.techjar.vivecraftforge.VivecraftForge;
import io.netty.buffer.ByteBuf;
import cpw.mods.fml.common.network.ByteBufUtils;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
|
package com.techjar.vivecraftforge.network;
public class ViveMessage implements IMessage {
public static class Handle implements IMessageHandler<ViveMessage, IMessage> {
@Override
public IMessage onMessage(ViveMessage message, MessageContext ctx) {
|
// Path: src/main/java/com/techjar/vivecraftforge/VivecraftForge.java
// @Mod(modid = "VivecraftForge", name = "Vivecraft Forge Extensions", version = "@VERSION@", dependencies = "required-after:Forge@[10.13.4.1558,)", acceptableRemoteVersions = "@RAW_VERSION@.*")
// public class VivecraftForge {
// @Instance("VivecraftForge")
// public static VivecraftForge instance;
//
// @SidedProxy(clientSide = "com.techjar.vivecraftforge.proxy.ProxyClient", serverSide = "com.techjar.vivecraftforge.proxy.ProxyServer")
// public static ProxyCommon proxy;
//
// public static SimpleNetworkWrapper networkVersion;
// //public static SimpleNetworkWrapper networkFreeMove; // currently not used
// public static SimpleNetworkWrapper networkLegacy;
// public static SimpleNetworkWrapper networkOK;
//
// public static VivecraftForgeChannelHandler packetPipeline;
//
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// config.load();
// Config.vrCreeperSwellDistance = config.get(Configuration.CATEGORY_GENERAL, "vrCreeperSwellDistance", 1.75, "Distance at which creepers swell and explode for VR players. Default: 1.75").getDouble(1.75D);
// if (config.hasChanged()) config.save();
// }
//
// @EventHandler
// public void load(FMLInitializationEvent event) {
// packetPipeline = VivecraftForgeChannelHandler.init();
// proxy.registerNetworkChannels();
// proxy.registerEventHandlers();
// proxy.registerEntities();
// proxy.registerRenderers();
// }
//
// @EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// // Stub Method
// }
// }
// Path: src/main/java/com/techjar/vivecraftforge/network/ViveMessage.java
import com.techjar.vivecraftforge.VivecraftForge;
import io.netty.buffer.ByteBuf;
import cpw.mods.fml.common.network.ByteBufUtils;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
package com.techjar.vivecraftforge.network;
public class ViveMessage implements IMessage {
public static class Handle implements IMessageHandler<ViveMessage, IMessage> {
@Override
public IMessage onMessage(ViveMessage message, MessageContext ctx) {
|
VivecraftForge.networkOK.sendTo(new ViveMessage("Teleport to your heart's content!"), ctx.getServerHandler().playerEntity);
|
Techjar/VivecraftForgeExtensions
|
src/main/java/com/techjar/vivecraftforge/core/FMLPlugin.java
|
// Path: src/main/java/com/techjar/vivecraftforge/core/asm/ClassTransformer.java
// public class ClassTransformer implements IClassTransformer {
// private static final List<ASMClassHandler> asmHandlers = new ArrayList<ASMClassHandler>();
// static {
// asmHandlers.add(new ASMHandlerEnableTeleporting());
// asmHandlers.add(new ASMHandlerHackForgeChannelName());
// asmHandlers.add(new ASMHandlerPlayerScaling());
// asmHandlers.add(new ASMHandlerIncreaseReachDistance());
// asmHandlers.add(new ASMHandlerCreeperRadius());
// asmHandlers.add(new ASMHandlerEndermanLook());
// }
//
// @Override
// public byte[] transform(String name, String transformedName, byte[] bytes) {
// for (ASMClassHandler handler : asmHandlers) {
// if (!handler.shouldPatchClass()) continue;
// ClassTuple tuple = handler.getDesiredClass();
// if (name.equals(tuple.classNameObf)) {
// VivecraftForgeLog.debug("Patching class: " + name + " (" + tuple.className + ")");
// bytes = handler.patchClass(bytes, true);
// } else if (name.equals(tuple.className)) {
// VivecraftForgeLog.debug("Patching class: " + name);
// bytes = handler.patchClass(bytes, false);
// }
// }
// return bytes;
// }
// }
|
import java.io.File;
import java.util.Map;
import com.techjar.vivecraftforge.core.asm.ClassTransformer;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.SortingIndex;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.Name;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.TransformerExclusions;
|
package com.techjar.vivecraftforge.core;
@Name("VivecraftForgeCore")
@MCVersion("1.7.10")
@TransformerExclusions("com.techjar.vivecraftforge.core")
//@SortingIndex(1001)
public class FMLPlugin implements IFMLLoadingPlugin {
public static File location;
@Override
public String[] getASMTransformerClass() {
|
// Path: src/main/java/com/techjar/vivecraftforge/core/asm/ClassTransformer.java
// public class ClassTransformer implements IClassTransformer {
// private static final List<ASMClassHandler> asmHandlers = new ArrayList<ASMClassHandler>();
// static {
// asmHandlers.add(new ASMHandlerEnableTeleporting());
// asmHandlers.add(new ASMHandlerHackForgeChannelName());
// asmHandlers.add(new ASMHandlerPlayerScaling());
// asmHandlers.add(new ASMHandlerIncreaseReachDistance());
// asmHandlers.add(new ASMHandlerCreeperRadius());
// asmHandlers.add(new ASMHandlerEndermanLook());
// }
//
// @Override
// public byte[] transform(String name, String transformedName, byte[] bytes) {
// for (ASMClassHandler handler : asmHandlers) {
// if (!handler.shouldPatchClass()) continue;
// ClassTuple tuple = handler.getDesiredClass();
// if (name.equals(tuple.classNameObf)) {
// VivecraftForgeLog.debug("Patching class: " + name + " (" + tuple.className + ")");
// bytes = handler.patchClass(bytes, true);
// } else if (name.equals(tuple.className)) {
// VivecraftForgeLog.debug("Patching class: " + name);
// bytes = handler.patchClass(bytes, false);
// }
// }
// return bytes;
// }
// }
// Path: src/main/java/com/techjar/vivecraftforge/core/FMLPlugin.java
import java.io.File;
import java.util.Map;
import com.techjar.vivecraftforge.core.asm.ClassTransformer;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.SortingIndex;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.Name;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.TransformerExclusions;
package com.techjar.vivecraftforge.core;
@Name("VivecraftForgeCore")
@MCVersion("1.7.10")
@TransformerExclusions("com.techjar.vivecraftforge.core")
//@SortingIndex(1001)
public class FMLPlugin implements IFMLLoadingPlugin {
public static File location;
@Override
public String[] getASMTransformerClass() {
|
return new String[]{ClassTransformer.class.getName()};
|
Techjar/VivecraftForgeExtensions
|
src/main/java/com/techjar/vivecraftforge/core/asm/ClassTransformer.java
|
// Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java
// public class VivecraftForgeLog {
// public static void info(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data);
// }
//
// public static void warning(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data);
// }
//
// public static void severe(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data);
// }
//
// public static void debug(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data);
// }
// }
|
import java.util.ArrayList;
import java.util.List;
import org.objectweb.asm.Type;
import com.techjar.vivecraftforge.core.asm.handler.*;
import com.techjar.vivecraftforge.util.VivecraftForgeLog;
import net.minecraft.entity.EntityLiving;
import net.minecraft.launchwrapper.IClassTransformer;
|
package com.techjar.vivecraftforge.core.asm;
public class ClassTransformer implements IClassTransformer {
private static final List<ASMClassHandler> asmHandlers = new ArrayList<ASMClassHandler>();
static {
asmHandlers.add(new ASMHandlerEnableTeleporting());
asmHandlers.add(new ASMHandlerHackForgeChannelName());
asmHandlers.add(new ASMHandlerPlayerScaling());
asmHandlers.add(new ASMHandlerIncreaseReachDistance());
asmHandlers.add(new ASMHandlerCreeperRadius());
asmHandlers.add(new ASMHandlerEndermanLook());
}
@Override
public byte[] transform(String name, String transformedName, byte[] bytes) {
for (ASMClassHandler handler : asmHandlers) {
if (!handler.shouldPatchClass()) continue;
ClassTuple tuple = handler.getDesiredClass();
if (name.equals(tuple.classNameObf)) {
|
// Path: src/main/java/com/techjar/vivecraftforge/util/VivecraftForgeLog.java
// public class VivecraftForgeLog {
// public static void info(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.INFO, message, data);
// }
//
// public static void warning(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.WARN, message, data);
// }
//
// public static void severe(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.ERROR, message, data);
// }
//
// public static void debug(String message, Object... data) {
// FMLRelaunchLog.log("Vivecraft Forge Extensions", Level.DEBUG, message, data);
// }
// }
// Path: src/main/java/com/techjar/vivecraftforge/core/asm/ClassTransformer.java
import java.util.ArrayList;
import java.util.List;
import org.objectweb.asm.Type;
import com.techjar.vivecraftforge.core.asm.handler.*;
import com.techjar.vivecraftforge.util.VivecraftForgeLog;
import net.minecraft.entity.EntityLiving;
import net.minecraft.launchwrapper.IClassTransformer;
package com.techjar.vivecraftforge.core.asm;
public class ClassTransformer implements IClassTransformer {
private static final List<ASMClassHandler> asmHandlers = new ArrayList<ASMClassHandler>();
static {
asmHandlers.add(new ASMHandlerEnableTeleporting());
asmHandlers.add(new ASMHandlerHackForgeChannelName());
asmHandlers.add(new ASMHandlerPlayerScaling());
asmHandlers.add(new ASMHandlerIncreaseReachDistance());
asmHandlers.add(new ASMHandlerCreeperRadius());
asmHandlers.add(new ASMHandlerEndermanLook());
}
@Override
public byte[] transform(String name, String transformedName, byte[] bytes) {
for (ASMClassHandler handler : asmHandlers) {
if (!handler.shouldPatchClass()) continue;
ClassTuple tuple = handler.getDesiredClass();
if (name.equals(tuple.classNameObf)) {
|
VivecraftForgeLog.debug("Patching class: " + name + " (" + tuple.className + ")");
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Genome.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/Solution.java
// public interface Solution<SolutionImplementationType extends Solution<?>> {
//
// /**
// * Returns a numeric value that represents the costs of this solution. If
// * the optimization problem is, to maximize the costs of a solution the
// * return value indicates the absolute quality of the solution (the
// * fitness).
// **/
// int getCosts();
//
// /**
// * Compares this solution to another solution.
// *
// * @return <code>true</code> if this solution instance is better than the
// * other solution<br>
// * <code>false</code> if this solution is of worse or equal quality.
// **/
// boolean isBetterThan(SolutionImplementationType otherSolution);
//
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/util/Comparable.java
// public interface Comparable<T> extends java.lang.Comparable<T> {
//
// static final int LOWER = -1;
// static final int EQUAL = 0;
// static final int GREATER = 1;
//
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/util/RNGGenerator.java
// public abstract class RNGGenerator {
// private final static Logger log = (Logger) LoggerFactory.getLogger(RNGGenerator.class);
//
// private static Random seedGenerator;
//
// public static void setMasterSeed(long masterSeed) {
// seedGenerator = new Random(masterSeed);
// log.info("Initialized random number generator with master seed {}", masterSeed);
// }
//
// public static Random createRandomNumberGenerator() {
// if (seedGenerator == null) {
// setMasterSeed(System.currentTimeMillis());
// }
// long seed = seedGenerator.nextLong();
// return new Random(seed);
// }
//
// }
|
import de.mh4j.solver.Solution;
import de.mh4j.util.Comparable;
import de.mh4j.util.RNGGenerator;
import java.util.Random;
|
/*
* Copyright 2012 Friedrich Große, Paul Seiferth,
* Sebastian Starroske, Yannik Stein
*
* This file is part of MetaHeuristics4Java.
*
* MetaHeuristics4Java is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MetaHeuristics4Java is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MetaHeuristics4Java. If not, see <http://www.gnu.org/licenses/>.
*/
package de.mh4j.solver.genetic;
/**
*
* TODO write class description
*
*/
public abstract class Genome implements Solution<Genome>, Comparable<Genome> {
private final Random random;
public final static int NO_BIRTH_GENERATION_ASSOCIATED = -1;
private int birthGeneration;
/**
* TODO write javadoc<br>
*/
public Genome() {
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/Solution.java
// public interface Solution<SolutionImplementationType extends Solution<?>> {
//
// /**
// * Returns a numeric value that represents the costs of this solution. If
// * the optimization problem is, to maximize the costs of a solution the
// * return value indicates the absolute quality of the solution (the
// * fitness).
// **/
// int getCosts();
//
// /**
// * Compares this solution to another solution.
// *
// * @return <code>true</code> if this solution instance is better than the
// * other solution<br>
// * <code>false</code> if this solution is of worse or equal quality.
// **/
// boolean isBetterThan(SolutionImplementationType otherSolution);
//
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/util/Comparable.java
// public interface Comparable<T> extends java.lang.Comparable<T> {
//
// static final int LOWER = -1;
// static final int EQUAL = 0;
// static final int GREATER = 1;
//
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/util/RNGGenerator.java
// public abstract class RNGGenerator {
// private final static Logger log = (Logger) LoggerFactory.getLogger(RNGGenerator.class);
//
// private static Random seedGenerator;
//
// public static void setMasterSeed(long masterSeed) {
// seedGenerator = new Random(masterSeed);
// log.info("Initialized random number generator with master seed {}", masterSeed);
// }
//
// public static Random createRandomNumberGenerator() {
// if (seedGenerator == null) {
// setMasterSeed(System.currentTimeMillis());
// }
// long seed = seedGenerator.nextLong();
// return new Random(seed);
// }
//
// }
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Genome.java
import de.mh4j.solver.Solution;
import de.mh4j.util.Comparable;
import de.mh4j.util.RNGGenerator;
import java.util.Random;
/*
* Copyright 2012 Friedrich Große, Paul Seiferth,
* Sebastian Starroske, Yannik Stein
*
* This file is part of MetaHeuristics4Java.
*
* MetaHeuristics4Java is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MetaHeuristics4Java is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MetaHeuristics4Java. If not, see <http://www.gnu.org/licenses/>.
*/
package de.mh4j.solver.genetic;
/**
*
* TODO write class description
*
*/
public abstract class Genome implements Solution<Genome>, Comparable<Genome> {
private final Random random;
public final static int NO_BIRTH_GENERATION_ASSOCIATED = -1;
private int birthGeneration;
/**
* TODO write javadoc<br>
*/
public Genome() {
|
random = RNGGenerator.createRandomNumberGenerator();
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/test/java/de/mh4j/solver/genetic/matingselection/RankingSelectorTest.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Couple.java
// public class Couple {
// private final Genome parent1;
// private final Genome parent2;
//
// public Couple(Genome parent1, Genome parent2) {
// this.parent1 = parent1;
// this.parent2 = parent2;
// }
//
// public Genome getParent1() {
// return parent1;
// }
//
// public Genome getParent2() {
// return parent2;
// }
//
// @Override
// public String toString() {
// return "<" + parent1.toString() + ", " + parent2.toString() + ">";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Genome.java
// public abstract class Genome implements Solution<Genome>, Comparable<Genome> {
//
// private final Random random;
//
// public final static int NO_BIRTH_GENERATION_ASSOCIATED = -1;
//
// private int birthGeneration;
//
// /**
// * TODO write javadoc<br>
// */
// public Genome() {
// random = RNGGenerator.createRandomNumberGenerator();
// birthGeneration = NO_BIRTH_GENERATION_ASSOCIATED;
// }
//
// /**
// * Returns the general Fitness of this genome. The better a genome is the
// * higher should this value be.
// */
// public abstract int getFitness();
//
// /**
// * The costs of a genome are the opposite of its fitness. The better a
// * genome is, the higher is its fitness and the lower will the costs be.
// *
// * @return the negated return value of <code>getFitness()</code>
// * @see #getFitness()
// */
// @Override
// public int getCosts() {
// return getFitness();
// }
//
// /**
// * TODO write javadoc
// */
// public int getBirthGeneration() {
// return birthGeneration;
// }
//
// /**
// * TODO write javadoc
// */
// public void setBirthGeneration(int birthGeneration) {
// this.birthGeneration = birthGeneration;
// }
//
// /**
// * Compares this genome to another genome depending on the return values of
// * {@link #isBetterThan(Genome)} and {@link #equals(Object)}.
// *
// * @param otherGenome
// * the other genome which is compared to this genome
// * @return <code>Comparable.GREATER</code> if this genome is better<br>
// * <code>Comparable.LOWER</code> if this genome is worse<br>
// * <code>Comparable.EQUAL</code> if both genomes are equal<br>
// * or some value randomly chosen between
// * <code>Comparable.LOWER</code> and <code>Comparable.GREATER</code>
// * if <code>this.isBetterThan(otherGenome)</code> and
// * <code>otherGenome.isBetterThan(this)</code> and
// * <code>this.equals(otherGenome)</code> all return
// * <code>false</code>
// * @see Comparable
// */
// @Override
// public int compareTo(Genome otherGenome) {
//
// if (this.isBetterThan(otherGenome)) {
// return Comparable.GREATER;
// }
// else if (otherGenome.isBetterThan(this)) {
// return Comparable.LOWER;
// }
// else if (this.equals(otherGenome)) {
// return Comparable.EQUAL;
// }
// else {
// if (random.nextBoolean()) {
// return Comparable.LOWER;
// }
// else {
// return Comparable.GREATER;
// }
// }
// }
// }
|
import java.util.Collection;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import de.mh4j.solver.genetic.Couple;
import de.mh4j.solver.genetic.Genome;
|
package de.mh4j.solver.genetic.matingselection;
public class RankingSelectorTest extends MatingSelectorTestCase {
@Override
@BeforeMethod
public void setUp() {
super.setUp();
}
@Test
public void testSelect() throws Exception {
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Couple.java
// public class Couple {
// private final Genome parent1;
// private final Genome parent2;
//
// public Couple(Genome parent1, Genome parent2) {
// this.parent1 = parent1;
// this.parent2 = parent2;
// }
//
// public Genome getParent1() {
// return parent1;
// }
//
// public Genome getParent2() {
// return parent2;
// }
//
// @Override
// public String toString() {
// return "<" + parent1.toString() + ", " + parent2.toString() + ">";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Genome.java
// public abstract class Genome implements Solution<Genome>, Comparable<Genome> {
//
// private final Random random;
//
// public final static int NO_BIRTH_GENERATION_ASSOCIATED = -1;
//
// private int birthGeneration;
//
// /**
// * TODO write javadoc<br>
// */
// public Genome() {
// random = RNGGenerator.createRandomNumberGenerator();
// birthGeneration = NO_BIRTH_GENERATION_ASSOCIATED;
// }
//
// /**
// * Returns the general Fitness of this genome. The better a genome is the
// * higher should this value be.
// */
// public abstract int getFitness();
//
// /**
// * The costs of a genome are the opposite of its fitness. The better a
// * genome is, the higher is its fitness and the lower will the costs be.
// *
// * @return the negated return value of <code>getFitness()</code>
// * @see #getFitness()
// */
// @Override
// public int getCosts() {
// return getFitness();
// }
//
// /**
// * TODO write javadoc
// */
// public int getBirthGeneration() {
// return birthGeneration;
// }
//
// /**
// * TODO write javadoc
// */
// public void setBirthGeneration(int birthGeneration) {
// this.birthGeneration = birthGeneration;
// }
//
// /**
// * Compares this genome to another genome depending on the return values of
// * {@link #isBetterThan(Genome)} and {@link #equals(Object)}.
// *
// * @param otherGenome
// * the other genome which is compared to this genome
// * @return <code>Comparable.GREATER</code> if this genome is better<br>
// * <code>Comparable.LOWER</code> if this genome is worse<br>
// * <code>Comparable.EQUAL</code> if both genomes are equal<br>
// * or some value randomly chosen between
// * <code>Comparable.LOWER</code> and <code>Comparable.GREATER</code>
// * if <code>this.isBetterThan(otherGenome)</code> and
// * <code>otherGenome.isBetterThan(this)</code> and
// * <code>this.equals(otherGenome)</code> all return
// * <code>false</code>
// * @see Comparable
// */
// @Override
// public int compareTo(Genome otherGenome) {
//
// if (this.isBetterThan(otherGenome)) {
// return Comparable.GREATER;
// }
// else if (otherGenome.isBetterThan(this)) {
// return Comparable.LOWER;
// }
// else if (this.equals(otherGenome)) {
// return Comparable.EQUAL;
// }
// else {
// if (random.nextBoolean()) {
// return Comparable.LOWER;
// }
// else {
// return Comparable.GREATER;
// }
// }
// }
// }
// Path: MetaHeuristics4Java/src/test/java/de/mh4j/solver/genetic/matingselection/RankingSelectorTest.java
import java.util.Collection;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import de.mh4j.solver.genetic.Couple;
import de.mh4j.solver.genetic.Genome;
package de.mh4j.solver.genetic.matingselection;
public class RankingSelectorTest extends MatingSelectorTestCase {
@Override
@BeforeMethod
public void setUp() {
super.setUp();
}
@Test
public void testSelect() throws Exception {
|
RankingSelector<Genome> selector = new RankingSelector<>();
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/test/java/de/mh4j/solver/genetic/matingselection/RankingSelectorTest.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Couple.java
// public class Couple {
// private final Genome parent1;
// private final Genome parent2;
//
// public Couple(Genome parent1, Genome parent2) {
// this.parent1 = parent1;
// this.parent2 = parent2;
// }
//
// public Genome getParent1() {
// return parent1;
// }
//
// public Genome getParent2() {
// return parent2;
// }
//
// @Override
// public String toString() {
// return "<" + parent1.toString() + ", " + parent2.toString() + ">";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Genome.java
// public abstract class Genome implements Solution<Genome>, Comparable<Genome> {
//
// private final Random random;
//
// public final static int NO_BIRTH_GENERATION_ASSOCIATED = -1;
//
// private int birthGeneration;
//
// /**
// * TODO write javadoc<br>
// */
// public Genome() {
// random = RNGGenerator.createRandomNumberGenerator();
// birthGeneration = NO_BIRTH_GENERATION_ASSOCIATED;
// }
//
// /**
// * Returns the general Fitness of this genome. The better a genome is the
// * higher should this value be.
// */
// public abstract int getFitness();
//
// /**
// * The costs of a genome are the opposite of its fitness. The better a
// * genome is, the higher is its fitness and the lower will the costs be.
// *
// * @return the negated return value of <code>getFitness()</code>
// * @see #getFitness()
// */
// @Override
// public int getCosts() {
// return getFitness();
// }
//
// /**
// * TODO write javadoc
// */
// public int getBirthGeneration() {
// return birthGeneration;
// }
//
// /**
// * TODO write javadoc
// */
// public void setBirthGeneration(int birthGeneration) {
// this.birthGeneration = birthGeneration;
// }
//
// /**
// * Compares this genome to another genome depending on the return values of
// * {@link #isBetterThan(Genome)} and {@link #equals(Object)}.
// *
// * @param otherGenome
// * the other genome which is compared to this genome
// * @return <code>Comparable.GREATER</code> if this genome is better<br>
// * <code>Comparable.LOWER</code> if this genome is worse<br>
// * <code>Comparable.EQUAL</code> if both genomes are equal<br>
// * or some value randomly chosen between
// * <code>Comparable.LOWER</code> and <code>Comparable.GREATER</code>
// * if <code>this.isBetterThan(otherGenome)</code> and
// * <code>otherGenome.isBetterThan(this)</code> and
// * <code>this.equals(otherGenome)</code> all return
// * <code>false</code>
// * @see Comparable
// */
// @Override
// public int compareTo(Genome otherGenome) {
//
// if (this.isBetterThan(otherGenome)) {
// return Comparable.GREATER;
// }
// else if (otherGenome.isBetterThan(this)) {
// return Comparable.LOWER;
// }
// else if (this.equals(otherGenome)) {
// return Comparable.EQUAL;
// }
// else {
// if (random.nextBoolean()) {
// return Comparable.LOWER;
// }
// else {
// return Comparable.GREATER;
// }
// }
// }
// }
|
import java.util.Collection;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import de.mh4j.solver.genetic.Couple;
import de.mh4j.solver.genetic.Genome;
|
package de.mh4j.solver.genetic.matingselection;
public class RankingSelectorTest extends MatingSelectorTestCase {
@Override
@BeforeMethod
public void setUp() {
super.setUp();
}
@Test
public void testSelect() throws Exception {
RankingSelector<Genome> selector = new RankingSelector<>();
int numberOfPairs = 4;
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Couple.java
// public class Couple {
// private final Genome parent1;
// private final Genome parent2;
//
// public Couple(Genome parent1, Genome parent2) {
// this.parent1 = parent1;
// this.parent2 = parent2;
// }
//
// public Genome getParent1() {
// return parent1;
// }
//
// public Genome getParent2() {
// return parent2;
// }
//
// @Override
// public String toString() {
// return "<" + parent1.toString() + ", " + parent2.toString() + ">";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Genome.java
// public abstract class Genome implements Solution<Genome>, Comparable<Genome> {
//
// private final Random random;
//
// public final static int NO_BIRTH_GENERATION_ASSOCIATED = -1;
//
// private int birthGeneration;
//
// /**
// * TODO write javadoc<br>
// */
// public Genome() {
// random = RNGGenerator.createRandomNumberGenerator();
// birthGeneration = NO_BIRTH_GENERATION_ASSOCIATED;
// }
//
// /**
// * Returns the general Fitness of this genome. The better a genome is the
// * higher should this value be.
// */
// public abstract int getFitness();
//
// /**
// * The costs of a genome are the opposite of its fitness. The better a
// * genome is, the higher is its fitness and the lower will the costs be.
// *
// * @return the negated return value of <code>getFitness()</code>
// * @see #getFitness()
// */
// @Override
// public int getCosts() {
// return getFitness();
// }
//
// /**
// * TODO write javadoc
// */
// public int getBirthGeneration() {
// return birthGeneration;
// }
//
// /**
// * TODO write javadoc
// */
// public void setBirthGeneration(int birthGeneration) {
// this.birthGeneration = birthGeneration;
// }
//
// /**
// * Compares this genome to another genome depending on the return values of
// * {@link #isBetterThan(Genome)} and {@link #equals(Object)}.
// *
// * @param otherGenome
// * the other genome which is compared to this genome
// * @return <code>Comparable.GREATER</code> if this genome is better<br>
// * <code>Comparable.LOWER</code> if this genome is worse<br>
// * <code>Comparable.EQUAL</code> if both genomes are equal<br>
// * or some value randomly chosen between
// * <code>Comparable.LOWER</code> and <code>Comparable.GREATER</code>
// * if <code>this.isBetterThan(otherGenome)</code> and
// * <code>otherGenome.isBetterThan(this)</code> and
// * <code>this.equals(otherGenome)</code> all return
// * <code>false</code>
// * @see Comparable
// */
// @Override
// public int compareTo(Genome otherGenome) {
//
// if (this.isBetterThan(otherGenome)) {
// return Comparable.GREATER;
// }
// else if (otherGenome.isBetterThan(this)) {
// return Comparable.LOWER;
// }
// else if (this.equals(otherGenome)) {
// return Comparable.EQUAL;
// }
// else {
// if (random.nextBoolean()) {
// return Comparable.LOWER;
// }
// else {
// return Comparable.GREATER;
// }
// }
// }
// }
// Path: MetaHeuristics4Java/src/test/java/de/mh4j/solver/genetic/matingselection/RankingSelectorTest.java
import java.util.Collection;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import de.mh4j.solver.genetic.Couple;
import de.mh4j.solver.genetic.Genome;
package de.mh4j.solver.genetic.matingselection;
public class RankingSelectorTest extends MatingSelectorTestCase {
@Override
@BeforeMethod
public void setUp() {
super.setUp();
}
@Test
public void testSelect() throws Exception {
RankingSelector<Genome> selector = new RankingSelector<>();
int numberOfPairs = 4;
|
Collection<Couple> parents = selector.select(numberOfPairs, genePool);
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/test/java/de/mh4j/solver/genetic/GenomeTest.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/util/Comparable.java
// public interface Comparable<T> extends java.lang.Comparable<T> {
//
// static final int LOWER = -1;
// static final int EQUAL = 0;
// static final int GREATER = 1;
//
// }
|
import org.testng.annotations.Test;
import de.mh4j.util.Comparable;
|
package de.mh4j.solver.genetic;
public class GenomeTest {
@Test
public void testGetBirthGeneration_WhenInitialized_BirthGenerationIsUnset() throws Exception {
Genome genome = new GenomeMock();
assert genome.getBirthGeneration() == Genome.NO_BIRTH_GENERATION_ASSOCIATED;
}
@Test
public void testSetBirthGeneration() throws Exception {
final int birthGeneration = 42;
Genome genome = new GenomeMock();
genome.setBirthGeneration(birthGeneration);
assert genome.getBirthGeneration() == birthGeneration;
}
@Test
public void testCompareGenomes() {
Genome badGenome = new GenomeMock(20);
Genome goodGenome = new GenomeMock(40);
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/util/Comparable.java
// public interface Comparable<T> extends java.lang.Comparable<T> {
//
// static final int LOWER = -1;
// static final int EQUAL = 0;
// static final int GREATER = 1;
//
// }
// Path: MetaHeuristics4Java/src/test/java/de/mh4j/solver/genetic/GenomeTest.java
import org.testng.annotations.Test;
import de.mh4j.util.Comparable;
package de.mh4j.solver.genetic;
public class GenomeTest {
@Test
public void testGetBirthGeneration_WhenInitialized_BirthGenerationIsUnset() throws Exception {
Genome genome = new GenomeMock();
assert genome.getBirthGeneration() == Genome.NO_BIRTH_GENERATION_ASSOCIATED;
}
@Test
public void testSetBirthGeneration() throws Exception {
final int birthGeneration = 42;
Genome genome = new GenomeMock();
genome.setBirthGeneration(birthGeneration);
assert genome.getBirthGeneration() == birthGeneration;
}
@Test
public void testCompareGenomes() {
Genome badGenome = new GenomeMock(20);
Genome goodGenome = new GenomeMock(40);
|
assert badGenome.compareTo(goodGenome) == Comparable.LOWER : "Bad genome should be worse than better genome";
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/test/java/de/mh4j/solver/genetic/matingselection/TournamentSelectorTest.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Couple.java
// public class Couple {
// private final Genome parent1;
// private final Genome parent2;
//
// public Couple(Genome parent1, Genome parent2) {
// this.parent1 = parent1;
// this.parent2 = parent2;
// }
//
// public Genome getParent1() {
// return parent1;
// }
//
// public Genome getParent2() {
// return parent2;
// }
//
// @Override
// public String toString() {
// return "<" + parent1.toString() + ", " + parent2.toString() + ">";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Genome.java
// public abstract class Genome implements Solution<Genome>, Comparable<Genome> {
//
// private final Random random;
//
// public final static int NO_BIRTH_GENERATION_ASSOCIATED = -1;
//
// private int birthGeneration;
//
// /**
// * TODO write javadoc<br>
// */
// public Genome() {
// random = RNGGenerator.createRandomNumberGenerator();
// birthGeneration = NO_BIRTH_GENERATION_ASSOCIATED;
// }
//
// /**
// * Returns the general Fitness of this genome. The better a genome is the
// * higher should this value be.
// */
// public abstract int getFitness();
//
// /**
// * The costs of a genome are the opposite of its fitness. The better a
// * genome is, the higher is its fitness and the lower will the costs be.
// *
// * @return the negated return value of <code>getFitness()</code>
// * @see #getFitness()
// */
// @Override
// public int getCosts() {
// return getFitness();
// }
//
// /**
// * TODO write javadoc
// */
// public int getBirthGeneration() {
// return birthGeneration;
// }
//
// /**
// * TODO write javadoc
// */
// public void setBirthGeneration(int birthGeneration) {
// this.birthGeneration = birthGeneration;
// }
//
// /**
// * Compares this genome to another genome depending on the return values of
// * {@link #isBetterThan(Genome)} and {@link #equals(Object)}.
// *
// * @param otherGenome
// * the other genome which is compared to this genome
// * @return <code>Comparable.GREATER</code> if this genome is better<br>
// * <code>Comparable.LOWER</code> if this genome is worse<br>
// * <code>Comparable.EQUAL</code> if both genomes are equal<br>
// * or some value randomly chosen between
// * <code>Comparable.LOWER</code> and <code>Comparable.GREATER</code>
// * if <code>this.isBetterThan(otherGenome)</code> and
// * <code>otherGenome.isBetterThan(this)</code> and
// * <code>this.equals(otherGenome)</code> all return
// * <code>false</code>
// * @see Comparable
// */
// @Override
// public int compareTo(Genome otherGenome) {
//
// if (this.isBetterThan(otherGenome)) {
// return Comparable.GREATER;
// }
// else if (otherGenome.isBetterThan(this)) {
// return Comparable.LOWER;
// }
// else if (this.equals(otherGenome)) {
// return Comparable.EQUAL;
// }
// else {
// if (random.nextBoolean()) {
// return Comparable.LOWER;
// }
// else {
// return Comparable.GREATER;
// }
// }
// }
// }
|
import java.util.Collection;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import de.mh4j.solver.genetic.Couple;
import de.mh4j.solver.genetic.Genome;
|
package de.mh4j.solver.genetic.matingselection;
public class TournamentSelectorTest extends MatingSelectorTestCase {
@Override
@BeforeMethod
public void setUp() {
super.setUp();
}
@Test
public void testSelect() throws Exception {
int numberOfPairs = 4;
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Couple.java
// public class Couple {
// private final Genome parent1;
// private final Genome parent2;
//
// public Couple(Genome parent1, Genome parent2) {
// this.parent1 = parent1;
// this.parent2 = parent2;
// }
//
// public Genome getParent1() {
// return parent1;
// }
//
// public Genome getParent2() {
// return parent2;
// }
//
// @Override
// public String toString() {
// return "<" + parent1.toString() + ", " + parent2.toString() + ">";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Genome.java
// public abstract class Genome implements Solution<Genome>, Comparable<Genome> {
//
// private final Random random;
//
// public final static int NO_BIRTH_GENERATION_ASSOCIATED = -1;
//
// private int birthGeneration;
//
// /**
// * TODO write javadoc<br>
// */
// public Genome() {
// random = RNGGenerator.createRandomNumberGenerator();
// birthGeneration = NO_BIRTH_GENERATION_ASSOCIATED;
// }
//
// /**
// * Returns the general Fitness of this genome. The better a genome is the
// * higher should this value be.
// */
// public abstract int getFitness();
//
// /**
// * The costs of a genome are the opposite of its fitness. The better a
// * genome is, the higher is its fitness and the lower will the costs be.
// *
// * @return the negated return value of <code>getFitness()</code>
// * @see #getFitness()
// */
// @Override
// public int getCosts() {
// return getFitness();
// }
//
// /**
// * TODO write javadoc
// */
// public int getBirthGeneration() {
// return birthGeneration;
// }
//
// /**
// * TODO write javadoc
// */
// public void setBirthGeneration(int birthGeneration) {
// this.birthGeneration = birthGeneration;
// }
//
// /**
// * Compares this genome to another genome depending on the return values of
// * {@link #isBetterThan(Genome)} and {@link #equals(Object)}.
// *
// * @param otherGenome
// * the other genome which is compared to this genome
// * @return <code>Comparable.GREATER</code> if this genome is better<br>
// * <code>Comparable.LOWER</code> if this genome is worse<br>
// * <code>Comparable.EQUAL</code> if both genomes are equal<br>
// * or some value randomly chosen between
// * <code>Comparable.LOWER</code> and <code>Comparable.GREATER</code>
// * if <code>this.isBetterThan(otherGenome)</code> and
// * <code>otherGenome.isBetterThan(this)</code> and
// * <code>this.equals(otherGenome)</code> all return
// * <code>false</code>
// * @see Comparable
// */
// @Override
// public int compareTo(Genome otherGenome) {
//
// if (this.isBetterThan(otherGenome)) {
// return Comparable.GREATER;
// }
// else if (otherGenome.isBetterThan(this)) {
// return Comparable.LOWER;
// }
// else if (this.equals(otherGenome)) {
// return Comparable.EQUAL;
// }
// else {
// if (random.nextBoolean()) {
// return Comparable.LOWER;
// }
// else {
// return Comparable.GREATER;
// }
// }
// }
// }
// Path: MetaHeuristics4Java/src/test/java/de/mh4j/solver/genetic/matingselection/TournamentSelectorTest.java
import java.util.Collection;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import de.mh4j.solver.genetic.Couple;
import de.mh4j.solver.genetic.Genome;
package de.mh4j.solver.genetic.matingselection;
public class TournamentSelectorTest extends MatingSelectorTestCase {
@Override
@BeforeMethod
public void setUp() {
super.setUp();
}
@Test
public void testSelect() throws Exception {
int numberOfPairs = 4;
|
MatingSelector<Genome> selector = new TournamentMatingSelector<>();
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/test/java/de/mh4j/solver/genetic/matingselection/TournamentSelectorTest.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Couple.java
// public class Couple {
// private final Genome parent1;
// private final Genome parent2;
//
// public Couple(Genome parent1, Genome parent2) {
// this.parent1 = parent1;
// this.parent2 = parent2;
// }
//
// public Genome getParent1() {
// return parent1;
// }
//
// public Genome getParent2() {
// return parent2;
// }
//
// @Override
// public String toString() {
// return "<" + parent1.toString() + ", " + parent2.toString() + ">";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Genome.java
// public abstract class Genome implements Solution<Genome>, Comparable<Genome> {
//
// private final Random random;
//
// public final static int NO_BIRTH_GENERATION_ASSOCIATED = -1;
//
// private int birthGeneration;
//
// /**
// * TODO write javadoc<br>
// */
// public Genome() {
// random = RNGGenerator.createRandomNumberGenerator();
// birthGeneration = NO_BIRTH_GENERATION_ASSOCIATED;
// }
//
// /**
// * Returns the general Fitness of this genome. The better a genome is the
// * higher should this value be.
// */
// public abstract int getFitness();
//
// /**
// * The costs of a genome are the opposite of its fitness. The better a
// * genome is, the higher is its fitness and the lower will the costs be.
// *
// * @return the negated return value of <code>getFitness()</code>
// * @see #getFitness()
// */
// @Override
// public int getCosts() {
// return getFitness();
// }
//
// /**
// * TODO write javadoc
// */
// public int getBirthGeneration() {
// return birthGeneration;
// }
//
// /**
// * TODO write javadoc
// */
// public void setBirthGeneration(int birthGeneration) {
// this.birthGeneration = birthGeneration;
// }
//
// /**
// * Compares this genome to another genome depending on the return values of
// * {@link #isBetterThan(Genome)} and {@link #equals(Object)}.
// *
// * @param otherGenome
// * the other genome which is compared to this genome
// * @return <code>Comparable.GREATER</code> if this genome is better<br>
// * <code>Comparable.LOWER</code> if this genome is worse<br>
// * <code>Comparable.EQUAL</code> if both genomes are equal<br>
// * or some value randomly chosen between
// * <code>Comparable.LOWER</code> and <code>Comparable.GREATER</code>
// * if <code>this.isBetterThan(otherGenome)</code> and
// * <code>otherGenome.isBetterThan(this)</code> and
// * <code>this.equals(otherGenome)</code> all return
// * <code>false</code>
// * @see Comparable
// */
// @Override
// public int compareTo(Genome otherGenome) {
//
// if (this.isBetterThan(otherGenome)) {
// return Comparable.GREATER;
// }
// else if (otherGenome.isBetterThan(this)) {
// return Comparable.LOWER;
// }
// else if (this.equals(otherGenome)) {
// return Comparable.EQUAL;
// }
// else {
// if (random.nextBoolean()) {
// return Comparable.LOWER;
// }
// else {
// return Comparable.GREATER;
// }
// }
// }
// }
|
import java.util.Collection;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import de.mh4j.solver.genetic.Couple;
import de.mh4j.solver.genetic.Genome;
|
package de.mh4j.solver.genetic.matingselection;
public class TournamentSelectorTest extends MatingSelectorTestCase {
@Override
@BeforeMethod
public void setUp() {
super.setUp();
}
@Test
public void testSelect() throws Exception {
int numberOfPairs = 4;
MatingSelector<Genome> selector = new TournamentMatingSelector<>();
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Couple.java
// public class Couple {
// private final Genome parent1;
// private final Genome parent2;
//
// public Couple(Genome parent1, Genome parent2) {
// this.parent1 = parent1;
// this.parent2 = parent2;
// }
//
// public Genome getParent1() {
// return parent1;
// }
//
// public Genome getParent2() {
// return parent2;
// }
//
// @Override
// public String toString() {
// return "<" + parent1.toString() + ", " + parent2.toString() + ">";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Genome.java
// public abstract class Genome implements Solution<Genome>, Comparable<Genome> {
//
// private final Random random;
//
// public final static int NO_BIRTH_GENERATION_ASSOCIATED = -1;
//
// private int birthGeneration;
//
// /**
// * TODO write javadoc<br>
// */
// public Genome() {
// random = RNGGenerator.createRandomNumberGenerator();
// birthGeneration = NO_BIRTH_GENERATION_ASSOCIATED;
// }
//
// /**
// * Returns the general Fitness of this genome. The better a genome is the
// * higher should this value be.
// */
// public abstract int getFitness();
//
// /**
// * The costs of a genome are the opposite of its fitness. The better a
// * genome is, the higher is its fitness and the lower will the costs be.
// *
// * @return the negated return value of <code>getFitness()</code>
// * @see #getFitness()
// */
// @Override
// public int getCosts() {
// return getFitness();
// }
//
// /**
// * TODO write javadoc
// */
// public int getBirthGeneration() {
// return birthGeneration;
// }
//
// /**
// * TODO write javadoc
// */
// public void setBirthGeneration(int birthGeneration) {
// this.birthGeneration = birthGeneration;
// }
//
// /**
// * Compares this genome to another genome depending on the return values of
// * {@link #isBetterThan(Genome)} and {@link #equals(Object)}.
// *
// * @param otherGenome
// * the other genome which is compared to this genome
// * @return <code>Comparable.GREATER</code> if this genome is better<br>
// * <code>Comparable.LOWER</code> if this genome is worse<br>
// * <code>Comparable.EQUAL</code> if both genomes are equal<br>
// * or some value randomly chosen between
// * <code>Comparable.LOWER</code> and <code>Comparable.GREATER</code>
// * if <code>this.isBetterThan(otherGenome)</code> and
// * <code>otherGenome.isBetterThan(this)</code> and
// * <code>this.equals(otherGenome)</code> all return
// * <code>false</code>
// * @see Comparable
// */
// @Override
// public int compareTo(Genome otherGenome) {
//
// if (this.isBetterThan(otherGenome)) {
// return Comparable.GREATER;
// }
// else if (otherGenome.isBetterThan(this)) {
// return Comparable.LOWER;
// }
// else if (this.equals(otherGenome)) {
// return Comparable.EQUAL;
// }
// else {
// if (random.nextBoolean()) {
// return Comparable.LOWER;
// }
// else {
// return Comparable.GREATER;
// }
// }
// }
// }
// Path: MetaHeuristics4Java/src/test/java/de/mh4j/solver/genetic/matingselection/TournamentSelectorTest.java
import java.util.Collection;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import de.mh4j.solver.genetic.Couple;
import de.mh4j.solver.genetic.Genome;
package de.mh4j.solver.genetic.matingselection;
public class TournamentSelectorTest extends MatingSelectorTestCase {
@Override
@BeforeMethod
public void setUp() {
super.setUp();
}
@Test
public void testSelect() throws Exception {
int numberOfPairs = 4;
MatingSelector<Genome> selector = new TournamentMatingSelector<>();
|
Collection<Couple> parents = selector.select(numberOfPairs, genePool);
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java-Examples/src/test/java/de/mh4j/examples/maxknapsack/solver/SimulatedAnnealingKnapsackSolverTest.java
|
// Path: MetaHeuristics4Java-Examples/src/main/java/de/mh4j/examples/maxknapsack/model/Item.java
// public class Item {
//
// public final String name;
// public final int price;
// public final int volume;
//
// public Item(String name, int price, int volume) {
// this.name = name;
// this.price = price;
// this.volume = volume;
// }
//
// @Override
// public boolean equals(Object otherObject) {
// if (otherObject instanceof Item == false) {
// return false;
// }
// Item otherItem = (Item) otherObject;
// return otherItem.name == this.name && otherItem.price == this.price && otherItem.volume == this.volume;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: MetaHeuristics4Java-Examples/src/main/java/de/mh4j/examples/maxknapsack/model/Knapsack.java
// public class Knapsack implements Solution<Knapsack> {
//
// private final int totalCapacity;
// private final List<Item> items;
//
// private int remainingCapacity;
// private int costs;
//
// public Knapsack(int capacity) {
// totalCapacity = capacity;
// remainingCapacity = totalCapacity;
// items = new ArrayList<>();
// costs = 0;
// }
//
// public Knapsack(Knapsack original) {
// this.totalCapacity = original.totalCapacity;
// this.items = new ArrayList<>(original.items);
// this.remainingCapacity = original.remainingCapacity;
// this.costs = original.costs;
// }
//
// @Override
// public int getCosts() {
// return costs;
// }
//
// public int getCapacity() {
// return totalCapacity;
// }
//
// @Override
// public boolean isBetterThan(Knapsack otherSolution) {
// return otherSolution.getCosts() < costs;
// }
//
// public boolean addItem(Item item) {
// int newRemainingCapacity = remainingCapacity - item.volume;
//
// if (newRemainingCapacity >= 0) {
// items.add(item);
// remainingCapacity = newRemainingCapacity;
// costs += item.price;
// }
//
// return newRemainingCapacity >= 0;
// }
//
// public int getNumberOfItems() {
// return items.size();
// }
//
// public int getRemainingCapacity() {
// return remainingCapacity;
// }
//
// public Item removeItem(int index) {
// Item removedItem = items.remove(index);
// costs -= removedItem.price;
// remainingCapacity += removedItem.volume;
// return removedItem;
// }
//
// public boolean isFull() {
// return remainingCapacity == 0;
// }
//
// @Override
// public boolean equals(Object otherObject) {
// if (otherObject instanceof Knapsack == false) {
// return false;
// }
//
// Knapsack otherKnapsack = (Knapsack) otherObject;
//
// if (otherKnapsack.items.size() != this.items.size()) {
// return false;
// }
//
// for (Item item : items) {
// if (otherKnapsack.items.contains(item) == false) {
// return false;
// }
// }
//
//
// return this.totalCapacity == otherKnapsack.totalCapacity;
// }
//
// @Override
// public String toString() {
// return (totalCapacity - remainingCapacity) + "/" + totalCapacity + ": " + items + " " + costs;
// }
// }
|
import static org.testng.AssertJUnit.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.testng.annotations.Test;
import ch.qos.logback.classic.Level;
import de.mh4j.examples.maxknapsack.model.Item;
import de.mh4j.examples.maxknapsack.model.Knapsack;
|
package de.mh4j.examples.maxknapsack.solver;
public class SimulatedAnnealingKnapsackSolverTest {
@Test
public void testSolveSimpleInstance() {
int knapsackCapacity = 59;
|
// Path: MetaHeuristics4Java-Examples/src/main/java/de/mh4j/examples/maxknapsack/model/Item.java
// public class Item {
//
// public final String name;
// public final int price;
// public final int volume;
//
// public Item(String name, int price, int volume) {
// this.name = name;
// this.price = price;
// this.volume = volume;
// }
//
// @Override
// public boolean equals(Object otherObject) {
// if (otherObject instanceof Item == false) {
// return false;
// }
// Item otherItem = (Item) otherObject;
// return otherItem.name == this.name && otherItem.price == this.price && otherItem.volume == this.volume;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: MetaHeuristics4Java-Examples/src/main/java/de/mh4j/examples/maxknapsack/model/Knapsack.java
// public class Knapsack implements Solution<Knapsack> {
//
// private final int totalCapacity;
// private final List<Item> items;
//
// private int remainingCapacity;
// private int costs;
//
// public Knapsack(int capacity) {
// totalCapacity = capacity;
// remainingCapacity = totalCapacity;
// items = new ArrayList<>();
// costs = 0;
// }
//
// public Knapsack(Knapsack original) {
// this.totalCapacity = original.totalCapacity;
// this.items = new ArrayList<>(original.items);
// this.remainingCapacity = original.remainingCapacity;
// this.costs = original.costs;
// }
//
// @Override
// public int getCosts() {
// return costs;
// }
//
// public int getCapacity() {
// return totalCapacity;
// }
//
// @Override
// public boolean isBetterThan(Knapsack otherSolution) {
// return otherSolution.getCosts() < costs;
// }
//
// public boolean addItem(Item item) {
// int newRemainingCapacity = remainingCapacity - item.volume;
//
// if (newRemainingCapacity >= 0) {
// items.add(item);
// remainingCapacity = newRemainingCapacity;
// costs += item.price;
// }
//
// return newRemainingCapacity >= 0;
// }
//
// public int getNumberOfItems() {
// return items.size();
// }
//
// public int getRemainingCapacity() {
// return remainingCapacity;
// }
//
// public Item removeItem(int index) {
// Item removedItem = items.remove(index);
// costs -= removedItem.price;
// remainingCapacity += removedItem.volume;
// return removedItem;
// }
//
// public boolean isFull() {
// return remainingCapacity == 0;
// }
//
// @Override
// public boolean equals(Object otherObject) {
// if (otherObject instanceof Knapsack == false) {
// return false;
// }
//
// Knapsack otherKnapsack = (Knapsack) otherObject;
//
// if (otherKnapsack.items.size() != this.items.size()) {
// return false;
// }
//
// for (Item item : items) {
// if (otherKnapsack.items.contains(item) == false) {
// return false;
// }
// }
//
//
// return this.totalCapacity == otherKnapsack.totalCapacity;
// }
//
// @Override
// public String toString() {
// return (totalCapacity - remainingCapacity) + "/" + totalCapacity + ": " + items + " " + costs;
// }
// }
// Path: MetaHeuristics4Java-Examples/src/test/java/de/mh4j/examples/maxknapsack/solver/SimulatedAnnealingKnapsackSolverTest.java
import static org.testng.AssertJUnit.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.testng.annotations.Test;
import ch.qos.logback.classic.Level;
import de.mh4j.examples.maxknapsack.model.Item;
import de.mh4j.examples.maxknapsack.model.Knapsack;
package de.mh4j.examples.maxknapsack.solver;
public class SimulatedAnnealingKnapsackSolverTest {
@Test
public void testSolveSimpleInstance() {
int knapsackCapacity = 59;
|
List<Item> items = new ArrayList<>(Arrays.asList(new Item("Foo", 100,
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java-Examples/src/test/java/de/mh4j/examples/maxknapsack/solver/SimulatedAnnealingKnapsackSolverTest.java
|
// Path: MetaHeuristics4Java-Examples/src/main/java/de/mh4j/examples/maxknapsack/model/Item.java
// public class Item {
//
// public final String name;
// public final int price;
// public final int volume;
//
// public Item(String name, int price, int volume) {
// this.name = name;
// this.price = price;
// this.volume = volume;
// }
//
// @Override
// public boolean equals(Object otherObject) {
// if (otherObject instanceof Item == false) {
// return false;
// }
// Item otherItem = (Item) otherObject;
// return otherItem.name == this.name && otherItem.price == this.price && otherItem.volume == this.volume;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: MetaHeuristics4Java-Examples/src/main/java/de/mh4j/examples/maxknapsack/model/Knapsack.java
// public class Knapsack implements Solution<Knapsack> {
//
// private final int totalCapacity;
// private final List<Item> items;
//
// private int remainingCapacity;
// private int costs;
//
// public Knapsack(int capacity) {
// totalCapacity = capacity;
// remainingCapacity = totalCapacity;
// items = new ArrayList<>();
// costs = 0;
// }
//
// public Knapsack(Knapsack original) {
// this.totalCapacity = original.totalCapacity;
// this.items = new ArrayList<>(original.items);
// this.remainingCapacity = original.remainingCapacity;
// this.costs = original.costs;
// }
//
// @Override
// public int getCosts() {
// return costs;
// }
//
// public int getCapacity() {
// return totalCapacity;
// }
//
// @Override
// public boolean isBetterThan(Knapsack otherSolution) {
// return otherSolution.getCosts() < costs;
// }
//
// public boolean addItem(Item item) {
// int newRemainingCapacity = remainingCapacity - item.volume;
//
// if (newRemainingCapacity >= 0) {
// items.add(item);
// remainingCapacity = newRemainingCapacity;
// costs += item.price;
// }
//
// return newRemainingCapacity >= 0;
// }
//
// public int getNumberOfItems() {
// return items.size();
// }
//
// public int getRemainingCapacity() {
// return remainingCapacity;
// }
//
// public Item removeItem(int index) {
// Item removedItem = items.remove(index);
// costs -= removedItem.price;
// remainingCapacity += removedItem.volume;
// return removedItem;
// }
//
// public boolean isFull() {
// return remainingCapacity == 0;
// }
//
// @Override
// public boolean equals(Object otherObject) {
// if (otherObject instanceof Knapsack == false) {
// return false;
// }
//
// Knapsack otherKnapsack = (Knapsack) otherObject;
//
// if (otherKnapsack.items.size() != this.items.size()) {
// return false;
// }
//
// for (Item item : items) {
// if (otherKnapsack.items.contains(item) == false) {
// return false;
// }
// }
//
//
// return this.totalCapacity == otherKnapsack.totalCapacity;
// }
//
// @Override
// public String toString() {
// return (totalCapacity - remainingCapacity) + "/" + totalCapacity + ": " + items + " " + costs;
// }
// }
|
import static org.testng.AssertJUnit.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.testng.annotations.Test;
import ch.qos.logback.classic.Level;
import de.mh4j.examples.maxknapsack.model.Item;
import de.mh4j.examples.maxknapsack.model.Knapsack;
|
package de.mh4j.examples.maxknapsack.solver;
public class SimulatedAnnealingKnapsackSolverTest {
@Test
public void testSolveSimpleInstance() {
int knapsackCapacity = 59;
List<Item> items = new ArrayList<>(Arrays.asList(new Item("Foo", 100,
40), new Item("Bar", 80, 30), new Item("Muh", 5, 5), new Item(
"Awe", 30, 10)));
SimulatedAnnealingKnapsackSolver solver = new SimulatedAnnealingKnapsackSolver(
knapsackCapacity, items);
solver.run();
}
@Test
public void testBuggyConfiguration() {
int knapsackCapacity = 59;
List<Item> items = new ArrayList<>(Arrays.asList(new Item("Foo", 100,
40), new Item("Bar", 80, 30), new Item("Muh", 5, 5), new Item(
"Awe", 30, 10)));
SimulatedAnnealingKnapsackSolver solver = new SimulatedAnnealingKnapsackSolver(
knapsackCapacity, items);
|
// Path: MetaHeuristics4Java-Examples/src/main/java/de/mh4j/examples/maxknapsack/model/Item.java
// public class Item {
//
// public final String name;
// public final int price;
// public final int volume;
//
// public Item(String name, int price, int volume) {
// this.name = name;
// this.price = price;
// this.volume = volume;
// }
//
// @Override
// public boolean equals(Object otherObject) {
// if (otherObject instanceof Item == false) {
// return false;
// }
// Item otherItem = (Item) otherObject;
// return otherItem.name == this.name && otherItem.price == this.price && otherItem.volume == this.volume;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: MetaHeuristics4Java-Examples/src/main/java/de/mh4j/examples/maxknapsack/model/Knapsack.java
// public class Knapsack implements Solution<Knapsack> {
//
// private final int totalCapacity;
// private final List<Item> items;
//
// private int remainingCapacity;
// private int costs;
//
// public Knapsack(int capacity) {
// totalCapacity = capacity;
// remainingCapacity = totalCapacity;
// items = new ArrayList<>();
// costs = 0;
// }
//
// public Knapsack(Knapsack original) {
// this.totalCapacity = original.totalCapacity;
// this.items = new ArrayList<>(original.items);
// this.remainingCapacity = original.remainingCapacity;
// this.costs = original.costs;
// }
//
// @Override
// public int getCosts() {
// return costs;
// }
//
// public int getCapacity() {
// return totalCapacity;
// }
//
// @Override
// public boolean isBetterThan(Knapsack otherSolution) {
// return otherSolution.getCosts() < costs;
// }
//
// public boolean addItem(Item item) {
// int newRemainingCapacity = remainingCapacity - item.volume;
//
// if (newRemainingCapacity >= 0) {
// items.add(item);
// remainingCapacity = newRemainingCapacity;
// costs += item.price;
// }
//
// return newRemainingCapacity >= 0;
// }
//
// public int getNumberOfItems() {
// return items.size();
// }
//
// public int getRemainingCapacity() {
// return remainingCapacity;
// }
//
// public Item removeItem(int index) {
// Item removedItem = items.remove(index);
// costs -= removedItem.price;
// remainingCapacity += removedItem.volume;
// return removedItem;
// }
//
// public boolean isFull() {
// return remainingCapacity == 0;
// }
//
// @Override
// public boolean equals(Object otherObject) {
// if (otherObject instanceof Knapsack == false) {
// return false;
// }
//
// Knapsack otherKnapsack = (Knapsack) otherObject;
//
// if (otherKnapsack.items.size() != this.items.size()) {
// return false;
// }
//
// for (Item item : items) {
// if (otherKnapsack.items.contains(item) == false) {
// return false;
// }
// }
//
//
// return this.totalCapacity == otherKnapsack.totalCapacity;
// }
//
// @Override
// public String toString() {
// return (totalCapacity - remainingCapacity) + "/" + totalCapacity + ": " + items + " " + costs;
// }
// }
// Path: MetaHeuristics4Java-Examples/src/test/java/de/mh4j/examples/maxknapsack/solver/SimulatedAnnealingKnapsackSolverTest.java
import static org.testng.AssertJUnit.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.testng.annotations.Test;
import ch.qos.logback.classic.Level;
import de.mh4j.examples.maxknapsack.model.Item;
import de.mh4j.examples.maxknapsack.model.Knapsack;
package de.mh4j.examples.maxknapsack.solver;
public class SimulatedAnnealingKnapsackSolverTest {
@Test
public void testSolveSimpleInstance() {
int knapsackCapacity = 59;
List<Item> items = new ArrayList<>(Arrays.asList(new Item("Foo", 100,
40), new Item("Bar", 80, 30), new Item("Muh", 5, 5), new Item(
"Awe", 30, 10)));
SimulatedAnnealingKnapsackSolver solver = new SimulatedAnnealingKnapsackSolver(
knapsackCapacity, items);
solver.run();
}
@Test
public void testBuggyConfiguration() {
int knapsackCapacity = 59;
List<Item> items = new ArrayList<>(Arrays.asList(new Item("Foo", 100,
40), new Item("Bar", 80, 30), new Item("Muh", 5, 5), new Item(
"Awe", 30, 10)));
SimulatedAnnealingKnapsackSolver solver = new SimulatedAnnealingKnapsackSolver(
knapsackCapacity, items);
|
Knapsack currentSolution = new Knapsack(knapsackCapacity);
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java-Examples/src/test/java/de/mh4j/examples/solver/LocalSearchSorterTest.java
|
// Path: MetaHeuristics4Java-Examples/src/main/java/de/mh4j/examples/Sorting.java
// public class Sorting implements Solution<Sorting> {
// private static final Logger log = LoggerFactory.getLogger(Sorting.class);
//
// protected final int[] numbers;
// protected int costs;
//
// public Sorting(int... numbers) {
// this.numbers = numbers;
// checkSize();
// checkForDuplicates();
// calculateCosts();
// }
//
// public Sorting(Sorting otherSorting) {
// this.numbers = Arrays.copyOf(otherSorting.numbers, otherSorting.numbers.length);
// this.costs = otherSorting.costs;
// }
//
// private void checkSize() throws IllegalArgumentException {
// if (numbers.length == 0) {
// throw new IllegalArgumentException("Input array can not be empty");
// }
//
// int highestNumber = numbers[0];
// for (int i = 1; i < numbers.length; i++) {
// if (numbers[i] > highestNumber) {
// highestNumber = numbers[i];
// }
// }
//
// if (numbers.length != highestNumber + 1) {
// throw new IllegalArgumentException("Input array does not contain enough numbers (highest number is "
// + highestNumber + " but there were " + numbers.length + " entries in zero based array)");
// }
// }
//
// private void checkForDuplicates() throws IllegalArgumentException {
// boolean[] numberExists = new boolean[numbers.length];
// for (int i = 0; i < numberExists.length; i++) {
// numberExists[i] = false;
// }
//
// for (int i = 0; i < numbers.length; i++) {
// int number = numbers[i];
// if (numberExists[number] == true) {
// throw new IllegalArgumentException("Input array contains at least one duplicate number at index " + i);
// }
// else {
// numberExists[number] = true;
// }
// }
// }
//
// private void calculateCosts() {
// costs = 0;
// for (int i = 0; i < numbers.length; i++) {
// costs += calculateCostsAtIndex(i);
// }
// }
//
// private int calculateCostsAtIndex(int index) {
// return Math.abs(index - numbers[index]);
// }
//
// @Override
// public int getCosts() {
// return costs;
// }
//
// @Override
// public boolean isBetterThan(Sorting otherSorting) {
// return this.getCosts() < otherSorting.getCosts();
// }
//
// public int[] getNumbers() {
// return numbers;
// }
//
// public int getAmountOfNumbers() {
// return numbers.length;
// }
//
// @Override
// public boolean equals(Object otherObject) {
// if (otherObject instanceof Sorting) {
// Sorting otherSorting = (Sorting) otherObject;
// return Arrays.equals(this.numbers, otherSorting.numbers);
// }
// else {
// return false;
// }
// }
//
// /**
// * Creates a new Sorting instance with a random non-repeating numbers array.
// *
// * @param amountOfNumbers
// * Determines how many different numbers will be used in this
// * sorting (i.e. the size of the underlying array)
// */
// public static Sorting createRandomSorting(int amountOfNumbers) {
// return Sorting.createRandomSorting(amountOfNumbers, System.nanoTime());
// }
//
// /**
// * Creates a new Sorting instance with a random non-repeating numbers array.
// *
// * @param amountOfNumbers
// * Determines how many different numbers will be used in this
// * sorting (i.e. the size of the underlying array)
// * @param seed
// * for the random generator
// */
// public static Sorting createRandomSorting(int amountOfNumbers, long seed) {
// log.debug("create random sorting using seed {}", seed);
//
// ArrayList<Integer> remainingNumbers = new ArrayList<>(amountOfNumbers);
// for (int i = 0; i < amountOfNumbers; i++) {
// remainingNumbers.add(new Integer(i));
// }
//
// Random random = new Random(seed);
// int[] numbers = new int[amountOfNumbers];
// int currentIndex = 0;
// do {
// int randomIndex = random.nextInt(remainingNumbers.size());
// int randomNumber = remainingNumbers.remove(randomIndex);
// numbers[currentIndex] = randomNumber;
// currentIndex++;
// } while (remainingNumbers.isEmpty() == false);
//
// return new Sorting(numbers);
// }
//
// public void swapIndices(int i, int j) {
// // subtract old costs for the swapped indices
// costs -= calculateCostsAtIndex(i);
// costs -= calculateCostsAtIndex(j);
//
// // do the actual swap
// int tmp = numbers[i];
// numbers[i] = numbers[j];
// numbers[j] = tmp;
//
// // add new costs for the swapped indices
// costs += calculateCostsAtIndex(i);
// costs += calculateCostsAtIndex(j);
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// for (int i = 0; i < numbers.length; i++) {
// builder.append(numbers[i]);
// builder.append(", ");
// }
// return builder.substring(0, builder.length() - 2);
// }
// }
|
import org.testng.annotations.Test;
import de.mh4j.examples.Sorting;
|
package de.mh4j.examples.solver;
public class LocalSearchSorterTest {
@Test
public void testCreateInitialSolution() {
LocalSearchSorter sorter = new LocalSearchSorter(10);
sorter.createInitialSolution();
/*
* if the solver could create any solution without throwing an exception
* this test succeeded. (Sorting class handles its validity by itself)
*/
}
@Test
public void testCreateRandomNeighbor() {
LocalSearchSorter sorter = new LocalSearchSorter(10);
// invoke step to initialize the solver
sorter.step();
|
// Path: MetaHeuristics4Java-Examples/src/main/java/de/mh4j/examples/Sorting.java
// public class Sorting implements Solution<Sorting> {
// private static final Logger log = LoggerFactory.getLogger(Sorting.class);
//
// protected final int[] numbers;
// protected int costs;
//
// public Sorting(int... numbers) {
// this.numbers = numbers;
// checkSize();
// checkForDuplicates();
// calculateCosts();
// }
//
// public Sorting(Sorting otherSorting) {
// this.numbers = Arrays.copyOf(otherSorting.numbers, otherSorting.numbers.length);
// this.costs = otherSorting.costs;
// }
//
// private void checkSize() throws IllegalArgumentException {
// if (numbers.length == 0) {
// throw new IllegalArgumentException("Input array can not be empty");
// }
//
// int highestNumber = numbers[0];
// for (int i = 1; i < numbers.length; i++) {
// if (numbers[i] > highestNumber) {
// highestNumber = numbers[i];
// }
// }
//
// if (numbers.length != highestNumber + 1) {
// throw new IllegalArgumentException("Input array does not contain enough numbers (highest number is "
// + highestNumber + " but there were " + numbers.length + " entries in zero based array)");
// }
// }
//
// private void checkForDuplicates() throws IllegalArgumentException {
// boolean[] numberExists = new boolean[numbers.length];
// for (int i = 0; i < numberExists.length; i++) {
// numberExists[i] = false;
// }
//
// for (int i = 0; i < numbers.length; i++) {
// int number = numbers[i];
// if (numberExists[number] == true) {
// throw new IllegalArgumentException("Input array contains at least one duplicate number at index " + i);
// }
// else {
// numberExists[number] = true;
// }
// }
// }
//
// private void calculateCosts() {
// costs = 0;
// for (int i = 0; i < numbers.length; i++) {
// costs += calculateCostsAtIndex(i);
// }
// }
//
// private int calculateCostsAtIndex(int index) {
// return Math.abs(index - numbers[index]);
// }
//
// @Override
// public int getCosts() {
// return costs;
// }
//
// @Override
// public boolean isBetterThan(Sorting otherSorting) {
// return this.getCosts() < otherSorting.getCosts();
// }
//
// public int[] getNumbers() {
// return numbers;
// }
//
// public int getAmountOfNumbers() {
// return numbers.length;
// }
//
// @Override
// public boolean equals(Object otherObject) {
// if (otherObject instanceof Sorting) {
// Sorting otherSorting = (Sorting) otherObject;
// return Arrays.equals(this.numbers, otherSorting.numbers);
// }
// else {
// return false;
// }
// }
//
// /**
// * Creates a new Sorting instance with a random non-repeating numbers array.
// *
// * @param amountOfNumbers
// * Determines how many different numbers will be used in this
// * sorting (i.e. the size of the underlying array)
// */
// public static Sorting createRandomSorting(int amountOfNumbers) {
// return Sorting.createRandomSorting(amountOfNumbers, System.nanoTime());
// }
//
// /**
// * Creates a new Sorting instance with a random non-repeating numbers array.
// *
// * @param amountOfNumbers
// * Determines how many different numbers will be used in this
// * sorting (i.e. the size of the underlying array)
// * @param seed
// * for the random generator
// */
// public static Sorting createRandomSorting(int amountOfNumbers, long seed) {
// log.debug("create random sorting using seed {}", seed);
//
// ArrayList<Integer> remainingNumbers = new ArrayList<>(amountOfNumbers);
// for (int i = 0; i < amountOfNumbers; i++) {
// remainingNumbers.add(new Integer(i));
// }
//
// Random random = new Random(seed);
// int[] numbers = new int[amountOfNumbers];
// int currentIndex = 0;
// do {
// int randomIndex = random.nextInt(remainingNumbers.size());
// int randomNumber = remainingNumbers.remove(randomIndex);
// numbers[currentIndex] = randomNumber;
// currentIndex++;
// } while (remainingNumbers.isEmpty() == false);
//
// return new Sorting(numbers);
// }
//
// public void swapIndices(int i, int j) {
// // subtract old costs for the swapped indices
// costs -= calculateCostsAtIndex(i);
// costs -= calculateCostsAtIndex(j);
//
// // do the actual swap
// int tmp = numbers[i];
// numbers[i] = numbers[j];
// numbers[j] = tmp;
//
// // add new costs for the swapped indices
// costs += calculateCostsAtIndex(i);
// costs += calculateCostsAtIndex(j);
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// for (int i = 0; i < numbers.length; i++) {
// builder.append(numbers[i]);
// builder.append(", ");
// }
// return builder.substring(0, builder.length() - 2);
// }
// }
// Path: MetaHeuristics4Java-Examples/src/test/java/de/mh4j/examples/solver/LocalSearchSorterTest.java
import org.testng.annotations.Test;
import de.mh4j.examples.Sorting;
package de.mh4j.examples.solver;
public class LocalSearchSorterTest {
@Test
public void testCreateInitialSolution() {
LocalSearchSorter sorter = new LocalSearchSorter(10);
sorter.createInitialSolution();
/*
* if the solver could create any solution without throwing an exception
* this test succeeded. (Sorting class handles its validity by itself)
*/
}
@Test
public void testCreateRandomNeighbor() {
LocalSearchSorter sorter = new LocalSearchSorter(10);
// invoke step to initialize the solver
sorter.step();
|
Sorting initialSorting = sorter.getCurrentSolution();
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/test/java/de/mh4j/solver/genetic/matingselection/StochasticUniversalSamplingSelectorTest.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Couple.java
// public class Couple {
// private final Genome parent1;
// private final Genome parent2;
//
// public Couple(Genome parent1, Genome parent2) {
// this.parent1 = parent1;
// this.parent2 = parent2;
// }
//
// public Genome getParent1() {
// return parent1;
// }
//
// public Genome getParent2() {
// return parent2;
// }
//
// @Override
// public String toString() {
// return "<" + parent1.toString() + ", " + parent2.toString() + ">";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Genome.java
// public abstract class Genome implements Solution<Genome>, Comparable<Genome> {
//
// private final Random random;
//
// public final static int NO_BIRTH_GENERATION_ASSOCIATED = -1;
//
// private int birthGeneration;
//
// /**
// * TODO write javadoc<br>
// */
// public Genome() {
// random = RNGGenerator.createRandomNumberGenerator();
// birthGeneration = NO_BIRTH_GENERATION_ASSOCIATED;
// }
//
// /**
// * Returns the general Fitness of this genome. The better a genome is the
// * higher should this value be.
// */
// public abstract int getFitness();
//
// /**
// * The costs of a genome are the opposite of its fitness. The better a
// * genome is, the higher is its fitness and the lower will the costs be.
// *
// * @return the negated return value of <code>getFitness()</code>
// * @see #getFitness()
// */
// @Override
// public int getCosts() {
// return getFitness();
// }
//
// /**
// * TODO write javadoc
// */
// public int getBirthGeneration() {
// return birthGeneration;
// }
//
// /**
// * TODO write javadoc
// */
// public void setBirthGeneration(int birthGeneration) {
// this.birthGeneration = birthGeneration;
// }
//
// /**
// * Compares this genome to another genome depending on the return values of
// * {@link #isBetterThan(Genome)} and {@link #equals(Object)}.
// *
// * @param otherGenome
// * the other genome which is compared to this genome
// * @return <code>Comparable.GREATER</code> if this genome is better<br>
// * <code>Comparable.LOWER</code> if this genome is worse<br>
// * <code>Comparable.EQUAL</code> if both genomes are equal<br>
// * or some value randomly chosen between
// * <code>Comparable.LOWER</code> and <code>Comparable.GREATER</code>
// * if <code>this.isBetterThan(otherGenome)</code> and
// * <code>otherGenome.isBetterThan(this)</code> and
// * <code>this.equals(otherGenome)</code> all return
// * <code>false</code>
// * @see Comparable
// */
// @Override
// public int compareTo(Genome otherGenome) {
//
// if (this.isBetterThan(otherGenome)) {
// return Comparable.GREATER;
// }
// else if (otherGenome.isBetterThan(this)) {
// return Comparable.LOWER;
// }
// else if (this.equals(otherGenome)) {
// return Comparable.EQUAL;
// }
// else {
// if (random.nextBoolean()) {
// return Comparable.LOWER;
// }
// else {
// return Comparable.GREATER;
// }
// }
// }
// }
|
import java.util.Collection;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import de.mh4j.solver.genetic.Couple;
import de.mh4j.solver.genetic.Genome;
|
package de.mh4j.solver.genetic.matingselection;
public class StochasticUniversalSamplingSelectorTest extends MatingSelectorTestCase {
@Override
@BeforeMethod
public void setUp() {
super.setUp();
}
@Test
public void testSelect() throws Exception {
int numberOfPairs = 4;
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Couple.java
// public class Couple {
// private final Genome parent1;
// private final Genome parent2;
//
// public Couple(Genome parent1, Genome parent2) {
// this.parent1 = parent1;
// this.parent2 = parent2;
// }
//
// public Genome getParent1() {
// return parent1;
// }
//
// public Genome getParent2() {
// return parent2;
// }
//
// @Override
// public String toString() {
// return "<" + parent1.toString() + ", " + parent2.toString() + ">";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Genome.java
// public abstract class Genome implements Solution<Genome>, Comparable<Genome> {
//
// private final Random random;
//
// public final static int NO_BIRTH_GENERATION_ASSOCIATED = -1;
//
// private int birthGeneration;
//
// /**
// * TODO write javadoc<br>
// */
// public Genome() {
// random = RNGGenerator.createRandomNumberGenerator();
// birthGeneration = NO_BIRTH_GENERATION_ASSOCIATED;
// }
//
// /**
// * Returns the general Fitness of this genome. The better a genome is the
// * higher should this value be.
// */
// public abstract int getFitness();
//
// /**
// * The costs of a genome are the opposite of its fitness. The better a
// * genome is, the higher is its fitness and the lower will the costs be.
// *
// * @return the negated return value of <code>getFitness()</code>
// * @see #getFitness()
// */
// @Override
// public int getCosts() {
// return getFitness();
// }
//
// /**
// * TODO write javadoc
// */
// public int getBirthGeneration() {
// return birthGeneration;
// }
//
// /**
// * TODO write javadoc
// */
// public void setBirthGeneration(int birthGeneration) {
// this.birthGeneration = birthGeneration;
// }
//
// /**
// * Compares this genome to another genome depending on the return values of
// * {@link #isBetterThan(Genome)} and {@link #equals(Object)}.
// *
// * @param otherGenome
// * the other genome which is compared to this genome
// * @return <code>Comparable.GREATER</code> if this genome is better<br>
// * <code>Comparable.LOWER</code> if this genome is worse<br>
// * <code>Comparable.EQUAL</code> if both genomes are equal<br>
// * or some value randomly chosen between
// * <code>Comparable.LOWER</code> and <code>Comparable.GREATER</code>
// * if <code>this.isBetterThan(otherGenome)</code> and
// * <code>otherGenome.isBetterThan(this)</code> and
// * <code>this.equals(otherGenome)</code> all return
// * <code>false</code>
// * @see Comparable
// */
// @Override
// public int compareTo(Genome otherGenome) {
//
// if (this.isBetterThan(otherGenome)) {
// return Comparable.GREATER;
// }
// else if (otherGenome.isBetterThan(this)) {
// return Comparable.LOWER;
// }
// else if (this.equals(otherGenome)) {
// return Comparable.EQUAL;
// }
// else {
// if (random.nextBoolean()) {
// return Comparable.LOWER;
// }
// else {
// return Comparable.GREATER;
// }
// }
// }
// }
// Path: MetaHeuristics4Java/src/test/java/de/mh4j/solver/genetic/matingselection/StochasticUniversalSamplingSelectorTest.java
import java.util.Collection;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import de.mh4j.solver.genetic.Couple;
import de.mh4j.solver.genetic.Genome;
package de.mh4j.solver.genetic.matingselection;
public class StochasticUniversalSamplingSelectorTest extends MatingSelectorTestCase {
@Override
@BeforeMethod
public void setUp() {
super.setUp();
}
@Test
public void testSelect() throws Exception {
int numberOfPairs = 4;
|
MatingSelector<Genome> selector = new StochasticUniversalSamplingSelector<>();
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/test/java/de/mh4j/solver/genetic/matingselection/StochasticUniversalSamplingSelectorTest.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Couple.java
// public class Couple {
// private final Genome parent1;
// private final Genome parent2;
//
// public Couple(Genome parent1, Genome parent2) {
// this.parent1 = parent1;
// this.parent2 = parent2;
// }
//
// public Genome getParent1() {
// return parent1;
// }
//
// public Genome getParent2() {
// return parent2;
// }
//
// @Override
// public String toString() {
// return "<" + parent1.toString() + ", " + parent2.toString() + ">";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Genome.java
// public abstract class Genome implements Solution<Genome>, Comparable<Genome> {
//
// private final Random random;
//
// public final static int NO_BIRTH_GENERATION_ASSOCIATED = -1;
//
// private int birthGeneration;
//
// /**
// * TODO write javadoc<br>
// */
// public Genome() {
// random = RNGGenerator.createRandomNumberGenerator();
// birthGeneration = NO_BIRTH_GENERATION_ASSOCIATED;
// }
//
// /**
// * Returns the general Fitness of this genome. The better a genome is the
// * higher should this value be.
// */
// public abstract int getFitness();
//
// /**
// * The costs of a genome are the opposite of its fitness. The better a
// * genome is, the higher is its fitness and the lower will the costs be.
// *
// * @return the negated return value of <code>getFitness()</code>
// * @see #getFitness()
// */
// @Override
// public int getCosts() {
// return getFitness();
// }
//
// /**
// * TODO write javadoc
// */
// public int getBirthGeneration() {
// return birthGeneration;
// }
//
// /**
// * TODO write javadoc
// */
// public void setBirthGeneration(int birthGeneration) {
// this.birthGeneration = birthGeneration;
// }
//
// /**
// * Compares this genome to another genome depending on the return values of
// * {@link #isBetterThan(Genome)} and {@link #equals(Object)}.
// *
// * @param otherGenome
// * the other genome which is compared to this genome
// * @return <code>Comparable.GREATER</code> if this genome is better<br>
// * <code>Comparable.LOWER</code> if this genome is worse<br>
// * <code>Comparable.EQUAL</code> if both genomes are equal<br>
// * or some value randomly chosen between
// * <code>Comparable.LOWER</code> and <code>Comparable.GREATER</code>
// * if <code>this.isBetterThan(otherGenome)</code> and
// * <code>otherGenome.isBetterThan(this)</code> and
// * <code>this.equals(otherGenome)</code> all return
// * <code>false</code>
// * @see Comparable
// */
// @Override
// public int compareTo(Genome otherGenome) {
//
// if (this.isBetterThan(otherGenome)) {
// return Comparable.GREATER;
// }
// else if (otherGenome.isBetterThan(this)) {
// return Comparable.LOWER;
// }
// else if (this.equals(otherGenome)) {
// return Comparable.EQUAL;
// }
// else {
// if (random.nextBoolean()) {
// return Comparable.LOWER;
// }
// else {
// return Comparable.GREATER;
// }
// }
// }
// }
|
import java.util.Collection;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import de.mh4j.solver.genetic.Couple;
import de.mh4j.solver.genetic.Genome;
|
package de.mh4j.solver.genetic.matingselection;
public class StochasticUniversalSamplingSelectorTest extends MatingSelectorTestCase {
@Override
@BeforeMethod
public void setUp() {
super.setUp();
}
@Test
public void testSelect() throws Exception {
int numberOfPairs = 4;
MatingSelector<Genome> selector = new StochasticUniversalSamplingSelector<>();
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Couple.java
// public class Couple {
// private final Genome parent1;
// private final Genome parent2;
//
// public Couple(Genome parent1, Genome parent2) {
// this.parent1 = parent1;
// this.parent2 = parent2;
// }
//
// public Genome getParent1() {
// return parent1;
// }
//
// public Genome getParent2() {
// return parent2;
// }
//
// @Override
// public String toString() {
// return "<" + parent1.toString() + ", " + parent2.toString() + ">";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/genetic/Genome.java
// public abstract class Genome implements Solution<Genome>, Comparable<Genome> {
//
// private final Random random;
//
// public final static int NO_BIRTH_GENERATION_ASSOCIATED = -1;
//
// private int birthGeneration;
//
// /**
// * TODO write javadoc<br>
// */
// public Genome() {
// random = RNGGenerator.createRandomNumberGenerator();
// birthGeneration = NO_BIRTH_GENERATION_ASSOCIATED;
// }
//
// /**
// * Returns the general Fitness of this genome. The better a genome is the
// * higher should this value be.
// */
// public abstract int getFitness();
//
// /**
// * The costs of a genome are the opposite of its fitness. The better a
// * genome is, the higher is its fitness and the lower will the costs be.
// *
// * @return the negated return value of <code>getFitness()</code>
// * @see #getFitness()
// */
// @Override
// public int getCosts() {
// return getFitness();
// }
//
// /**
// * TODO write javadoc
// */
// public int getBirthGeneration() {
// return birthGeneration;
// }
//
// /**
// * TODO write javadoc
// */
// public void setBirthGeneration(int birthGeneration) {
// this.birthGeneration = birthGeneration;
// }
//
// /**
// * Compares this genome to another genome depending on the return values of
// * {@link #isBetterThan(Genome)} and {@link #equals(Object)}.
// *
// * @param otherGenome
// * the other genome which is compared to this genome
// * @return <code>Comparable.GREATER</code> if this genome is better<br>
// * <code>Comparable.LOWER</code> if this genome is worse<br>
// * <code>Comparable.EQUAL</code> if both genomes are equal<br>
// * or some value randomly chosen between
// * <code>Comparable.LOWER</code> and <code>Comparable.GREATER</code>
// * if <code>this.isBetterThan(otherGenome)</code> and
// * <code>otherGenome.isBetterThan(this)</code> and
// * <code>this.equals(otherGenome)</code> all return
// * <code>false</code>
// * @see Comparable
// */
// @Override
// public int compareTo(Genome otherGenome) {
//
// if (this.isBetterThan(otherGenome)) {
// return Comparable.GREATER;
// }
// else if (otherGenome.isBetterThan(this)) {
// return Comparable.LOWER;
// }
// else if (this.equals(otherGenome)) {
// return Comparable.EQUAL;
// }
// else {
// if (random.nextBoolean()) {
// return Comparable.LOWER;
// }
// else {
// return Comparable.GREATER;
// }
// }
// }
// }
// Path: MetaHeuristics4Java/src/test/java/de/mh4j/solver/genetic/matingselection/StochasticUniversalSamplingSelectorTest.java
import java.util.Collection;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import de.mh4j.solver.genetic.Couple;
import de.mh4j.solver.genetic.Genome;
package de.mh4j.solver.genetic.matingselection;
public class StochasticUniversalSamplingSelectorTest extends MatingSelectorTestCase {
@Override
@BeforeMethod
public void setUp() {
super.setUp();
}
@Test
public void testSelect() throws Exception {
int numberOfPairs = 4;
MatingSelector<Genome> selector = new StochasticUniversalSamplingSelector<>();
|
Collection<Couple> parents = selector.select(numberOfPairs, genePool);
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/test/java/de/mh4j/solver/StepCountTerminationTest.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/StepCountTermination.java
// public class StepCountTermination implements TerminationCondition {
//
// private final Solver<?> solver;
// private final int maxStepCount;
//
// public StepCountTermination(Solver<?> solver, int maxStepCount) {
// this.solver = solver;
// this.maxStepCount = maxStepCount;
// }
//
// @Override
// public boolean shouldTerminate() {
// return solver.getNumberOfSteps() >= maxStepCount;
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/TerminationCondition.java
// public interface TerminationCondition {
//
// // TODO add javadoc
// boolean shouldTerminate();
//
// }
|
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.testng.annotations.Test;
import de.mh4j.solver.termination.StepCountTermination;
import de.mh4j.solver.termination.TerminationCondition;
|
package de.mh4j.solver;
public class StepCountTerminationTest {
@Test
@SuppressWarnings("unchecked")
public void testShouldTerminate() {
int maxStepCount = 100;
Solver<Object> solver = mock(Solver.class);
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/StepCountTermination.java
// public class StepCountTermination implements TerminationCondition {
//
// private final Solver<?> solver;
// private final int maxStepCount;
//
// public StepCountTermination(Solver<?> solver, int maxStepCount) {
// this.solver = solver;
// this.maxStepCount = maxStepCount;
// }
//
// @Override
// public boolean shouldTerminate() {
// return solver.getNumberOfSteps() >= maxStepCount;
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/TerminationCondition.java
// public interface TerminationCondition {
//
// // TODO add javadoc
// boolean shouldTerminate();
//
// }
// Path: MetaHeuristics4Java/src/test/java/de/mh4j/solver/StepCountTerminationTest.java
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.testng.annotations.Test;
import de.mh4j.solver.termination.StepCountTermination;
import de.mh4j.solver.termination.TerminationCondition;
package de.mh4j.solver;
public class StepCountTerminationTest {
@Test
@SuppressWarnings("unchecked")
public void testShouldTerminate() {
int maxStepCount = 100;
Solver<Object> solver = mock(Solver.class);
|
TerminationCondition terminator = new StepCountTermination(solver, maxStepCount);
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/test/java/de/mh4j/solver/StepCountTerminationTest.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/StepCountTermination.java
// public class StepCountTermination implements TerminationCondition {
//
// private final Solver<?> solver;
// private final int maxStepCount;
//
// public StepCountTermination(Solver<?> solver, int maxStepCount) {
// this.solver = solver;
// this.maxStepCount = maxStepCount;
// }
//
// @Override
// public boolean shouldTerminate() {
// return solver.getNumberOfSteps() >= maxStepCount;
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/TerminationCondition.java
// public interface TerminationCondition {
//
// // TODO add javadoc
// boolean shouldTerminate();
//
// }
|
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.testng.annotations.Test;
import de.mh4j.solver.termination.StepCountTermination;
import de.mh4j.solver.termination.TerminationCondition;
|
package de.mh4j.solver;
public class StepCountTerminationTest {
@Test
@SuppressWarnings("unchecked")
public void testShouldTerminate() {
int maxStepCount = 100;
Solver<Object> solver = mock(Solver.class);
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/StepCountTermination.java
// public class StepCountTermination implements TerminationCondition {
//
// private final Solver<?> solver;
// private final int maxStepCount;
//
// public StepCountTermination(Solver<?> solver, int maxStepCount) {
// this.solver = solver;
// this.maxStepCount = maxStepCount;
// }
//
// @Override
// public boolean shouldTerminate() {
// return solver.getNumberOfSteps() >= maxStepCount;
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/TerminationCondition.java
// public interface TerminationCondition {
//
// // TODO add javadoc
// boolean shouldTerminate();
//
// }
// Path: MetaHeuristics4Java/src/test/java/de/mh4j/solver/StepCountTerminationTest.java
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.testng.annotations.Test;
import de.mh4j.solver.termination.StepCountTermination;
import de.mh4j.solver.termination.TerminationCondition;
package de.mh4j.solver;
public class StepCountTerminationTest {
@Test
@SuppressWarnings("unchecked")
public void testShouldTerminate() {
int maxStepCount = 100;
Solver<Object> solver = mock(Solver.class);
|
TerminationCondition terminator = new StepCountTermination(solver, maxStepCount);
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/test/java/de/mh4j/solver/StagnationTerminationTest.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/StagnationTermination.java
// public class StagnationTermination implements TerminationCondition {
//
// private final Solver<? extends Solution<?>> solver;
// private final int maxNrOfStagnatingSteps;
//
// private int nrOfStagnatingSteps;
// private Solution<?> lastSolution;
//
// public StagnationTermination(Solver<? extends Solution<?>> solver,
// int maxNrOfStagnatingSteps) {
// this.solver = solver;
// this.maxNrOfStagnatingSteps = maxNrOfStagnatingSteps;
// this.nrOfStagnatingSteps = 0;
// }
//
// @Override
// public boolean shouldTerminate() {
// Solution<?> currentSolution = solver.getCurrentSolution();
//
// if (lastSolution == null) {
// lastSolution = currentSolution;
// nrOfStagnatingSteps = 0;
// } else if (currentSolution.equals(lastSolution)) {
// nrOfStagnatingSteps++;
// } else {
// nrOfStagnatingSteps = 0;
// lastSolution = currentSolution;
// }
//
// return nrOfStagnatingSteps >= maxNrOfStagnatingSteps;
// }
//
// @Override
// public String toString() {
// return "stagnation termination condition (" + maxNrOfStagnatingSteps
// + " non-improving steps)";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/TerminationCondition.java
// public interface TerminationCondition {
//
// // TODO add javadoc
// boolean shouldTerminate();
//
// }
|
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.testng.annotations.Test;
import de.mh4j.solver.termination.StagnationTermination;
import de.mh4j.solver.termination.TerminationCondition;
|
package de.mh4j.solver;
public class StagnationTerminationTest {
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testShouldTerminate() {
int maxNrOfStagnatingSteps = 50;
Solver solver = mock(Solver.class);
when(solver.getCurrentSolution()).thenReturn(mock(Solution.class));
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/StagnationTermination.java
// public class StagnationTermination implements TerminationCondition {
//
// private final Solver<? extends Solution<?>> solver;
// private final int maxNrOfStagnatingSteps;
//
// private int nrOfStagnatingSteps;
// private Solution<?> lastSolution;
//
// public StagnationTermination(Solver<? extends Solution<?>> solver,
// int maxNrOfStagnatingSteps) {
// this.solver = solver;
// this.maxNrOfStagnatingSteps = maxNrOfStagnatingSteps;
// this.nrOfStagnatingSteps = 0;
// }
//
// @Override
// public boolean shouldTerminate() {
// Solution<?> currentSolution = solver.getCurrentSolution();
//
// if (lastSolution == null) {
// lastSolution = currentSolution;
// nrOfStagnatingSteps = 0;
// } else if (currentSolution.equals(lastSolution)) {
// nrOfStagnatingSteps++;
// } else {
// nrOfStagnatingSteps = 0;
// lastSolution = currentSolution;
// }
//
// return nrOfStagnatingSteps >= maxNrOfStagnatingSteps;
// }
//
// @Override
// public String toString() {
// return "stagnation termination condition (" + maxNrOfStagnatingSteps
// + " non-improving steps)";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/TerminationCondition.java
// public interface TerminationCondition {
//
// // TODO add javadoc
// boolean shouldTerminate();
//
// }
// Path: MetaHeuristics4Java/src/test/java/de/mh4j/solver/StagnationTerminationTest.java
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.testng.annotations.Test;
import de.mh4j.solver.termination.StagnationTermination;
import de.mh4j.solver.termination.TerminationCondition;
package de.mh4j.solver;
public class StagnationTerminationTest {
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testShouldTerminate() {
int maxNrOfStagnatingSteps = 50;
Solver solver = mock(Solver.class);
when(solver.getCurrentSolution()).thenReturn(mock(Solution.class));
|
TerminationCondition terminator = new StagnationTermination(solver, maxNrOfStagnatingSteps);
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/test/java/de/mh4j/solver/StagnationTerminationTest.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/StagnationTermination.java
// public class StagnationTermination implements TerminationCondition {
//
// private final Solver<? extends Solution<?>> solver;
// private final int maxNrOfStagnatingSteps;
//
// private int nrOfStagnatingSteps;
// private Solution<?> lastSolution;
//
// public StagnationTermination(Solver<? extends Solution<?>> solver,
// int maxNrOfStagnatingSteps) {
// this.solver = solver;
// this.maxNrOfStagnatingSteps = maxNrOfStagnatingSteps;
// this.nrOfStagnatingSteps = 0;
// }
//
// @Override
// public boolean shouldTerminate() {
// Solution<?> currentSolution = solver.getCurrentSolution();
//
// if (lastSolution == null) {
// lastSolution = currentSolution;
// nrOfStagnatingSteps = 0;
// } else if (currentSolution.equals(lastSolution)) {
// nrOfStagnatingSteps++;
// } else {
// nrOfStagnatingSteps = 0;
// lastSolution = currentSolution;
// }
//
// return nrOfStagnatingSteps >= maxNrOfStagnatingSteps;
// }
//
// @Override
// public String toString() {
// return "stagnation termination condition (" + maxNrOfStagnatingSteps
// + " non-improving steps)";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/TerminationCondition.java
// public interface TerminationCondition {
//
// // TODO add javadoc
// boolean shouldTerminate();
//
// }
|
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.testng.annotations.Test;
import de.mh4j.solver.termination.StagnationTermination;
import de.mh4j.solver.termination.TerminationCondition;
|
package de.mh4j.solver;
public class StagnationTerminationTest {
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testShouldTerminate() {
int maxNrOfStagnatingSteps = 50;
Solver solver = mock(Solver.class);
when(solver.getCurrentSolution()).thenReturn(mock(Solution.class));
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/StagnationTermination.java
// public class StagnationTermination implements TerminationCondition {
//
// private final Solver<? extends Solution<?>> solver;
// private final int maxNrOfStagnatingSteps;
//
// private int nrOfStagnatingSteps;
// private Solution<?> lastSolution;
//
// public StagnationTermination(Solver<? extends Solution<?>> solver,
// int maxNrOfStagnatingSteps) {
// this.solver = solver;
// this.maxNrOfStagnatingSteps = maxNrOfStagnatingSteps;
// this.nrOfStagnatingSteps = 0;
// }
//
// @Override
// public boolean shouldTerminate() {
// Solution<?> currentSolution = solver.getCurrentSolution();
//
// if (lastSolution == null) {
// lastSolution = currentSolution;
// nrOfStagnatingSteps = 0;
// } else if (currentSolution.equals(lastSolution)) {
// nrOfStagnatingSteps++;
// } else {
// nrOfStagnatingSteps = 0;
// lastSolution = currentSolution;
// }
//
// return nrOfStagnatingSteps >= maxNrOfStagnatingSteps;
// }
//
// @Override
// public String toString() {
// return "stagnation termination condition (" + maxNrOfStagnatingSteps
// + " non-improving steps)";
// }
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/TerminationCondition.java
// public interface TerminationCondition {
//
// // TODO add javadoc
// boolean shouldTerminate();
//
// }
// Path: MetaHeuristics4Java/src/test/java/de/mh4j/solver/StagnationTerminationTest.java
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.testng.annotations.Test;
import de.mh4j.solver.termination.StagnationTermination;
import de.mh4j.solver.termination.TerminationCondition;
package de.mh4j.solver;
public class StagnationTerminationTest {
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testShouldTerminate() {
int maxNrOfStagnatingSteps = 50;
Solver solver = mock(Solver.class);
when(solver.getCurrentSolution()).thenReturn(mock(Solution.class));
|
TerminationCondition terminator = new StagnationTermination(solver, maxNrOfStagnatingSteps);
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/test/java/de/mh4j/solver/AbstractSolverTest.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/TerminationCondition.java
// public interface TerminationCondition {
//
// // TODO add javadoc
// boolean shouldTerminate();
//
// }
|
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.testng.annotations.Test;
import ch.qos.logback.classic.Level;
import de.mh4j.solver.termination.TerminationCondition;
|
package de.mh4j.solver;
public class AbstractSolverTest {
@Test
public void testSolverRun() {
AbstractSolver<Object> solver = spy(new AbstractSolverMock());
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/TerminationCondition.java
// public interface TerminationCondition {
//
// // TODO add javadoc
// boolean shouldTerminate();
//
// }
// Path: MetaHeuristics4Java/src/test/java/de/mh4j/solver/AbstractSolverTest.java
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.testng.annotations.Test;
import ch.qos.logback.classic.Level;
import de.mh4j.solver.termination.TerminationCondition;
package de.mh4j.solver;
public class AbstractSolverTest {
@Test
public void testSolverRun() {
AbstractSolver<Object> solver = spy(new AbstractSolverMock());
|
TerminationCondition terminationCondition = mock(TerminationCondition.class);
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/main/java/de/mh4j/solver/AbstractSolver.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/TerminationCondition.java
// public interface TerminationCondition {
//
// // TODO add javadoc
// boolean shouldTerminate();
//
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/util/RNGGenerator.java
// public abstract class RNGGenerator {
// private final static Logger log = (Logger) LoggerFactory.getLogger(RNGGenerator.class);
//
// private static Random seedGenerator;
//
// public static void setMasterSeed(long masterSeed) {
// seedGenerator = new Random(masterSeed);
// log.info("Initialized random number generator with master seed {}", masterSeed);
// }
//
// public static Random createRandomNumberGenerator() {
// if (seedGenerator == null) {
// setMasterSeed(System.currentTimeMillis());
// }
// long seed = seedGenerator.nextLong();
// return new Random(seed);
// }
//
// }
|
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import de.mh4j.solver.termination.TerminationCondition;
import de.mh4j.util.RNGGenerator;
|
/*
* Copyright 2012 Friedrich Große, Paul Seiferth,
* Sebastian Starroske, Yannik Stein
*
* This file is part of MetaHeuristics4Java.
*
* MetaHeuristics4Java is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MetaHeuristics4Java is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MetaHeuristics4Java. If not, see <http://www.gnu.org/licenses/>.
*/
package de.mh4j.solver;
/**
* A Solver is the representation of an algorithm that can find or approximate
* solutions to a given optimization problem.
*
* TODO write more about the possible implementation and utilization of a solver
*
* @param <GenericSolutionType>
* the actual Type of the solution class.
*
* @author Friedrich Große <friedrich.grosse@gmail.com>
*/
public abstract class AbstractSolver<GenericSolutionType> implements Solver<GenericSolutionType> {
protected final Logger log = (Logger) LoggerFactory.getLogger(getClass());
protected final Random randomizer;
private final List<SolverStateListener<GenericSolutionType>> stateListeners = new ArrayList<>(2);
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/TerminationCondition.java
// public interface TerminationCondition {
//
// // TODO add javadoc
// boolean shouldTerminate();
//
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/util/RNGGenerator.java
// public abstract class RNGGenerator {
// private final static Logger log = (Logger) LoggerFactory.getLogger(RNGGenerator.class);
//
// private static Random seedGenerator;
//
// public static void setMasterSeed(long masterSeed) {
// seedGenerator = new Random(masterSeed);
// log.info("Initialized random number generator with master seed {}", masterSeed);
// }
//
// public static Random createRandomNumberGenerator() {
// if (seedGenerator == null) {
// setMasterSeed(System.currentTimeMillis());
// }
// long seed = seedGenerator.nextLong();
// return new Random(seed);
// }
//
// }
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/AbstractSolver.java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import de.mh4j.solver.termination.TerminationCondition;
import de.mh4j.util.RNGGenerator;
/*
* Copyright 2012 Friedrich Große, Paul Seiferth,
* Sebastian Starroske, Yannik Stein
*
* This file is part of MetaHeuristics4Java.
*
* MetaHeuristics4Java is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MetaHeuristics4Java is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MetaHeuristics4Java. If not, see <http://www.gnu.org/licenses/>.
*/
package de.mh4j.solver;
/**
* A Solver is the representation of an algorithm that can find or approximate
* solutions to a given optimization problem.
*
* TODO write more about the possible implementation and utilization of a solver
*
* @param <GenericSolutionType>
* the actual Type of the solution class.
*
* @author Friedrich Große <friedrich.grosse@gmail.com>
*/
public abstract class AbstractSolver<GenericSolutionType> implements Solver<GenericSolutionType> {
protected final Logger log = (Logger) LoggerFactory.getLogger(getClass());
protected final Random randomizer;
private final List<SolverStateListener<GenericSolutionType>> stateListeners = new ArrayList<>(2);
|
private final List<TerminationCondition> terminationConditions = new ArrayList<>(1);
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java/src/main/java/de/mh4j/solver/AbstractSolver.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/TerminationCondition.java
// public interface TerminationCondition {
//
// // TODO add javadoc
// boolean shouldTerminate();
//
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/util/RNGGenerator.java
// public abstract class RNGGenerator {
// private final static Logger log = (Logger) LoggerFactory.getLogger(RNGGenerator.class);
//
// private static Random seedGenerator;
//
// public static void setMasterSeed(long masterSeed) {
// seedGenerator = new Random(masterSeed);
// log.info("Initialized random number generator with master seed {}", masterSeed);
// }
//
// public static Random createRandomNumberGenerator() {
// if (seedGenerator == null) {
// setMasterSeed(System.currentTimeMillis());
// }
// long seed = seedGenerator.nextLong();
// return new Random(seed);
// }
//
// }
|
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import de.mh4j.solver.termination.TerminationCondition;
import de.mh4j.util.RNGGenerator;
|
/*
* Copyright 2012 Friedrich Große, Paul Seiferth,
* Sebastian Starroske, Yannik Stein
*
* This file is part of MetaHeuristics4Java.
*
* MetaHeuristics4Java is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MetaHeuristics4Java is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MetaHeuristics4Java. If not, see <http://www.gnu.org/licenses/>.
*/
package de.mh4j.solver;
/**
* A Solver is the representation of an algorithm that can find or approximate
* solutions to a given optimization problem.
*
* TODO write more about the possible implementation and utilization of a solver
*
* @param <GenericSolutionType>
* the actual Type of the solution class.
*
* @author Friedrich Große <friedrich.grosse@gmail.com>
*/
public abstract class AbstractSolver<GenericSolutionType> implements Solver<GenericSolutionType> {
protected final Logger log = (Logger) LoggerFactory.getLogger(getClass());
protected final Random randomizer;
private final List<SolverStateListener<GenericSolutionType>> stateListeners = new ArrayList<>(2);
private final List<TerminationCondition> terminationConditions = new ArrayList<>(1);
private int numberOfSteps = 0;
private boolean isInitialized = false;
/**
* Creates a new solver. Note that the solver initialization will not yet be
* started. Instead this is done after the first call to {@link #step()} or
* {@link #run()}.
*/
public AbstractSolver() {
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/termination/TerminationCondition.java
// public interface TerminationCondition {
//
// // TODO add javadoc
// boolean shouldTerminate();
//
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/util/RNGGenerator.java
// public abstract class RNGGenerator {
// private final static Logger log = (Logger) LoggerFactory.getLogger(RNGGenerator.class);
//
// private static Random seedGenerator;
//
// public static void setMasterSeed(long masterSeed) {
// seedGenerator = new Random(masterSeed);
// log.info("Initialized random number generator with master seed {}", masterSeed);
// }
//
// public static Random createRandomNumberGenerator() {
// if (seedGenerator == null) {
// setMasterSeed(System.currentTimeMillis());
// }
// long seed = seedGenerator.nextLong();
// return new Random(seed);
// }
//
// }
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/AbstractSolver.java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import de.mh4j.solver.termination.TerminationCondition;
import de.mh4j.util.RNGGenerator;
/*
* Copyright 2012 Friedrich Große, Paul Seiferth,
* Sebastian Starroske, Yannik Stein
*
* This file is part of MetaHeuristics4Java.
*
* MetaHeuristics4Java is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MetaHeuristics4Java is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MetaHeuristics4Java. If not, see <http://www.gnu.org/licenses/>.
*/
package de.mh4j.solver;
/**
* A Solver is the representation of an algorithm that can find or approximate
* solutions to a given optimization problem.
*
* TODO write more about the possible implementation and utilization of a solver
*
* @param <GenericSolutionType>
* the actual Type of the solution class.
*
* @author Friedrich Große <friedrich.grosse@gmail.com>
*/
public abstract class AbstractSolver<GenericSolutionType> implements Solver<GenericSolutionType> {
protected final Logger log = (Logger) LoggerFactory.getLogger(getClass());
protected final Random randomizer;
private final List<SolverStateListener<GenericSolutionType>> stateListeners = new ArrayList<>(2);
private final List<TerminationCondition> terminationConditions = new ArrayList<>(1);
private int numberOfSteps = 0;
private boolean isInitialized = false;
/**
* Creates a new solver. Note that the solver initialization will not yet be
* started. Instead this is done after the first call to {@link #step()} or
* {@link #run()}.
*/
public AbstractSolver() {
|
randomizer = RNGGenerator.createRandomNumberGenerator();
|
MH4J/MetaHeuristics4Java
|
MetaHeuristics4Java-Examples/src/main/java/de/mh4j/examples/ExampleSolverStateListener.java
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/Solution.java
// public interface Solution<SolutionImplementationType extends Solution<?>> {
//
// /**
// * Returns a numeric value that represents the costs of this solution. If
// * the optimization problem is, to maximize the costs of a solution the
// * return value indicates the absolute quality of the solution (the
// * fitness).
// **/
// int getCosts();
//
// /**
// * Compares this solution to another solution.
// *
// * @return <code>true</code> if this solution instance is better than the
// * other solution<br>
// * <code>false</code> if this solution is of worse or equal quality.
// **/
// boolean isBetterThan(SolutionImplementationType otherSolution);
//
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/Solver.java
// public interface Solver<GenericSolutionType> extends Runnable {
//
// /**
// * Performs a single step in the algorithm of this solver. The following
// * actions will be taken:
// * <ol>
// * <li>The solver will be {@link #initialize() initialized} if it has not
// * yet been initialized by a previous call to this method</li>
// * <li>The actual algorithm step will be performed</li>
// * <li>The step counter will be advanced by 1</li>
// * <li>All {@link SolverStateListener SolverStateListeners} will be notified
// * by a call to {@link SolverStateListener#solverStateHasChanged()}</li>
// */
// void step();
//
// /**
// * Runs the whole algorithm until the termination condition is reached.
// */
// @Override
// void run();
//
// /**
// * Resets this solver. The current solution will be discarded and the solver
// * will be initialized again. All {@link SolverStateListener
// * SolverStateListeners} will be notified.
// */
// void reset();
//
// /**
// * Returns how often a single step in the solvers algorithm has been
// * executed.
// */
// int getNumberOfSteps();
//
// /**
// * Returns the current solution that has been created after the last call to
// * {@link #step()}.<br>
// * <br>
// * <b>Note:</b><br>
// * This interim solution may not be the best solution ever found and can
// * even be <code>null</code> if {@link #step()} has never been called.
// */
// GenericSolutionType getCurrentSolution();
//
// /**
// * Returns <code>true</code> as soon as the solver has finished optimizing
// * the problem. Otherwise <code>false</code> is returned.
// */
// boolean hasFinished();
//
// /**
// * Adds a {@linkplain SolverStateListener} to this solver. The listener will
// * be informed about important events that may occur on this solver.
// */
// void addStateListener(SolverStateListener<GenericSolutionType> listener);
//
// /**
// * Removes a {@linkplain SolverStateListener} from this solver. The listener
// * will no longer be informed about important events that may occur on this
// * solver.
// */
// void removeStateListener(SolverStateListener<GenericSolutionType> listener);
//
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/SolverStateAdapter.java
// public class SolverStateAdapter<GenericSolutionType> implements SolverStateListener<GenericSolutionType> {
//
// @Override
// public void solverHasBeenRestarted(Solver<GenericSolutionType> solver) {
// // do nothing until this method is overridden
//
// }
//
// @Override
// public void solverHasStepped(Solver<GenericSolutionType> solver) {
// // do nothing until this method is overridden
//
// }
//
// @Override
// public void solverHasFinished(Solver<GenericSolutionType> solver) {
// // do nothing until this method is overridden
// }
//
// }
|
import de.mh4j.solver.Solution;
import de.mh4j.solver.Solver;
import de.mh4j.solver.SolverStateAdapter;
|
package de.mh4j.examples;
public class ExampleSolverStateListener<GenericSolutionType extends Solution<GenericSolutionType>> extends
SolverStateAdapter<GenericSolutionType> {
GenericSolutionType lastSolution = null;
@Override
|
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/Solution.java
// public interface Solution<SolutionImplementationType extends Solution<?>> {
//
// /**
// * Returns a numeric value that represents the costs of this solution. If
// * the optimization problem is, to maximize the costs of a solution the
// * return value indicates the absolute quality of the solution (the
// * fitness).
// **/
// int getCosts();
//
// /**
// * Compares this solution to another solution.
// *
// * @return <code>true</code> if this solution instance is better than the
// * other solution<br>
// * <code>false</code> if this solution is of worse or equal quality.
// **/
// boolean isBetterThan(SolutionImplementationType otherSolution);
//
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/Solver.java
// public interface Solver<GenericSolutionType> extends Runnable {
//
// /**
// * Performs a single step in the algorithm of this solver. The following
// * actions will be taken:
// * <ol>
// * <li>The solver will be {@link #initialize() initialized} if it has not
// * yet been initialized by a previous call to this method</li>
// * <li>The actual algorithm step will be performed</li>
// * <li>The step counter will be advanced by 1</li>
// * <li>All {@link SolverStateListener SolverStateListeners} will be notified
// * by a call to {@link SolverStateListener#solverStateHasChanged()}</li>
// */
// void step();
//
// /**
// * Runs the whole algorithm until the termination condition is reached.
// */
// @Override
// void run();
//
// /**
// * Resets this solver. The current solution will be discarded and the solver
// * will be initialized again. All {@link SolverStateListener
// * SolverStateListeners} will be notified.
// */
// void reset();
//
// /**
// * Returns how often a single step in the solvers algorithm has been
// * executed.
// */
// int getNumberOfSteps();
//
// /**
// * Returns the current solution that has been created after the last call to
// * {@link #step()}.<br>
// * <br>
// * <b>Note:</b><br>
// * This interim solution may not be the best solution ever found and can
// * even be <code>null</code> if {@link #step()} has never been called.
// */
// GenericSolutionType getCurrentSolution();
//
// /**
// * Returns <code>true</code> as soon as the solver has finished optimizing
// * the problem. Otherwise <code>false</code> is returned.
// */
// boolean hasFinished();
//
// /**
// * Adds a {@linkplain SolverStateListener} to this solver. The listener will
// * be informed about important events that may occur on this solver.
// */
// void addStateListener(SolverStateListener<GenericSolutionType> listener);
//
// /**
// * Removes a {@linkplain SolverStateListener} from this solver. The listener
// * will no longer be informed about important events that may occur on this
// * solver.
// */
// void removeStateListener(SolverStateListener<GenericSolutionType> listener);
//
// }
//
// Path: MetaHeuristics4Java/src/main/java/de/mh4j/solver/SolverStateAdapter.java
// public class SolverStateAdapter<GenericSolutionType> implements SolverStateListener<GenericSolutionType> {
//
// @Override
// public void solverHasBeenRestarted(Solver<GenericSolutionType> solver) {
// // do nothing until this method is overridden
//
// }
//
// @Override
// public void solverHasStepped(Solver<GenericSolutionType> solver) {
// // do nothing until this method is overridden
//
// }
//
// @Override
// public void solverHasFinished(Solver<GenericSolutionType> solver) {
// // do nothing until this method is overridden
// }
//
// }
// Path: MetaHeuristics4Java-Examples/src/main/java/de/mh4j/examples/ExampleSolverStateListener.java
import de.mh4j.solver.Solution;
import de.mh4j.solver.Solver;
import de.mh4j.solver.SolverStateAdapter;
package de.mh4j.examples;
public class ExampleSolverStateListener<GenericSolutionType extends Solution<GenericSolutionType>> extends
SolverStateAdapter<GenericSolutionType> {
GenericSolutionType lastSolution = null;
@Override
|
public void solverHasStepped(Solver<GenericSolutionType> solver) {
|
greenrobot/EventBus
|
EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java
|
// Path: EventBus/src/org/greenrobot/eventbus/android/AndroidComponents.java
// public abstract class AndroidComponents {
//
// private static final AndroidComponents implementation;
//
// static {
// implementation = AndroidDependenciesDetector.isAndroidSDKAvailable()
// ? AndroidDependenciesDetector.instantiateAndroidComponents()
// : null;
// }
//
// public static boolean areAvailable() {
// return implementation != null;
// }
//
// public static AndroidComponents get() {
// return implementation;
// }
//
// public final Logger logger;
// public final MainThreadSupport defaultMainThreadSupport;
//
// public AndroidComponents(Logger logger, MainThreadSupport defaultMainThreadSupport) {
// this.logger = logger;
// this.defaultMainThreadSupport = defaultMainThreadSupport;
// }
// }
|
import org.greenrobot.eventbus.android.AndroidComponents;
import org.greenrobot.eventbus.meta.SubscriberInfoIndex;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
|
/** Adds an index generated by EventBus' annotation preprocessor. */
public EventBusBuilder addIndex(SubscriberInfoIndex index) {
if (subscriberInfoIndexes == null) {
subscriberInfoIndexes = new ArrayList<>();
}
subscriberInfoIndexes.add(index);
return this;
}
/**
* Set a specific log handler for all EventBus logging.
* <p/>
* By default, all logging is via {@code android.util.Log} on Android or System.out on JVM.
*/
public EventBusBuilder logger(Logger logger) {
this.logger = logger;
return this;
}
Logger getLogger() {
if (logger != null) {
return logger;
} else {
return Logger.Default.get();
}
}
MainThreadSupport getMainThreadSupport() {
if (mainThreadSupport != null) {
return mainThreadSupport;
|
// Path: EventBus/src/org/greenrobot/eventbus/android/AndroidComponents.java
// public abstract class AndroidComponents {
//
// private static final AndroidComponents implementation;
//
// static {
// implementation = AndroidDependenciesDetector.isAndroidSDKAvailable()
// ? AndroidDependenciesDetector.instantiateAndroidComponents()
// : null;
// }
//
// public static boolean areAvailable() {
// return implementation != null;
// }
//
// public static AndroidComponents get() {
// return implementation;
// }
//
// public final Logger logger;
// public final MainThreadSupport defaultMainThreadSupport;
//
// public AndroidComponents(Logger logger, MainThreadSupport defaultMainThreadSupport) {
// this.logger = logger;
// this.defaultMainThreadSupport = defaultMainThreadSupport;
// }
// }
// Path: EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java
import org.greenrobot.eventbus.android.AndroidComponents;
import org.greenrobot.eventbus.meta.SubscriberInfoIndex;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/** Adds an index generated by EventBus' annotation preprocessor. */
public EventBusBuilder addIndex(SubscriberInfoIndex index) {
if (subscriberInfoIndexes == null) {
subscriberInfoIndexes = new ArrayList<>();
}
subscriberInfoIndexes.add(index);
return this;
}
/**
* Set a specific log handler for all EventBus logging.
* <p/>
* By default, all logging is via {@code android.util.Log} on Android or System.out on JVM.
*/
public EventBusBuilder logger(Logger logger) {
this.logger = logger;
return this;
}
Logger getLogger() {
if (logger != null) {
return logger;
} else {
return Logger.Default.get();
}
}
MainThreadSupport getMainThreadSupport() {
if (mainThreadSupport != null) {
return mainThreadSupport;
|
} else if (AndroidComponents.areAvailable()) {
|
greenrobot/EventBus
|
EventBusTest/src/org/greenrobot/eventbus/AndroidComponentsAvailabilityTest.java
|
// Path: EventBus/src/org/greenrobot/eventbus/android/AndroidComponents.java
// public abstract class AndroidComponents {
//
// private static final AndroidComponents implementation;
//
// static {
// implementation = AndroidDependenciesDetector.isAndroidSDKAvailable()
// ? AndroidDependenciesDetector.instantiateAndroidComponents()
// : null;
// }
//
// public static boolean areAvailable() {
// return implementation != null;
// }
//
// public static AndroidComponents get() {
// return implementation;
// }
//
// public final Logger logger;
// public final MainThreadSupport defaultMainThreadSupport;
//
// public AndroidComponents(Logger logger, MainThreadSupport defaultMainThreadSupport) {
// this.logger = logger;
// this.defaultMainThreadSupport = defaultMainThreadSupport;
// }
// }
|
import org.greenrobot.eventbus.android.AndroidComponents;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
|
package org.greenrobot.eventbus;
public class AndroidComponentsAvailabilityTest {
@Test
public void shouldBeAvailable() {
|
// Path: EventBus/src/org/greenrobot/eventbus/android/AndroidComponents.java
// public abstract class AndroidComponents {
//
// private static final AndroidComponents implementation;
//
// static {
// implementation = AndroidDependenciesDetector.isAndroidSDKAvailable()
// ? AndroidDependenciesDetector.instantiateAndroidComponents()
// : null;
// }
//
// public static boolean areAvailable() {
// return implementation != null;
// }
//
// public static AndroidComponents get() {
// return implementation;
// }
//
// public final Logger logger;
// public final MainThreadSupport defaultMainThreadSupport;
//
// public AndroidComponents(Logger logger, MainThreadSupport defaultMainThreadSupport) {
// this.logger = logger;
// this.defaultMainThreadSupport = defaultMainThreadSupport;
// }
// }
// Path: EventBusTest/src/org/greenrobot/eventbus/AndroidComponentsAvailabilityTest.java
import org.greenrobot.eventbus.android.AndroidComponents;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
package org.greenrobot.eventbus;
public class AndroidComponentsAvailabilityTest {
@Test
public void shouldBeAvailable() {
|
assertTrue(AndroidComponents.areAvailable());
|
greenrobot/EventBus
|
EventBus/src/org/greenrobot/eventbus/util/ExceptionToResourceMapping.java
|
// Path: EventBus/src/org/greenrobot/eventbus/Logger.java
// public interface Logger {
//
// void log(Level level, String msg);
//
// void log(Level level, String msg, Throwable th);
//
// class JavaLogger implements Logger {
// protected final java.util.logging.Logger logger;
//
// public JavaLogger(String tag) {
// logger = java.util.logging.Logger.getLogger(tag);
// }
//
// @Override
// public void log(Level level, String msg) {
// // TODO Replace logged method with caller method
// logger.log(level, msg);
// }
//
// @Override
// public void log(Level level, String msg, Throwable th) {
// // TODO Replace logged method with caller method
// logger.log(level, msg, th);
// }
//
// }
//
// class SystemOutLogger implements Logger {
//
// @Override
// public void log(Level level, String msg) {
// System.out.println("[" + level + "] " + msg);
// }
//
// @Override
// public void log(Level level, String msg, Throwable th) {
// System.out.println("[" + level + "] " + msg);
// th.printStackTrace(System.out);
// }
//
// }
//
// class Default {
// public static Logger get() {
// if (AndroidComponents.areAvailable()) {
// return AndroidComponents.get().logger;
// }
//
// return new SystemOutLogger();
// }
// }
//
// }
|
import org.greenrobot.eventbus.Logger;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
|
/*
* Copyright (C) 2012-2020 Markus Junginger, greenrobot (http://greenrobot.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.greenrobot.eventbus.util;
/**
* Maps throwables to texts for error dialogs. Use Config to configure the mapping.
*
* @author Markus
*/
public class ExceptionToResourceMapping {
public final Map<Class<? extends Throwable>, Integer> throwableToMsgIdMap;
public ExceptionToResourceMapping() {
throwableToMsgIdMap = new HashMap<>();
}
/** Looks at the exception and its causes trying to find an ID. */
public Integer mapThrowable(final Throwable throwable) {
Throwable throwableToCheck = throwable;
int depthToGo = 20;
while (true) {
Integer resId = mapThrowableFlat(throwableToCheck);
if (resId != null) {
return resId;
} else {
throwableToCheck = throwableToCheck.getCause();
depthToGo--;
if (depthToGo <= 0 || throwableToCheck == throwable || throwableToCheck == null) {
|
// Path: EventBus/src/org/greenrobot/eventbus/Logger.java
// public interface Logger {
//
// void log(Level level, String msg);
//
// void log(Level level, String msg, Throwable th);
//
// class JavaLogger implements Logger {
// protected final java.util.logging.Logger logger;
//
// public JavaLogger(String tag) {
// logger = java.util.logging.Logger.getLogger(tag);
// }
//
// @Override
// public void log(Level level, String msg) {
// // TODO Replace logged method with caller method
// logger.log(level, msg);
// }
//
// @Override
// public void log(Level level, String msg, Throwable th) {
// // TODO Replace logged method with caller method
// logger.log(level, msg, th);
// }
//
// }
//
// class SystemOutLogger implements Logger {
//
// @Override
// public void log(Level level, String msg) {
// System.out.println("[" + level + "] " + msg);
// }
//
// @Override
// public void log(Level level, String msg, Throwable th) {
// System.out.println("[" + level + "] " + msg);
// th.printStackTrace(System.out);
// }
//
// }
//
// class Default {
// public static Logger get() {
// if (AndroidComponents.areAvailable()) {
// return AndroidComponents.get().logger;
// }
//
// return new SystemOutLogger();
// }
// }
//
// }
// Path: EventBus/src/org/greenrobot/eventbus/util/ExceptionToResourceMapping.java
import org.greenrobot.eventbus.Logger;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
/*
* Copyright (C) 2012-2020 Markus Junginger, greenrobot (http://greenrobot.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.greenrobot.eventbus.util;
/**
* Maps throwables to texts for error dialogs. Use Config to configure the mapping.
*
* @author Markus
*/
public class ExceptionToResourceMapping {
public final Map<Class<? extends Throwable>, Integer> throwableToMsgIdMap;
public ExceptionToResourceMapping() {
throwableToMsgIdMap = new HashMap<>();
}
/** Looks at the exception and its causes trying to find an ID. */
public Integer mapThrowable(final Throwable throwable) {
Throwable throwableToCheck = throwable;
int depthToGo = 20;
while (true) {
Integer resId = mapThrowableFlat(throwableToCheck);
if (resId != null) {
return resId;
} else {
throwableToCheck = throwableToCheck.getCause();
depthToGo--;
if (depthToGo <= 0 || throwableToCheck == throwable || throwableToCheck == null) {
|
Logger logger = Logger.Default.get(); // No EventBus instance here
|
greenrobot/EventBus
|
EventBusPerformance/src/org/greenrobot/eventbusperf/testsubject/PerfTestOtto.java
|
// Path: EventBusPerformance/src/org/greenrobot/eventbusperf/Test.java
// public abstract class Test {
// protected final Context context;
// protected final TestParams params;
// public final AtomicLong eventsReceivedCount = new AtomicLong();
// protected long primaryResultMicros;
// protected int primaryResultCount;
// protected String otherTestResults;
//
// protected boolean canceled;
//
// public Test(Context context, TestParams params) {
// this.context = context;
// this.params = params;
// }
//
// public void cancel() {
// canceled = true;
// }
//
// /** prepares the test, all things which are not relevant for test results */
// public abstract void prepareTest();
//
// public abstract void runTest();
//
// /** returns the display name of the test. e.g. EventBus */
// public abstract String getDisplayName();
//
// protected void waitForReceivedEventCount(int expectedEventCount) {
// while (eventsReceivedCount.get() < expectedEventCount) {
// try {
// Thread.sleep(1);
// } catch (InterruptedException e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// public long getPrimaryResultMicros() {
// return primaryResultMicros;
// }
//
// public double getPrimaryResultRate() {
// return primaryResultCount / (primaryResultMicros / 1000000d);
// }
//
// public String getOtherTestResults() {
// return otherTestResults;
// }
//
// }
//
// Path: EventBusPerformance/src/org/greenrobot/eventbusperf/TestEvent.java
// public class TestEvent {
//
// }
|
import org.greenrobot.eventbusperf.TestEvent;
import org.greenrobot.eventbusperf.TestParams;
import android.app.Activity;
import android.content.Context;
import android.os.Looper;
import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import org.greenrobot.eventbusperf.Test;
|
subscriberClass = Subscriber.class;
}
@Override
public void prepareTest() {
Looper.prepare();
try {
Constructor<?> constructor = subscriberClass.getConstructor(PerfTestOtto.class);
for (int i = 0; i < params.getSubscriberCount(); i++) {
Object subscriber = constructor.newInstance(this);
subscribers.add(subscriber);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static class Post extends PerfTestOtto {
public Post(Context context, TestParams params) {
super(context, params);
}
@Override
public void prepareTest() {
super.prepareTest();
super.registerSubscribers();
}
public void runTest() {
|
// Path: EventBusPerformance/src/org/greenrobot/eventbusperf/Test.java
// public abstract class Test {
// protected final Context context;
// protected final TestParams params;
// public final AtomicLong eventsReceivedCount = new AtomicLong();
// protected long primaryResultMicros;
// protected int primaryResultCount;
// protected String otherTestResults;
//
// protected boolean canceled;
//
// public Test(Context context, TestParams params) {
// this.context = context;
// this.params = params;
// }
//
// public void cancel() {
// canceled = true;
// }
//
// /** prepares the test, all things which are not relevant for test results */
// public abstract void prepareTest();
//
// public abstract void runTest();
//
// /** returns the display name of the test. e.g. EventBus */
// public abstract String getDisplayName();
//
// protected void waitForReceivedEventCount(int expectedEventCount) {
// while (eventsReceivedCount.get() < expectedEventCount) {
// try {
// Thread.sleep(1);
// } catch (InterruptedException e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// public long getPrimaryResultMicros() {
// return primaryResultMicros;
// }
//
// public double getPrimaryResultRate() {
// return primaryResultCount / (primaryResultMicros / 1000000d);
// }
//
// public String getOtherTestResults() {
// return otherTestResults;
// }
//
// }
//
// Path: EventBusPerformance/src/org/greenrobot/eventbusperf/TestEvent.java
// public class TestEvent {
//
// }
// Path: EventBusPerformance/src/org/greenrobot/eventbusperf/testsubject/PerfTestOtto.java
import org.greenrobot.eventbusperf.TestEvent;
import org.greenrobot.eventbusperf.TestParams;
import android.app.Activity;
import android.content.Context;
import android.os.Looper;
import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import org.greenrobot.eventbusperf.Test;
subscriberClass = Subscriber.class;
}
@Override
public void prepareTest() {
Looper.prepare();
try {
Constructor<?> constructor = subscriberClass.getConstructor(PerfTestOtto.class);
for (int i = 0; i < params.getSubscriberCount(); i++) {
Object subscriber = constructor.newInstance(this);
subscribers.add(subscriber);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static class Post extends PerfTestOtto {
public Post(Context context, TestParams params) {
super(context, params);
}
@Override
public void prepareTest() {
super.prepareTest();
super.registerSubscribers();
}
public void runTest() {
|
TestEvent event = new TestEvent();
|
greenrobot/EventBus
|
EventBus/src/org/greenrobot/eventbus/Logger.java
|
// Path: EventBus/src/org/greenrobot/eventbus/android/AndroidComponents.java
// public abstract class AndroidComponents {
//
// private static final AndroidComponents implementation;
//
// static {
// implementation = AndroidDependenciesDetector.isAndroidSDKAvailable()
// ? AndroidDependenciesDetector.instantiateAndroidComponents()
// : null;
// }
//
// public static boolean areAvailable() {
// return implementation != null;
// }
//
// public static AndroidComponents get() {
// return implementation;
// }
//
// public final Logger logger;
// public final MainThreadSupport defaultMainThreadSupport;
//
// public AndroidComponents(Logger logger, MainThreadSupport defaultMainThreadSupport) {
// this.logger = logger;
// this.defaultMainThreadSupport = defaultMainThreadSupport;
// }
// }
|
import org.greenrobot.eventbus.android.AndroidComponents;
import java.util.logging.Level;
|
public void log(Level level, String msg) {
// TODO Replace logged method with caller method
logger.log(level, msg);
}
@Override
public void log(Level level, String msg, Throwable th) {
// TODO Replace logged method with caller method
logger.log(level, msg, th);
}
}
class SystemOutLogger implements Logger {
@Override
public void log(Level level, String msg) {
System.out.println("[" + level + "] " + msg);
}
@Override
public void log(Level level, String msg, Throwable th) {
System.out.println("[" + level + "] " + msg);
th.printStackTrace(System.out);
}
}
class Default {
public static Logger get() {
|
// Path: EventBus/src/org/greenrobot/eventbus/android/AndroidComponents.java
// public abstract class AndroidComponents {
//
// private static final AndroidComponents implementation;
//
// static {
// implementation = AndroidDependenciesDetector.isAndroidSDKAvailable()
// ? AndroidDependenciesDetector.instantiateAndroidComponents()
// : null;
// }
//
// public static boolean areAvailable() {
// return implementation != null;
// }
//
// public static AndroidComponents get() {
// return implementation;
// }
//
// public final Logger logger;
// public final MainThreadSupport defaultMainThreadSupport;
//
// public AndroidComponents(Logger logger, MainThreadSupport defaultMainThreadSupport) {
// this.logger = logger;
// this.defaultMainThreadSupport = defaultMainThreadSupport;
// }
// }
// Path: EventBus/src/org/greenrobot/eventbus/Logger.java
import org.greenrobot.eventbus.android.AndroidComponents;
import java.util.logging.Level;
public void log(Level level, String msg) {
// TODO Replace logged method with caller method
logger.log(level, msg);
}
@Override
public void log(Level level, String msg, Throwable th) {
// TODO Replace logged method with caller method
logger.log(level, msg, th);
}
}
class SystemOutLogger implements Logger {
@Override
public void log(Level level, String msg) {
System.out.println("[" + level + "] " + msg);
}
@Override
public void log(Level level, String msg, Throwable th) {
System.out.println("[" + level + "] " + msg);
th.printStackTrace(System.out);
}
}
class Default {
public static Logger get() {
|
if (AndroidComponents.areAvailable()) {
|
greenrobot/EventBus
|
EventBusAnnotationProcessor/src/org/greenrobot/eventbus/annotationprocessor/EventBusAnnotationProcessor.java
|
// Path: EventBus/src/org/greenrobot/eventbus/ThreadMode.java
// public enum ThreadMode {
// /**
// * This is the default. Subscriber will be called directly in the same thread, which is posting the event. Event delivery
// * implies the least overhead because it avoids thread switching completely. Thus, this is the recommended mode for
// * simple tasks that are known to complete in a very short time without requiring the main thread. Event handlers
// * using this mode must return quickly to avoid blocking the posting thread, which may be the main thread.
// */
// POSTING,
//
// /**
// * On Android, subscriber will be called in Android's main thread (UI thread). If the posting thread is
// * the main thread, subscriber methods will be called directly, blocking the posting thread. Otherwise the event
// * is queued for delivery (non-blocking). Subscribers using this mode must return quickly to avoid blocking the main thread.
// * <p>
// * If not on Android, behaves the same as {@link #POSTING}.
// */
// MAIN,
//
// /**
// * On Android, subscriber will be called in Android's main thread (UI thread). Different from {@link #MAIN},
// * the event will always be queued for delivery. This ensures that the post call is non-blocking.
// * <p>
// * If not on Android, behaves the same as {@link #POSTING}.
// */
// MAIN_ORDERED,
//
// /**
// * On Android, subscriber will be called in a background thread. If posting thread is not the main thread, subscriber methods
// * will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single
// * background thread, that will deliver all its events sequentially. Subscribers using this mode should try to
// * return quickly to avoid blocking the background thread.
// * <p>
// * If not on Android, always uses a background thread.
// */
// BACKGROUND,
//
// /**
// * Subscriber will be called in a separate thread. This is always independent of the posting thread and the
// * main thread. Posting events never wait for subscriber methods using this mode. Subscriber methods should
// * use this mode if their execution might take some time, e.g. for network access. Avoid triggering a large number
// * of long-running asynchronous subscriber methods at the same time to limit the number of concurrent threads. EventBus
// * uses a thread pool to efficiently reuse threads from completed asynchronous subscriber notifications.
// */
// ASYNC
// }
|
import net.ltgt.gradle.incap.IncrementalAnnotationProcessor;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import de.greenrobot.common.ListMap;
import static net.ltgt.gradle.incap.IncrementalAnnotationProcessorType.AGGREGATING;
|
// Don't use TypeElement.getSimpleName, it doesn't work for us with inner classes
return className.substring(paket.length() + 1);
} else {
// Paranoia
throw new IllegalStateException("Mismatching " + paket + " vs. " + className);
}
}
private PackageElement getPackageElement(TypeElement subscriberClass) {
Element candidate = subscriberClass.getEnclosingElement();
while (!(candidate instanceof PackageElement)) {
candidate = candidate.getEnclosingElement();
}
return (PackageElement) candidate;
}
private void writeCreateSubscriberMethods(BufferedWriter writer, List<ExecutableElement> methods,
String callPrefix, String myPackage) throws IOException {
for (ExecutableElement method : methods) {
List<? extends VariableElement> parameters = method.getParameters();
TypeMirror paramType = getParamTypeMirror(parameters.get(0), null);
TypeElement paramElement = (TypeElement) processingEnv.getTypeUtils().asElement(paramType);
String methodName = method.getSimpleName().toString();
String eventClass = getClassString(paramElement, myPackage) + ".class";
Subscribe subscribe = method.getAnnotation(Subscribe.class);
List<String> parts = new ArrayList<>();
parts.add(callPrefix + "(\"" + methodName + "\",");
String lineEnd = "),";
if (subscribe.priority() == 0 && !subscribe.sticky()) {
|
// Path: EventBus/src/org/greenrobot/eventbus/ThreadMode.java
// public enum ThreadMode {
// /**
// * This is the default. Subscriber will be called directly in the same thread, which is posting the event. Event delivery
// * implies the least overhead because it avoids thread switching completely. Thus, this is the recommended mode for
// * simple tasks that are known to complete in a very short time without requiring the main thread. Event handlers
// * using this mode must return quickly to avoid blocking the posting thread, which may be the main thread.
// */
// POSTING,
//
// /**
// * On Android, subscriber will be called in Android's main thread (UI thread). If the posting thread is
// * the main thread, subscriber methods will be called directly, blocking the posting thread. Otherwise the event
// * is queued for delivery (non-blocking). Subscribers using this mode must return quickly to avoid blocking the main thread.
// * <p>
// * If not on Android, behaves the same as {@link #POSTING}.
// */
// MAIN,
//
// /**
// * On Android, subscriber will be called in Android's main thread (UI thread). Different from {@link #MAIN},
// * the event will always be queued for delivery. This ensures that the post call is non-blocking.
// * <p>
// * If not on Android, behaves the same as {@link #POSTING}.
// */
// MAIN_ORDERED,
//
// /**
// * On Android, subscriber will be called in a background thread. If posting thread is not the main thread, subscriber methods
// * will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single
// * background thread, that will deliver all its events sequentially. Subscribers using this mode should try to
// * return quickly to avoid blocking the background thread.
// * <p>
// * If not on Android, always uses a background thread.
// */
// BACKGROUND,
//
// /**
// * Subscriber will be called in a separate thread. This is always independent of the posting thread and the
// * main thread. Posting events never wait for subscriber methods using this mode. Subscriber methods should
// * use this mode if their execution might take some time, e.g. for network access. Avoid triggering a large number
// * of long-running asynchronous subscriber methods at the same time to limit the number of concurrent threads. EventBus
// * uses a thread pool to efficiently reuse threads from completed asynchronous subscriber notifications.
// */
// ASYNC
// }
// Path: EventBusAnnotationProcessor/src/org/greenrobot/eventbus/annotationprocessor/EventBusAnnotationProcessor.java
import net.ltgt.gradle.incap.IncrementalAnnotationProcessor;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import de.greenrobot.common.ListMap;
import static net.ltgt.gradle.incap.IncrementalAnnotationProcessorType.AGGREGATING;
// Don't use TypeElement.getSimpleName, it doesn't work for us with inner classes
return className.substring(paket.length() + 1);
} else {
// Paranoia
throw new IllegalStateException("Mismatching " + paket + " vs. " + className);
}
}
private PackageElement getPackageElement(TypeElement subscriberClass) {
Element candidate = subscriberClass.getEnclosingElement();
while (!(candidate instanceof PackageElement)) {
candidate = candidate.getEnclosingElement();
}
return (PackageElement) candidate;
}
private void writeCreateSubscriberMethods(BufferedWriter writer, List<ExecutableElement> methods,
String callPrefix, String myPackage) throws IOException {
for (ExecutableElement method : methods) {
List<? extends VariableElement> parameters = method.getParameters();
TypeMirror paramType = getParamTypeMirror(parameters.get(0), null);
TypeElement paramElement = (TypeElement) processingEnv.getTypeUtils().asElement(paramType);
String methodName = method.getSimpleName().toString();
String eventClass = getClassString(paramElement, myPackage) + ".class";
Subscribe subscribe = method.getAnnotation(Subscribe.class);
List<String> parts = new ArrayList<>();
parts.add(callPrefix + "(\"" + methodName + "\",");
String lineEnd = "),";
if (subscribe.priority() == 0 && !subscribe.sticky()) {
|
if (subscribe.threadMode() == ThreadMode.POSTING) {
|
greenrobot/EventBus
|
EventBus/src/org/greenrobot/eventbus/android/AndroidComponents.java
|
// Path: EventBus/src/org/greenrobot/eventbus/Logger.java
// public interface Logger {
//
// void log(Level level, String msg);
//
// void log(Level level, String msg, Throwable th);
//
// class JavaLogger implements Logger {
// protected final java.util.logging.Logger logger;
//
// public JavaLogger(String tag) {
// logger = java.util.logging.Logger.getLogger(tag);
// }
//
// @Override
// public void log(Level level, String msg) {
// // TODO Replace logged method with caller method
// logger.log(level, msg);
// }
//
// @Override
// public void log(Level level, String msg, Throwable th) {
// // TODO Replace logged method with caller method
// logger.log(level, msg, th);
// }
//
// }
//
// class SystemOutLogger implements Logger {
//
// @Override
// public void log(Level level, String msg) {
// System.out.println("[" + level + "] " + msg);
// }
//
// @Override
// public void log(Level level, String msg, Throwable th) {
// System.out.println("[" + level + "] " + msg);
// th.printStackTrace(System.out);
// }
//
// }
//
// class Default {
// public static Logger get() {
// if (AndroidComponents.areAvailable()) {
// return AndroidComponents.get().logger;
// }
//
// return new SystemOutLogger();
// }
// }
//
// }
//
// Path: EventBus/src/org/greenrobot/eventbus/MainThreadSupport.java
// public interface MainThreadSupport {
//
// boolean isMainThread();
//
// Poster createPoster(EventBus eventBus);
// }
|
import org.greenrobot.eventbus.Logger;
import org.greenrobot.eventbus.MainThreadSupport;
|
package org.greenrobot.eventbus.android;
public abstract class AndroidComponents {
private static final AndroidComponents implementation;
static {
implementation = AndroidDependenciesDetector.isAndroidSDKAvailable()
? AndroidDependenciesDetector.instantiateAndroidComponents()
: null;
}
public static boolean areAvailable() {
return implementation != null;
}
public static AndroidComponents get() {
return implementation;
}
|
// Path: EventBus/src/org/greenrobot/eventbus/Logger.java
// public interface Logger {
//
// void log(Level level, String msg);
//
// void log(Level level, String msg, Throwable th);
//
// class JavaLogger implements Logger {
// protected final java.util.logging.Logger logger;
//
// public JavaLogger(String tag) {
// logger = java.util.logging.Logger.getLogger(tag);
// }
//
// @Override
// public void log(Level level, String msg) {
// // TODO Replace logged method with caller method
// logger.log(level, msg);
// }
//
// @Override
// public void log(Level level, String msg, Throwable th) {
// // TODO Replace logged method with caller method
// logger.log(level, msg, th);
// }
//
// }
//
// class SystemOutLogger implements Logger {
//
// @Override
// public void log(Level level, String msg) {
// System.out.println("[" + level + "] " + msg);
// }
//
// @Override
// public void log(Level level, String msg, Throwable th) {
// System.out.println("[" + level + "] " + msg);
// th.printStackTrace(System.out);
// }
//
// }
//
// class Default {
// public static Logger get() {
// if (AndroidComponents.areAvailable()) {
// return AndroidComponents.get().logger;
// }
//
// return new SystemOutLogger();
// }
// }
//
// }
//
// Path: EventBus/src/org/greenrobot/eventbus/MainThreadSupport.java
// public interface MainThreadSupport {
//
// boolean isMainThread();
//
// Poster createPoster(EventBus eventBus);
// }
// Path: EventBus/src/org/greenrobot/eventbus/android/AndroidComponents.java
import org.greenrobot.eventbus.Logger;
import org.greenrobot.eventbus.MainThreadSupport;
package org.greenrobot.eventbus.android;
public abstract class AndroidComponents {
private static final AndroidComponents implementation;
static {
implementation = AndroidDependenciesDetector.isAndroidSDKAvailable()
? AndroidDependenciesDetector.instantiateAndroidComponents()
: null;
}
public static boolean areAvailable() {
return implementation != null;
}
public static AndroidComponents get() {
return implementation;
}
|
public final Logger logger;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.