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
|
|---|---|---|---|---|---|---|
jvdb/derric
|
src/org/derric_lang/validator/interpreter/structure/Decl.java
|
// Path: src/org/derric_lang/validator/ValidatorInputStream.java
// public abstract class ValidatorInputStream extends InputStream {
//
// public abstract boolean isByteAligned();
// public abstract boolean atEOF() throws IOException;
//
// public abstract long lastLocation();
// public abstract long lastRead();
// public abstract void mark();
// public abstract void reset() throws IOException;
//
// public abstract boolean skipBits(long bits) throws IOException;
// public abstract long skip(long bytes) throws IOException;
//
// public abstract ValidatorInputStream bitOrder(BitOrder order);
// public abstract ValidatorInputStream byteOrder(ByteOrder order);
// public abstract ValidatorInputStream signed();
// public abstract ValidatorInputStream unsigned();
// public abstract long readInteger(long bits) throws IOException;
//
// public abstract ValidatorInputStream includeMarker(boolean includeMarker);
// public abstract Content readUntil(long bits, ValueSet values) throws IOException;
//
// public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException;
// }
//
// Path: src/org/derric_lang/validator/interpreter/Sentence.java
// public class Sentence {
//
// private final URI _inputFile;
//
// private String _structureName;
// private ISourceLocation _sequenceLocation;
// private ISourceLocation _structureLocation;
// private ISourceLocation _inputLocation;
//
// private List<StructureMatch> _matches;
// private List<StructureMatch> _sub;
// private List<FieldMatch> _fields;
//
// public Sentence(URI inputFile) {
// _inputFile = inputFile;
// _matches = new ArrayList<StructureMatch>();
// _sub = new ArrayList<StructureMatch>();
// _fields = new ArrayList<FieldMatch>();
// }
//
// public void setStructureName(String name) {
// _structureName = name;
// }
//
// public void setSequenceLocation(ISourceLocation location) {
// _sequenceLocation = location;
// }
//
// public void setStructureLocation(ISourceLocation location) {
// _structureLocation = location;
// }
//
// public void setStructureInputLocation(int offset, int length) {
// _inputLocation = new SourceLocation(_inputFile, offset, length);
// }
//
// public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) {
// boolean dup = false;
// int index = 0;
// for (int i = 0; i < _fields.size(); i++) {
// if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) {
// dup = true;
// index = i;
// String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name;
// int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset();
// int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset;
// FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength));
// _fields.add(index, fm);
// _fields.remove(index + 1);
// break;
// }
// }
// if (!dup) {
// _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length)));
// }
// }
//
// public void subMatch() {
// List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>();
// fieldMatches.addAll(_fields);
// _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches));
// _fields.clear();
// }
//
// public void fullMatch() {
// _matches.addAll(_sub);
// clearSub();
// }
//
// public void clearSub() {
// _sub.clear();
// _fields.clear();
// }
//
// @Override
// public String toString() {
// String out = "";
// boolean first = true;
// for (StructureMatch s : _matches) {
// if (first) {
// first = false;
// } else {
// out += " ";
// }
// out += s.name;
// }
// return out;
// }
//
// public List<StructureMatch> getMatches() {
// return _matches;
// }
//
// }
|
import java.util.Map;
import org.derric_lang.validator.ValidatorInputStream;
import org.derric_lang.validator.interpreter.Sentence;
|
package org.derric_lang.validator.interpreter.structure;
public abstract class Decl extends Statement {
private final String _name;
protected final Type _type;
protected Decl(String name, Type type) {
_name = name;
_type = type;
}
public String getName() {
return _name;
}
public Type getType() {
return _type;
}
|
// Path: src/org/derric_lang/validator/ValidatorInputStream.java
// public abstract class ValidatorInputStream extends InputStream {
//
// public abstract boolean isByteAligned();
// public abstract boolean atEOF() throws IOException;
//
// public abstract long lastLocation();
// public abstract long lastRead();
// public abstract void mark();
// public abstract void reset() throws IOException;
//
// public abstract boolean skipBits(long bits) throws IOException;
// public abstract long skip(long bytes) throws IOException;
//
// public abstract ValidatorInputStream bitOrder(BitOrder order);
// public abstract ValidatorInputStream byteOrder(ByteOrder order);
// public abstract ValidatorInputStream signed();
// public abstract ValidatorInputStream unsigned();
// public abstract long readInteger(long bits) throws IOException;
//
// public abstract ValidatorInputStream includeMarker(boolean includeMarker);
// public abstract Content readUntil(long bits, ValueSet values) throws IOException;
//
// public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException;
// }
//
// Path: src/org/derric_lang/validator/interpreter/Sentence.java
// public class Sentence {
//
// private final URI _inputFile;
//
// private String _structureName;
// private ISourceLocation _sequenceLocation;
// private ISourceLocation _structureLocation;
// private ISourceLocation _inputLocation;
//
// private List<StructureMatch> _matches;
// private List<StructureMatch> _sub;
// private List<FieldMatch> _fields;
//
// public Sentence(URI inputFile) {
// _inputFile = inputFile;
// _matches = new ArrayList<StructureMatch>();
// _sub = new ArrayList<StructureMatch>();
// _fields = new ArrayList<FieldMatch>();
// }
//
// public void setStructureName(String name) {
// _structureName = name;
// }
//
// public void setSequenceLocation(ISourceLocation location) {
// _sequenceLocation = location;
// }
//
// public void setStructureLocation(ISourceLocation location) {
// _structureLocation = location;
// }
//
// public void setStructureInputLocation(int offset, int length) {
// _inputLocation = new SourceLocation(_inputFile, offset, length);
// }
//
// public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) {
// boolean dup = false;
// int index = 0;
// for (int i = 0; i < _fields.size(); i++) {
// if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) {
// dup = true;
// index = i;
// String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name;
// int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset();
// int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset;
// FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength));
// _fields.add(index, fm);
// _fields.remove(index + 1);
// break;
// }
// }
// if (!dup) {
// _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length)));
// }
// }
//
// public void subMatch() {
// List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>();
// fieldMatches.addAll(_fields);
// _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches));
// _fields.clear();
// }
//
// public void fullMatch() {
// _matches.addAll(_sub);
// clearSub();
// }
//
// public void clearSub() {
// _sub.clear();
// _fields.clear();
// }
//
// @Override
// public String toString() {
// String out = "";
// boolean first = true;
// for (StructureMatch s : _matches) {
// if (first) {
// first = false;
// } else {
// out += " ";
// }
// out += s.name;
// }
// return out;
// }
//
// public List<StructureMatch> getMatches() {
// return _matches;
// }
//
// }
// Path: src/org/derric_lang/validator/interpreter/structure/Decl.java
import java.util.Map;
import org.derric_lang.validator.ValidatorInputStream;
import org.derric_lang.validator.interpreter.Sentence;
package org.derric_lang.validator.interpreter.structure;
public abstract class Decl extends Statement {
private final String _name;
protected final Type _type;
protected Decl(String name, Type type) {
_name = name;
_type = type;
}
public String getName() {
return _name;
}
public Type getType() {
return _type;
}
|
public boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) {
|
jvdb/derric
|
src/org/derric_lang/validator/interpreter/structure/Decl.java
|
// Path: src/org/derric_lang/validator/ValidatorInputStream.java
// public abstract class ValidatorInputStream extends InputStream {
//
// public abstract boolean isByteAligned();
// public abstract boolean atEOF() throws IOException;
//
// public abstract long lastLocation();
// public abstract long lastRead();
// public abstract void mark();
// public abstract void reset() throws IOException;
//
// public abstract boolean skipBits(long bits) throws IOException;
// public abstract long skip(long bytes) throws IOException;
//
// public abstract ValidatorInputStream bitOrder(BitOrder order);
// public abstract ValidatorInputStream byteOrder(ByteOrder order);
// public abstract ValidatorInputStream signed();
// public abstract ValidatorInputStream unsigned();
// public abstract long readInteger(long bits) throws IOException;
//
// public abstract ValidatorInputStream includeMarker(boolean includeMarker);
// public abstract Content readUntil(long bits, ValueSet values) throws IOException;
//
// public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException;
// }
//
// Path: src/org/derric_lang/validator/interpreter/Sentence.java
// public class Sentence {
//
// private final URI _inputFile;
//
// private String _structureName;
// private ISourceLocation _sequenceLocation;
// private ISourceLocation _structureLocation;
// private ISourceLocation _inputLocation;
//
// private List<StructureMatch> _matches;
// private List<StructureMatch> _sub;
// private List<FieldMatch> _fields;
//
// public Sentence(URI inputFile) {
// _inputFile = inputFile;
// _matches = new ArrayList<StructureMatch>();
// _sub = new ArrayList<StructureMatch>();
// _fields = new ArrayList<FieldMatch>();
// }
//
// public void setStructureName(String name) {
// _structureName = name;
// }
//
// public void setSequenceLocation(ISourceLocation location) {
// _sequenceLocation = location;
// }
//
// public void setStructureLocation(ISourceLocation location) {
// _structureLocation = location;
// }
//
// public void setStructureInputLocation(int offset, int length) {
// _inputLocation = new SourceLocation(_inputFile, offset, length);
// }
//
// public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) {
// boolean dup = false;
// int index = 0;
// for (int i = 0; i < _fields.size(); i++) {
// if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) {
// dup = true;
// index = i;
// String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name;
// int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset();
// int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset;
// FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength));
// _fields.add(index, fm);
// _fields.remove(index + 1);
// break;
// }
// }
// if (!dup) {
// _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length)));
// }
// }
//
// public void subMatch() {
// List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>();
// fieldMatches.addAll(_fields);
// _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches));
// _fields.clear();
// }
//
// public void fullMatch() {
// _matches.addAll(_sub);
// clearSub();
// }
//
// public void clearSub() {
// _sub.clear();
// _fields.clear();
// }
//
// @Override
// public String toString() {
// String out = "";
// boolean first = true;
// for (StructureMatch s : _matches) {
// if (first) {
// first = false;
// } else {
// out += " ";
// }
// out += s.name;
// }
// return out;
// }
//
// public List<StructureMatch> getMatches() {
// return _matches;
// }
//
// }
|
import java.util.Map;
import org.derric_lang.validator.ValidatorInputStream;
import org.derric_lang.validator.interpreter.Sentence;
|
package org.derric_lang.validator.interpreter.structure;
public abstract class Decl extends Statement {
private final String _name;
protected final Type _type;
protected Decl(String name, Type type) {
_name = name;
_type = type;
}
public String getName() {
return _name;
}
public Type getType() {
return _type;
}
|
// Path: src/org/derric_lang/validator/ValidatorInputStream.java
// public abstract class ValidatorInputStream extends InputStream {
//
// public abstract boolean isByteAligned();
// public abstract boolean atEOF() throws IOException;
//
// public abstract long lastLocation();
// public abstract long lastRead();
// public abstract void mark();
// public abstract void reset() throws IOException;
//
// public abstract boolean skipBits(long bits) throws IOException;
// public abstract long skip(long bytes) throws IOException;
//
// public abstract ValidatorInputStream bitOrder(BitOrder order);
// public abstract ValidatorInputStream byteOrder(ByteOrder order);
// public abstract ValidatorInputStream signed();
// public abstract ValidatorInputStream unsigned();
// public abstract long readInteger(long bits) throws IOException;
//
// public abstract ValidatorInputStream includeMarker(boolean includeMarker);
// public abstract Content readUntil(long bits, ValueSet values) throws IOException;
//
// public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException;
// }
//
// Path: src/org/derric_lang/validator/interpreter/Sentence.java
// public class Sentence {
//
// private final URI _inputFile;
//
// private String _structureName;
// private ISourceLocation _sequenceLocation;
// private ISourceLocation _structureLocation;
// private ISourceLocation _inputLocation;
//
// private List<StructureMatch> _matches;
// private List<StructureMatch> _sub;
// private List<FieldMatch> _fields;
//
// public Sentence(URI inputFile) {
// _inputFile = inputFile;
// _matches = new ArrayList<StructureMatch>();
// _sub = new ArrayList<StructureMatch>();
// _fields = new ArrayList<FieldMatch>();
// }
//
// public void setStructureName(String name) {
// _structureName = name;
// }
//
// public void setSequenceLocation(ISourceLocation location) {
// _sequenceLocation = location;
// }
//
// public void setStructureLocation(ISourceLocation location) {
// _structureLocation = location;
// }
//
// public void setStructureInputLocation(int offset, int length) {
// _inputLocation = new SourceLocation(_inputFile, offset, length);
// }
//
// public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) {
// boolean dup = false;
// int index = 0;
// for (int i = 0; i < _fields.size(); i++) {
// if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) {
// dup = true;
// index = i;
// String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name;
// int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset();
// int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset;
// FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength));
// _fields.add(index, fm);
// _fields.remove(index + 1);
// break;
// }
// }
// if (!dup) {
// _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length)));
// }
// }
//
// public void subMatch() {
// List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>();
// fieldMatches.addAll(_fields);
// _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches));
// _fields.clear();
// }
//
// public void fullMatch() {
// _matches.addAll(_sub);
// clearSub();
// }
//
// public void clearSub() {
// _sub.clear();
// _fields.clear();
// }
//
// @Override
// public String toString() {
// String out = "";
// boolean first = true;
// for (StructureMatch s : _matches) {
// if (first) {
// first = false;
// } else {
// out += " ";
// }
// out += s.name;
// }
// return out;
// }
//
// public List<StructureMatch> getMatches() {
// return _matches;
// }
//
// }
// Path: src/org/derric_lang/validator/interpreter/structure/Decl.java
import java.util.Map;
import org.derric_lang.validator.ValidatorInputStream;
import org.derric_lang.validator.interpreter.Sentence;
package org.derric_lang.validator.interpreter.structure;
public abstract class Decl extends Statement {
private final String _name;
protected final Type _type;
protected Decl(String name, Type type) {
_name = name;
_type = type;
}
public String getName() {
return _name;
}
public Type getType() {
return _type;
}
|
public boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) {
|
jvdb/derric
|
src/org/derric_lang/validator/interpreter/structure/Calc.java
|
// Path: src/org/derric_lang/validator/ValidatorInputStream.java
// public abstract class ValidatorInputStream extends InputStream {
//
// public abstract boolean isByteAligned();
// public abstract boolean atEOF() throws IOException;
//
// public abstract long lastLocation();
// public abstract long lastRead();
// public abstract void mark();
// public abstract void reset() throws IOException;
//
// public abstract boolean skipBits(long bits) throws IOException;
// public abstract long skip(long bytes) throws IOException;
//
// public abstract ValidatorInputStream bitOrder(BitOrder order);
// public abstract ValidatorInputStream byteOrder(ByteOrder order);
// public abstract ValidatorInputStream signed();
// public abstract ValidatorInputStream unsigned();
// public abstract long readInteger(long bits) throws IOException;
//
// public abstract ValidatorInputStream includeMarker(boolean includeMarker);
// public abstract Content readUntil(long bits, ValueSet values) throws IOException;
//
// public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException;
// }
//
// Path: src/org/derric_lang/validator/interpreter/Sentence.java
// public class Sentence {
//
// private final URI _inputFile;
//
// private String _structureName;
// private ISourceLocation _sequenceLocation;
// private ISourceLocation _structureLocation;
// private ISourceLocation _inputLocation;
//
// private List<StructureMatch> _matches;
// private List<StructureMatch> _sub;
// private List<FieldMatch> _fields;
//
// public Sentence(URI inputFile) {
// _inputFile = inputFile;
// _matches = new ArrayList<StructureMatch>();
// _sub = new ArrayList<StructureMatch>();
// _fields = new ArrayList<FieldMatch>();
// }
//
// public void setStructureName(String name) {
// _structureName = name;
// }
//
// public void setSequenceLocation(ISourceLocation location) {
// _sequenceLocation = location;
// }
//
// public void setStructureLocation(ISourceLocation location) {
// _structureLocation = location;
// }
//
// public void setStructureInputLocation(int offset, int length) {
// _inputLocation = new SourceLocation(_inputFile, offset, length);
// }
//
// public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) {
// boolean dup = false;
// int index = 0;
// for (int i = 0; i < _fields.size(); i++) {
// if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) {
// dup = true;
// index = i;
// String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name;
// int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset();
// int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset;
// FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength));
// _fields.add(index, fm);
// _fields.remove(index + 1);
// break;
// }
// }
// if (!dup) {
// _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length)));
// }
// }
//
// public void subMatch() {
// List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>();
// fieldMatches.addAll(_fields);
// _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches));
// _fields.clear();
// }
//
// public void fullMatch() {
// _matches.addAll(_sub);
// clearSub();
// }
//
// public void clearSub() {
// _sub.clear();
// _fields.clear();
// }
//
// @Override
// public String toString() {
// String out = "";
// boolean first = true;
// for (StructureMatch s : _matches) {
// if (first) {
// first = false;
// } else {
// out += " ";
// }
// out += s.name;
// }
// return out;
// }
//
// public List<StructureMatch> getMatches() {
// return _matches;
// }
//
// }
|
import java.util.Map;
import org.derric_lang.validator.ValidatorInputStream;
import org.derric_lang.validator.interpreter.Sentence;
|
package org.derric_lang.validator.interpreter.structure;
public class Calc extends Statement {
private final String _name;
private final ValueExpression _exp;
public Calc(String name, ValueExpression exp) {
_name = name;
_exp = exp;
}
@Override
|
// Path: src/org/derric_lang/validator/ValidatorInputStream.java
// public abstract class ValidatorInputStream extends InputStream {
//
// public abstract boolean isByteAligned();
// public abstract boolean atEOF() throws IOException;
//
// public abstract long lastLocation();
// public abstract long lastRead();
// public abstract void mark();
// public abstract void reset() throws IOException;
//
// public abstract boolean skipBits(long bits) throws IOException;
// public abstract long skip(long bytes) throws IOException;
//
// public abstract ValidatorInputStream bitOrder(BitOrder order);
// public abstract ValidatorInputStream byteOrder(ByteOrder order);
// public abstract ValidatorInputStream signed();
// public abstract ValidatorInputStream unsigned();
// public abstract long readInteger(long bits) throws IOException;
//
// public abstract ValidatorInputStream includeMarker(boolean includeMarker);
// public abstract Content readUntil(long bits, ValueSet values) throws IOException;
//
// public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException;
// }
//
// Path: src/org/derric_lang/validator/interpreter/Sentence.java
// public class Sentence {
//
// private final URI _inputFile;
//
// private String _structureName;
// private ISourceLocation _sequenceLocation;
// private ISourceLocation _structureLocation;
// private ISourceLocation _inputLocation;
//
// private List<StructureMatch> _matches;
// private List<StructureMatch> _sub;
// private List<FieldMatch> _fields;
//
// public Sentence(URI inputFile) {
// _inputFile = inputFile;
// _matches = new ArrayList<StructureMatch>();
// _sub = new ArrayList<StructureMatch>();
// _fields = new ArrayList<FieldMatch>();
// }
//
// public void setStructureName(String name) {
// _structureName = name;
// }
//
// public void setSequenceLocation(ISourceLocation location) {
// _sequenceLocation = location;
// }
//
// public void setStructureLocation(ISourceLocation location) {
// _structureLocation = location;
// }
//
// public void setStructureInputLocation(int offset, int length) {
// _inputLocation = new SourceLocation(_inputFile, offset, length);
// }
//
// public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) {
// boolean dup = false;
// int index = 0;
// for (int i = 0; i < _fields.size(); i++) {
// if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) {
// dup = true;
// index = i;
// String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name;
// int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset();
// int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset;
// FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength));
// _fields.add(index, fm);
// _fields.remove(index + 1);
// break;
// }
// }
// if (!dup) {
// _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length)));
// }
// }
//
// public void subMatch() {
// List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>();
// fieldMatches.addAll(_fields);
// _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches));
// _fields.clear();
// }
//
// public void fullMatch() {
// _matches.addAll(_sub);
// clearSub();
// }
//
// public void clearSub() {
// _sub.clear();
// _fields.clear();
// }
//
// @Override
// public String toString() {
// String out = "";
// boolean first = true;
// for (StructureMatch s : _matches) {
// if (first) {
// first = false;
// } else {
// out += " ";
// }
// out += s.name;
// }
// return out;
// }
//
// public List<StructureMatch> getMatches() {
// return _matches;
// }
//
// }
// Path: src/org/derric_lang/validator/interpreter/structure/Calc.java
import java.util.Map;
import org.derric_lang.validator.ValidatorInputStream;
import org.derric_lang.validator.interpreter.Sentence;
package org.derric_lang.validator.interpreter.structure;
public class Calc extends Statement {
private final String _name;
private final ValueExpression _exp;
public Calc(String name, ValueExpression exp) {
_name = name;
_exp = exp;
}
@Override
|
public boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) {
|
jvdb/derric
|
src/org/derric_lang/validator/interpreter/structure/Calc.java
|
// Path: src/org/derric_lang/validator/ValidatorInputStream.java
// public abstract class ValidatorInputStream extends InputStream {
//
// public abstract boolean isByteAligned();
// public abstract boolean atEOF() throws IOException;
//
// public abstract long lastLocation();
// public abstract long lastRead();
// public abstract void mark();
// public abstract void reset() throws IOException;
//
// public abstract boolean skipBits(long bits) throws IOException;
// public abstract long skip(long bytes) throws IOException;
//
// public abstract ValidatorInputStream bitOrder(BitOrder order);
// public abstract ValidatorInputStream byteOrder(ByteOrder order);
// public abstract ValidatorInputStream signed();
// public abstract ValidatorInputStream unsigned();
// public abstract long readInteger(long bits) throws IOException;
//
// public abstract ValidatorInputStream includeMarker(boolean includeMarker);
// public abstract Content readUntil(long bits, ValueSet values) throws IOException;
//
// public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException;
// }
//
// Path: src/org/derric_lang/validator/interpreter/Sentence.java
// public class Sentence {
//
// private final URI _inputFile;
//
// private String _structureName;
// private ISourceLocation _sequenceLocation;
// private ISourceLocation _structureLocation;
// private ISourceLocation _inputLocation;
//
// private List<StructureMatch> _matches;
// private List<StructureMatch> _sub;
// private List<FieldMatch> _fields;
//
// public Sentence(URI inputFile) {
// _inputFile = inputFile;
// _matches = new ArrayList<StructureMatch>();
// _sub = new ArrayList<StructureMatch>();
// _fields = new ArrayList<FieldMatch>();
// }
//
// public void setStructureName(String name) {
// _structureName = name;
// }
//
// public void setSequenceLocation(ISourceLocation location) {
// _sequenceLocation = location;
// }
//
// public void setStructureLocation(ISourceLocation location) {
// _structureLocation = location;
// }
//
// public void setStructureInputLocation(int offset, int length) {
// _inputLocation = new SourceLocation(_inputFile, offset, length);
// }
//
// public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) {
// boolean dup = false;
// int index = 0;
// for (int i = 0; i < _fields.size(); i++) {
// if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) {
// dup = true;
// index = i;
// String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name;
// int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset();
// int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset;
// FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength));
// _fields.add(index, fm);
// _fields.remove(index + 1);
// break;
// }
// }
// if (!dup) {
// _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length)));
// }
// }
//
// public void subMatch() {
// List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>();
// fieldMatches.addAll(_fields);
// _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches));
// _fields.clear();
// }
//
// public void fullMatch() {
// _matches.addAll(_sub);
// clearSub();
// }
//
// public void clearSub() {
// _sub.clear();
// _fields.clear();
// }
//
// @Override
// public String toString() {
// String out = "";
// boolean first = true;
// for (StructureMatch s : _matches) {
// if (first) {
// first = false;
// } else {
// out += " ";
// }
// out += s.name;
// }
// return out;
// }
//
// public List<StructureMatch> getMatches() {
// return _matches;
// }
//
// }
|
import java.util.Map;
import org.derric_lang.validator.ValidatorInputStream;
import org.derric_lang.validator.interpreter.Sentence;
|
package org.derric_lang.validator.interpreter.structure;
public class Calc extends Statement {
private final String _name;
private final ValueExpression _exp;
public Calc(String name, ValueExpression exp) {
_name = name;
_exp = exp;
}
@Override
|
// Path: src/org/derric_lang/validator/ValidatorInputStream.java
// public abstract class ValidatorInputStream extends InputStream {
//
// public abstract boolean isByteAligned();
// public abstract boolean atEOF() throws IOException;
//
// public abstract long lastLocation();
// public abstract long lastRead();
// public abstract void mark();
// public abstract void reset() throws IOException;
//
// public abstract boolean skipBits(long bits) throws IOException;
// public abstract long skip(long bytes) throws IOException;
//
// public abstract ValidatorInputStream bitOrder(BitOrder order);
// public abstract ValidatorInputStream byteOrder(ByteOrder order);
// public abstract ValidatorInputStream signed();
// public abstract ValidatorInputStream unsigned();
// public abstract long readInteger(long bits) throws IOException;
//
// public abstract ValidatorInputStream includeMarker(boolean includeMarker);
// public abstract Content readUntil(long bits, ValueSet values) throws IOException;
//
// public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException;
// }
//
// Path: src/org/derric_lang/validator/interpreter/Sentence.java
// public class Sentence {
//
// private final URI _inputFile;
//
// private String _structureName;
// private ISourceLocation _sequenceLocation;
// private ISourceLocation _structureLocation;
// private ISourceLocation _inputLocation;
//
// private List<StructureMatch> _matches;
// private List<StructureMatch> _sub;
// private List<FieldMatch> _fields;
//
// public Sentence(URI inputFile) {
// _inputFile = inputFile;
// _matches = new ArrayList<StructureMatch>();
// _sub = new ArrayList<StructureMatch>();
// _fields = new ArrayList<FieldMatch>();
// }
//
// public void setStructureName(String name) {
// _structureName = name;
// }
//
// public void setSequenceLocation(ISourceLocation location) {
// _sequenceLocation = location;
// }
//
// public void setStructureLocation(ISourceLocation location) {
// _structureLocation = location;
// }
//
// public void setStructureInputLocation(int offset, int length) {
// _inputLocation = new SourceLocation(_inputFile, offset, length);
// }
//
// public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) {
// boolean dup = false;
// int index = 0;
// for (int i = 0; i < _fields.size(); i++) {
// if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) {
// dup = true;
// index = i;
// String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name;
// int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset();
// int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset;
// FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength));
// _fields.add(index, fm);
// _fields.remove(index + 1);
// break;
// }
// }
// if (!dup) {
// _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length)));
// }
// }
//
// public void subMatch() {
// List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>();
// fieldMatches.addAll(_fields);
// _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches));
// _fields.clear();
// }
//
// public void fullMatch() {
// _matches.addAll(_sub);
// clearSub();
// }
//
// public void clearSub() {
// _sub.clear();
// _fields.clear();
// }
//
// @Override
// public String toString() {
// String out = "";
// boolean first = true;
// for (StructureMatch s : _matches) {
// if (first) {
// first = false;
// } else {
// out += " ";
// }
// out += s.name;
// }
// return out;
// }
//
// public List<StructureMatch> getMatches() {
// return _matches;
// }
//
// }
// Path: src/org/derric_lang/validator/interpreter/structure/Calc.java
import java.util.Map;
import org.derric_lang.validator.ValidatorInputStream;
import org.derric_lang.validator.interpreter.Sentence;
package org.derric_lang.validator.interpreter.structure;
public class Calc extends Statement {
private final String _name;
private final ValueExpression _exp;
public Calc(String name, ValueExpression exp) {
_name = name;
_exp = exp;
}
@Override
|
public boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) {
|
jvdb/derric
|
src/org/derric_lang/validator/interpreter/structure/Range.java
|
// Path: src/org/derric_lang/validator/ValueSet.java
// public class ValueSet implements ValueComparer {
//
// private ArrayList<ValueComparer> _values = new ArrayList<ValueComparer>();
//
// public void addEquals(long value) {
// _values.add(new Value(value, true));
// }
//
// public void addNot(long value) {
// _values.add(new Value(value, false));
// }
//
// public void addEquals(long lower, long upper) {
// _values.add(new Range(lower, upper, true));
// }
//
// public void addNot(long lower, long upper) {
// _values.add(new Range(lower, upper, false));
// }
//
// @Override
// public boolean equals(long value) {
// for (ValueComparer vc : _values) {
// if (vc.equals(value))
// return true;
// }
// return false;
// }
//
// class Value implements ValueComparer {
// public long value;
// public boolean equals;
//
// public Value(long value, boolean equals) {
// this.value = value;
// this.equals = equals;
// }
//
// @Override
// public boolean equals(long value) {
// return (this.value == value) == equals;
// }
// }
//
// class Range implements ValueComparer {
// public long lower;
// public long upper;
// public boolean equals;
//
// public Range(long lower, long upper, boolean equals) {
// this.lower = lower;
// this.upper = upper;
// this.equals = equals;
// }
//
// @Override
// public boolean equals(long value) {
// return (lower <= value && upper >= value) == equals;
// }
// }
// }
|
import java.util.Map;
import org.derric_lang.validator.ValueSet;
|
package org.derric_lang.validator.interpreter.structure;
public class Range extends ValueSetExpression {
private final ValueExpression _lower;
private final ValueExpression _upper;
public Range(ValueExpression lower, ValueExpression upper) {
_lower = lower;
_upper = upper;
}
public ValueExpression getLower() {
return _lower;
}
public ValueExpression getUpper() {
return _upper;
}
@Override
|
// Path: src/org/derric_lang/validator/ValueSet.java
// public class ValueSet implements ValueComparer {
//
// private ArrayList<ValueComparer> _values = new ArrayList<ValueComparer>();
//
// public void addEquals(long value) {
// _values.add(new Value(value, true));
// }
//
// public void addNot(long value) {
// _values.add(new Value(value, false));
// }
//
// public void addEquals(long lower, long upper) {
// _values.add(new Range(lower, upper, true));
// }
//
// public void addNot(long lower, long upper) {
// _values.add(new Range(lower, upper, false));
// }
//
// @Override
// public boolean equals(long value) {
// for (ValueComparer vc : _values) {
// if (vc.equals(value))
// return true;
// }
// return false;
// }
//
// class Value implements ValueComparer {
// public long value;
// public boolean equals;
//
// public Value(long value, boolean equals) {
// this.value = value;
// this.equals = equals;
// }
//
// @Override
// public boolean equals(long value) {
// return (this.value == value) == equals;
// }
// }
//
// class Range implements ValueComparer {
// public long lower;
// public long upper;
// public boolean equals;
//
// public Range(long lower, long upper, boolean equals) {
// this.lower = lower;
// this.upper = upper;
// this.equals = equals;
// }
//
// @Override
// public boolean equals(long value) {
// return (lower <= value && upper >= value) == equals;
// }
// }
// }
// Path: src/org/derric_lang/validator/interpreter/structure/Range.java
import java.util.Map;
import org.derric_lang.validator.ValueSet;
package org.derric_lang.validator.interpreter.structure;
public class Range extends ValueSetExpression {
private final ValueExpression _lower;
private final ValueExpression _upper;
public Range(ValueExpression lower, ValueExpression upper) {
_lower = lower;
_upper = upper;
}
public ValueExpression getLower() {
return _lower;
}
public ValueExpression getUpper() {
return _upper;
}
@Override
|
public ValueSet eval(ValueSet vs, Map<String, Type> globals, Map<String, Type> locals) {
|
jvdb/derric
|
src/org/derric_lang/validator/interpreter/symbol/Term.java
|
// Path: src/org/derric_lang/validator/interpreter/Interpreter.java
// public class Interpreter extends Validator {
//
// private final String _format;
// private final List<Symbol> _sequence;
// private final List<Structure> _structures;
// private final Map<String, Type> _globals;
//
// private Sentence _current;
// private URI _inputFile;
//
// public Interpreter(URI inputFile, String format, List<Symbol> sequence, List<Structure> structures, List<Decl> globals) {
// super(format);
// _inputFile = inputFile;
// _format = format;
// _sequence = sequence;
// _structures = structures;
// _globals = new HashMap<String, Type>();
// for (Decl d : globals) {
// _globals.put(d.getName(), d.getType());
// }
// setStream(ValidatorInputStreamFactory.create(_inputFile));
// }
//
// @Override
// public String getExtension() {
// return _format;
// }
//
// @Override
// protected ParseResult tryParseBody() throws IOException {
// _current = new Sentence(_inputFile);
// for (Symbol s : _sequence) {
// if (!s.parse(this)) {
// return new ParseResult(false, _input.lastLocation(), _input.lastRead(), s.toString(), _current.toString());
// }
// _current.fullMatch();
// //System.out.println("Validated " + s.toString());
// }
// return new ParseResult(true, _input.lastLocation(), _input.lastRead(), "", _current.toString());
// }
//
// @Override
// public ParseResult findNextFooter() throws IOException {
// return null;
// }
//
// public boolean parseStructure(String name) throws IOException {
// long offset = _input.lastLocation();
// for (Structure s : _structures) {
// if (name.equals(s.getName())) {
// if (s.parse(_input, _globals, _current)) {
// _current.setStructureLocation(s.getLocation());
// _current.setStructureInputLocation((int)offset, (int)(_input.lastLocation() - offset));
// //System.out.println("Structure " + s.getName() + " matched!");
// return true;
// } else {
// return false;
// }
// }
// }
// throw new RuntimeException("Unknown structure requested: " + name);
// }
//
// public ValidatorInputStream getInput() {
// return _input;
// }
//
// public Sentence getCurrent() {
// return _current;
// }
//
// }
|
import java.io.IOException;
import org.derric_lang.validator.interpreter.Interpreter;
|
package org.derric_lang.validator.interpreter.symbol;
public class Term extends Symbol {
private final String _name;
public Term(String name) {
_name = name;
}
@Override
|
// Path: src/org/derric_lang/validator/interpreter/Interpreter.java
// public class Interpreter extends Validator {
//
// private final String _format;
// private final List<Symbol> _sequence;
// private final List<Structure> _structures;
// private final Map<String, Type> _globals;
//
// private Sentence _current;
// private URI _inputFile;
//
// public Interpreter(URI inputFile, String format, List<Symbol> sequence, List<Structure> structures, List<Decl> globals) {
// super(format);
// _inputFile = inputFile;
// _format = format;
// _sequence = sequence;
// _structures = structures;
// _globals = new HashMap<String, Type>();
// for (Decl d : globals) {
// _globals.put(d.getName(), d.getType());
// }
// setStream(ValidatorInputStreamFactory.create(_inputFile));
// }
//
// @Override
// public String getExtension() {
// return _format;
// }
//
// @Override
// protected ParseResult tryParseBody() throws IOException {
// _current = new Sentence(_inputFile);
// for (Symbol s : _sequence) {
// if (!s.parse(this)) {
// return new ParseResult(false, _input.lastLocation(), _input.lastRead(), s.toString(), _current.toString());
// }
// _current.fullMatch();
// //System.out.println("Validated " + s.toString());
// }
// return new ParseResult(true, _input.lastLocation(), _input.lastRead(), "", _current.toString());
// }
//
// @Override
// public ParseResult findNextFooter() throws IOException {
// return null;
// }
//
// public boolean parseStructure(String name) throws IOException {
// long offset = _input.lastLocation();
// for (Structure s : _structures) {
// if (name.equals(s.getName())) {
// if (s.parse(_input, _globals, _current)) {
// _current.setStructureLocation(s.getLocation());
// _current.setStructureInputLocation((int)offset, (int)(_input.lastLocation() - offset));
// //System.out.println("Structure " + s.getName() + " matched!");
// return true;
// } else {
// return false;
// }
// }
// }
// throw new RuntimeException("Unknown structure requested: " + name);
// }
//
// public ValidatorInputStream getInput() {
// return _input;
// }
//
// public Sentence getCurrent() {
// return _current;
// }
//
// }
// Path: src/org/derric_lang/validator/interpreter/symbol/Term.java
import java.io.IOException;
import org.derric_lang.validator.interpreter.Interpreter;
package org.derric_lang.validator.interpreter.symbol;
public class Term extends Symbol {
private final String _name;
public Term(String name) {
_name = name;
}
@Override
|
public boolean parse(Interpreter in) throws IOException {
|
jvdb/derric
|
src/org/derric_lang/validator/interpreter/symbol/AnyOf.java
|
// Path: src/org/derric_lang/validator/interpreter/Interpreter.java
// public class Interpreter extends Validator {
//
// private final String _format;
// private final List<Symbol> _sequence;
// private final List<Structure> _structures;
// private final Map<String, Type> _globals;
//
// private Sentence _current;
// private URI _inputFile;
//
// public Interpreter(URI inputFile, String format, List<Symbol> sequence, List<Structure> structures, List<Decl> globals) {
// super(format);
// _inputFile = inputFile;
// _format = format;
// _sequence = sequence;
// _structures = structures;
// _globals = new HashMap<String, Type>();
// for (Decl d : globals) {
// _globals.put(d.getName(), d.getType());
// }
// setStream(ValidatorInputStreamFactory.create(_inputFile));
// }
//
// @Override
// public String getExtension() {
// return _format;
// }
//
// @Override
// protected ParseResult tryParseBody() throws IOException {
// _current = new Sentence(_inputFile);
// for (Symbol s : _sequence) {
// if (!s.parse(this)) {
// return new ParseResult(false, _input.lastLocation(), _input.lastRead(), s.toString(), _current.toString());
// }
// _current.fullMatch();
// //System.out.println("Validated " + s.toString());
// }
// return new ParseResult(true, _input.lastLocation(), _input.lastRead(), "", _current.toString());
// }
//
// @Override
// public ParseResult findNextFooter() throws IOException {
// return null;
// }
//
// public boolean parseStructure(String name) throws IOException {
// long offset = _input.lastLocation();
// for (Structure s : _structures) {
// if (name.equals(s.getName())) {
// if (s.parse(_input, _globals, _current)) {
// _current.setStructureLocation(s.getLocation());
// _current.setStructureInputLocation((int)offset, (int)(_input.lastLocation() - offset));
// //System.out.println("Structure " + s.getName() + " matched!");
// return true;
// } else {
// return false;
// }
// }
// }
// throw new RuntimeException("Unknown structure requested: " + name);
// }
//
// public ValidatorInputStream getInput() {
// return _input;
// }
//
// public Sentence getCurrent() {
// return _current;
// }
//
// }
|
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.derric_lang.validator.interpreter.Interpreter;
|
package org.derric_lang.validator.interpreter.symbol;
public class AnyOf extends Symbol {
private final List<Symbol> _symbols;
public AnyOf(HashSet<Symbol> symbols) {
_symbols = new ArrayList<Symbol>();
Symbol empty = null;
for (Symbol s : symbols) {
if (s.isEmpty()) {
empty = s;
} else {
_symbols.add(s);
}
}
if (empty != null) {
_symbols.add(empty);
}
}
@Override
|
// Path: src/org/derric_lang/validator/interpreter/Interpreter.java
// public class Interpreter extends Validator {
//
// private final String _format;
// private final List<Symbol> _sequence;
// private final List<Structure> _structures;
// private final Map<String, Type> _globals;
//
// private Sentence _current;
// private URI _inputFile;
//
// public Interpreter(URI inputFile, String format, List<Symbol> sequence, List<Structure> structures, List<Decl> globals) {
// super(format);
// _inputFile = inputFile;
// _format = format;
// _sequence = sequence;
// _structures = structures;
// _globals = new HashMap<String, Type>();
// for (Decl d : globals) {
// _globals.put(d.getName(), d.getType());
// }
// setStream(ValidatorInputStreamFactory.create(_inputFile));
// }
//
// @Override
// public String getExtension() {
// return _format;
// }
//
// @Override
// protected ParseResult tryParseBody() throws IOException {
// _current = new Sentence(_inputFile);
// for (Symbol s : _sequence) {
// if (!s.parse(this)) {
// return new ParseResult(false, _input.lastLocation(), _input.lastRead(), s.toString(), _current.toString());
// }
// _current.fullMatch();
// //System.out.println("Validated " + s.toString());
// }
// return new ParseResult(true, _input.lastLocation(), _input.lastRead(), "", _current.toString());
// }
//
// @Override
// public ParseResult findNextFooter() throws IOException {
// return null;
// }
//
// public boolean parseStructure(String name) throws IOException {
// long offset = _input.lastLocation();
// for (Structure s : _structures) {
// if (name.equals(s.getName())) {
// if (s.parse(_input, _globals, _current)) {
// _current.setStructureLocation(s.getLocation());
// _current.setStructureInputLocation((int)offset, (int)(_input.lastLocation() - offset));
// //System.out.println("Structure " + s.getName() + " matched!");
// return true;
// } else {
// return false;
// }
// }
// }
// throw new RuntimeException("Unknown structure requested: " + name);
// }
//
// public ValidatorInputStream getInput() {
// return _input;
// }
//
// public Sentence getCurrent() {
// return _current;
// }
//
// }
// Path: src/org/derric_lang/validator/interpreter/symbol/AnyOf.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.derric_lang.validator.interpreter.Interpreter;
package org.derric_lang.validator.interpreter.symbol;
public class AnyOf extends Symbol {
private final List<Symbol> _symbols;
public AnyOf(HashSet<Symbol> symbols) {
_symbols = new ArrayList<Symbol>();
Symbol empty = null;
for (Symbol s : symbols) {
if (s.isEmpty()) {
empty = s;
} else {
_symbols.add(s);
}
}
if (empty != null) {
_symbols.add(empty);
}
}
@Override
|
public boolean parse(Interpreter in) throws IOException {
|
jvdb/derric
|
src/org/derric_lang/validator/interpreter/symbol/Seq.java
|
// Path: src/org/derric_lang/validator/interpreter/Interpreter.java
// public class Interpreter extends Validator {
//
// private final String _format;
// private final List<Symbol> _sequence;
// private final List<Structure> _structures;
// private final Map<String, Type> _globals;
//
// private Sentence _current;
// private URI _inputFile;
//
// public Interpreter(URI inputFile, String format, List<Symbol> sequence, List<Structure> structures, List<Decl> globals) {
// super(format);
// _inputFile = inputFile;
// _format = format;
// _sequence = sequence;
// _structures = structures;
// _globals = new HashMap<String, Type>();
// for (Decl d : globals) {
// _globals.put(d.getName(), d.getType());
// }
// setStream(ValidatorInputStreamFactory.create(_inputFile));
// }
//
// @Override
// public String getExtension() {
// return _format;
// }
//
// @Override
// protected ParseResult tryParseBody() throws IOException {
// _current = new Sentence(_inputFile);
// for (Symbol s : _sequence) {
// if (!s.parse(this)) {
// return new ParseResult(false, _input.lastLocation(), _input.lastRead(), s.toString(), _current.toString());
// }
// _current.fullMatch();
// //System.out.println("Validated " + s.toString());
// }
// return new ParseResult(true, _input.lastLocation(), _input.lastRead(), "", _current.toString());
// }
//
// @Override
// public ParseResult findNextFooter() throws IOException {
// return null;
// }
//
// public boolean parseStructure(String name) throws IOException {
// long offset = _input.lastLocation();
// for (Structure s : _structures) {
// if (name.equals(s.getName())) {
// if (s.parse(_input, _globals, _current)) {
// _current.setStructureLocation(s.getLocation());
// _current.setStructureInputLocation((int)offset, (int)(_input.lastLocation() - offset));
// //System.out.println("Structure " + s.getName() + " matched!");
// return true;
// } else {
// return false;
// }
// }
// }
// throw new RuntimeException("Unknown structure requested: " + name);
// }
//
// public ValidatorInputStream getInput() {
// return _input;
// }
//
// public Sentence getCurrent() {
// return _current;
// }
//
// }
|
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.derric_lang.validator.interpreter.Interpreter;
|
package org.derric_lang.validator.interpreter.symbol;
public class Seq extends Symbol {
private final List<Symbol> _symbols;
public Seq(ArrayList<Symbol> symbols) {
_symbols = symbols;
}
@Override
|
// Path: src/org/derric_lang/validator/interpreter/Interpreter.java
// public class Interpreter extends Validator {
//
// private final String _format;
// private final List<Symbol> _sequence;
// private final List<Structure> _structures;
// private final Map<String, Type> _globals;
//
// private Sentence _current;
// private URI _inputFile;
//
// public Interpreter(URI inputFile, String format, List<Symbol> sequence, List<Structure> structures, List<Decl> globals) {
// super(format);
// _inputFile = inputFile;
// _format = format;
// _sequence = sequence;
// _structures = structures;
// _globals = new HashMap<String, Type>();
// for (Decl d : globals) {
// _globals.put(d.getName(), d.getType());
// }
// setStream(ValidatorInputStreamFactory.create(_inputFile));
// }
//
// @Override
// public String getExtension() {
// return _format;
// }
//
// @Override
// protected ParseResult tryParseBody() throws IOException {
// _current = new Sentence(_inputFile);
// for (Symbol s : _sequence) {
// if (!s.parse(this)) {
// return new ParseResult(false, _input.lastLocation(), _input.lastRead(), s.toString(), _current.toString());
// }
// _current.fullMatch();
// //System.out.println("Validated " + s.toString());
// }
// return new ParseResult(true, _input.lastLocation(), _input.lastRead(), "", _current.toString());
// }
//
// @Override
// public ParseResult findNextFooter() throws IOException {
// return null;
// }
//
// public boolean parseStructure(String name) throws IOException {
// long offset = _input.lastLocation();
// for (Structure s : _structures) {
// if (name.equals(s.getName())) {
// if (s.parse(_input, _globals, _current)) {
// _current.setStructureLocation(s.getLocation());
// _current.setStructureInputLocation((int)offset, (int)(_input.lastLocation() - offset));
// //System.out.println("Structure " + s.getName() + " matched!");
// return true;
// } else {
// return false;
// }
// }
// }
// throw new RuntimeException("Unknown structure requested: " + name);
// }
//
// public ValidatorInputStream getInput() {
// return _input;
// }
//
// public Sentence getCurrent() {
// return _current;
// }
//
// }
// Path: src/org/derric_lang/validator/interpreter/symbol/Seq.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.derric_lang.validator.interpreter.Interpreter;
package org.derric_lang.validator.interpreter.symbol;
public class Seq extends Symbol {
private final List<Symbol> _symbols;
public Seq(ArrayList<Symbol> symbols) {
_symbols = symbols;
}
@Override
|
public boolean parse(Interpreter in) throws IOException {
|
zerg000000/mario-ai
|
src/main/java/ch/idsia/benchmark/mario/engine/Replayer.java
|
// Path: src/main/java/ch/idsia/tools/ReplayerOptions.java
// public class ReplayerOptions
// {
// public static class Interval implements Serializable
// {
// public int from;
// public int to;
//
// public Interval()
// {
// from = 0;
// to = 0;
// }
//
// public Interval(String interval)
// {
// String[] nums = interval.split(":");
// from = Integer.valueOf(nums[0]);
// to = Integer.valueOf(nums[1]);
// }
//
// public Interval(final int i, final int i1)
// {
// from = i;
// to = i1;
// }
// }
//
// private Queue<Interval> chunks = new LinkedList<Interval>();
// private Queue<String> replays = new LinkedList<String>();
// private String regex = "[a-zA-Z_0-9.-]+(;\\d+:\\d+)*";
//
// public ReplayerOptions(String options)
// {
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(options);
//
// while (matcher.find())
// {
// String group = matcher.group();
// replays.add(group);
// }
// }
//
// public String getNextReplayFile()
// {
// String s = replays.poll();
// if (s == null)
// return null;
//
// String[] subgroups = s.split(";");
// if (subgroups.length == 0)
// return null;
//
// String fileName = subgroups[0];
// chunks.clear();
//
// if (subgroups.length > 1)
// for (int i = 1; i < subgroups.length; i++)
// chunks.add(new Interval(subgroups[i]));
//
// return fileName;
// }
//
// public Interval getNextIntervalInMarioseconds()
// {
// return chunks.poll();
// }
//
// public Interval getNextIntervalInTicks()
// {
// Interval i = chunks.poll();
// Interval res = null;
//
// if (i != null)
// res = new Interval(i.from * GlobalOptions.mariosecondMultiplier, i.to * GlobalOptions.mariosecondMultiplier);
//
// return res;
// }
//
// public boolean hasMoreChunks()
// {
// return !chunks.isEmpty();
// }
//
// public void setChunks(Queue chunks)
// {
// this.chunks = chunks;
// }
// }
|
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Queue;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import ch.idsia.benchmark.mario.environments.Environment;
import ch.idsia.tools.ReplayerOptions;
|
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.benchmark.mario.engine;
/**
* Created by IntelliJ IDEA.
* User: Sergey Karakovskiy, firstName_at_idsia_dot_ch
* Date: May 5, 2009
* Time: 9:34:33 PM
* Package: ch.idsia.utils
*/
public class Replayer
{
private ZipFile zf = null;
private ZipEntry ze = null;
private BufferedInputStream fis;
|
// Path: src/main/java/ch/idsia/tools/ReplayerOptions.java
// public class ReplayerOptions
// {
// public static class Interval implements Serializable
// {
// public int from;
// public int to;
//
// public Interval()
// {
// from = 0;
// to = 0;
// }
//
// public Interval(String interval)
// {
// String[] nums = interval.split(":");
// from = Integer.valueOf(nums[0]);
// to = Integer.valueOf(nums[1]);
// }
//
// public Interval(final int i, final int i1)
// {
// from = i;
// to = i1;
// }
// }
//
// private Queue<Interval> chunks = new LinkedList<Interval>();
// private Queue<String> replays = new LinkedList<String>();
// private String regex = "[a-zA-Z_0-9.-]+(;\\d+:\\d+)*";
//
// public ReplayerOptions(String options)
// {
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(options);
//
// while (matcher.find())
// {
// String group = matcher.group();
// replays.add(group);
// }
// }
//
// public String getNextReplayFile()
// {
// String s = replays.poll();
// if (s == null)
// return null;
//
// String[] subgroups = s.split(";");
// if (subgroups.length == 0)
// return null;
//
// String fileName = subgroups[0];
// chunks.clear();
//
// if (subgroups.length > 1)
// for (int i = 1; i < subgroups.length; i++)
// chunks.add(new Interval(subgroups[i]));
//
// return fileName;
// }
//
// public Interval getNextIntervalInMarioseconds()
// {
// return chunks.poll();
// }
//
// public Interval getNextIntervalInTicks()
// {
// Interval i = chunks.poll();
// Interval res = null;
//
// if (i != null)
// res = new Interval(i.from * GlobalOptions.mariosecondMultiplier, i.to * GlobalOptions.mariosecondMultiplier);
//
// return res;
// }
//
// public boolean hasMoreChunks()
// {
// return !chunks.isEmpty();
// }
//
// public void setChunks(Queue chunks)
// {
// this.chunks = chunks;
// }
// }
// Path: src/main/java/ch/idsia/benchmark/mario/engine/Replayer.java
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Queue;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import ch.idsia.benchmark.mario.environments.Environment;
import ch.idsia.tools.ReplayerOptions;
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.benchmark.mario.engine;
/**
* Created by IntelliJ IDEA.
* User: Sergey Karakovskiy, firstName_at_idsia_dot_ch
* Date: May 5, 2009
* Time: 9:34:33 PM
* Package: ch.idsia.utils
*/
public class Replayer
{
private ZipFile zf = null;
private ZipEntry ze = null;
private BufferedInputStream fis;
|
private ReplayerOptions options;
|
zerg000000/mario-ai
|
src/main/java/ch/idsia/utils/ParameterContainer.java
|
// Path: src/main/java/ch/idsia/agents/AgentsPool.java
// public final class AgentsPool
// {
// private static Agent currentAgent = null;
// private static AgentLoader agentLoader = AgentLoader.getInstance();
//
// public static void addAgent(Agent agent)
// {
// agentsHashMap.put(agent.getName(), agent);
// }
//
// public static void addAgent(String agentWOXName, boolean isPunj) throws IllegalFormatException
// {
// addAgent(loadAgent(agentWOXName, isPunj));
// }
//
// public static Agent loadAgent(String name, boolean isPunj)
// {
// return agentLoader.loadAgent(name, isPunj);
// }
//
// public static Collection<Agent> getAgentsCollection()
// {
// return agentsHashMap.values();
// }
//
// public static Set<String> getAgentsNames()
// {
// return AgentsPool.agentsHashMap.keySet();
// }
//
// public static Agent getAgentByName(String agentName)
// {
// // There is only one case possible;
// Agent ret = AgentsPool.agentsHashMap.get(agentName);
// if (ret == null)
// ret = AgentsPool.agentsHashMap.get(agentName.split(":")[0]);
// return ret;
// }
//
// public static Agent getCurrentAgent()
// {
// if (currentAgent == null)
// currentAgent = (Agent) getAgentsCollection().toArray()[0];
// return currentAgent;
// }
//
// public static void setCurrentAgent(Agent agent)
// {
// currentAgent = agent;
// }
//
// //public static void setCurrentAgent(String agentWOXName)
// //{
// // setCurrentAgent(AgentsPool.loadAgent(agentWOXName));
// //}
//
// static HashMap<String, Agent> agentsHashMap = new LinkedHashMap<String, Agent>();
// }
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import ch.idsia.agents.Agent;
import ch.idsia.agents.AgentsPool;
|
// {
// System.err.println("Parameter " + param + " is not valid. Typo?");
// return "";
// }
}
public int i(String s)
{
return Integer.parseInt(s);
}
public float f(String s)
{
return Float.parseFloat(s);
}
public String s(boolean b)
{
return b ? "on" : "off";
}
public String s(Object i)
{
return String.valueOf(i);
}
public String s(Agent a)
{
try
{
|
// Path: src/main/java/ch/idsia/agents/AgentsPool.java
// public final class AgentsPool
// {
// private static Agent currentAgent = null;
// private static AgentLoader agentLoader = AgentLoader.getInstance();
//
// public static void addAgent(Agent agent)
// {
// agentsHashMap.put(agent.getName(), agent);
// }
//
// public static void addAgent(String agentWOXName, boolean isPunj) throws IllegalFormatException
// {
// addAgent(loadAgent(agentWOXName, isPunj));
// }
//
// public static Agent loadAgent(String name, boolean isPunj)
// {
// return agentLoader.loadAgent(name, isPunj);
// }
//
// public static Collection<Agent> getAgentsCollection()
// {
// return agentsHashMap.values();
// }
//
// public static Set<String> getAgentsNames()
// {
// return AgentsPool.agentsHashMap.keySet();
// }
//
// public static Agent getAgentByName(String agentName)
// {
// // There is only one case possible;
// Agent ret = AgentsPool.agentsHashMap.get(agentName);
// if (ret == null)
// ret = AgentsPool.agentsHashMap.get(agentName.split(":")[0]);
// return ret;
// }
//
// public static Agent getCurrentAgent()
// {
// if (currentAgent == null)
// currentAgent = (Agent) getAgentsCollection().toArray()[0];
// return currentAgent;
// }
//
// public static void setCurrentAgent(Agent agent)
// {
// currentAgent = agent;
// }
//
// //public static void setCurrentAgent(String agentWOXName)
// //{
// // setCurrentAgent(AgentsPool.loadAgent(agentWOXName));
// //}
//
// static HashMap<String, Agent> agentsHashMap = new LinkedHashMap<String, Agent>();
// }
// Path: src/main/java/ch/idsia/utils/ParameterContainer.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import ch.idsia.agents.Agent;
import ch.idsia.agents.AgentsPool;
// {
// System.err.println("Parameter " + param + " is not valid. Typo?");
// return "";
// }
}
public int i(String s)
{
return Integer.parseInt(s);
}
public float f(String s)
{
return Float.parseFloat(s);
}
public String s(boolean b)
{
return b ? "on" : "off";
}
public String s(Object i)
{
return String.valueOf(i);
}
public String s(Agent a)
{
try
{
|
if (AgentsPool.getAgentByName(a.getName()) == null)
|
zerg000000/mario-ai
|
src/main/java/ch/idsia/benchmark/mario/engine/sprites/Particle.java
|
// Path: src/main/java/ch/idsia/benchmark/mario/engine/Art.java
// public class Art
// {
// public static Image[][] mario;
// public static Image[][] racoonmario;
// public static Image[][] smallMario;
// public static Image[][] fireMario;
// public static Image[][] enemies;
// public static Image[][] items;
// public static Image[][] level;
// public static Image[][] particles;
// public static Image[][] font;
// public static Image[][] bg;
// public static Image[][] princess;
// // public static Image[][] map;
// // public static Image[][] endScene;
// // public static Image[][] gameOver;
// // public static Image logo;
// // public static Image titleScreen;
// // final static String curDir = System.getProperty("user.dir");
//
// public static void init(GraphicsConfiguration gc)
// {
// try
// {
// mario = cutImage(gc, "resources/mariosheet.png", 32, 32);
// racoonmario = cutImage(gc, "resources/racoonmariosheet.png", 32, 32);
// smallMario = cutImage(gc, "resources/smallmariosheet.png", 16, 16);
// fireMario = cutImage(gc, "resources/firemariosheet.png", 32, 32);
// enemies = cutImage(gc, "resources/enemysheet.png", 16, 32);
// items = cutImage(gc, "resources/itemsheet.png", 16, 16);
// level = cutImage(gc, "resources/mapsheet.png", 16, 16);
// // map = cutImage(gc, "resources/worldmap.png", 16, 16);
// particles = cutImage(gc, "resources/particlesheet.png", 8, 8);
// bg = cutImage(gc, "resources/bgsheet.png", 32, 32);
// // logo = getImage(gc, "resources/logo.gif");
// // titleScreen = getImage(gc, "resources/title.gif");
// font = cutImage(gc, "resources/font.gif", 8, 8);
// princess = cutImage(gc, "resources/princess.png", 32, 32);
// // endScene = cutImage(gc, "resources/endscene.gif", 96, 96);
// // gameOver = cutImage(gc, "resources/gameovergost.gif", 96, 64);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// }
//
// private static Image getImage(GraphicsConfiguration gc, String imageName) throws IOException
// {
// BufferedImage source = null;
// try
// { source = ImageIO.read(Art.class.getResourceAsStream(imageName)); }
// catch (Exception e) { e.printStackTrace(); }
//
// assert source != null;
// Image image = gc.createCompatibleImage(source.getWidth(), source.getHeight(), Transparency.BITMASK);
// Graphics2D g = (Graphics2D) image.getGraphics();
// g.setComposite(AlphaComposite.Src);
// g.drawImage(source, 0, 0, null);
// g.dispose();
// return image;
// }
//
// private static Image[][] cutImage(GraphicsConfiguration gc, String imageName, int xSize, int ySize) throws IOException
// {
// Image source = getImage(gc, imageName);
// Image[][] images = new Image[source.getWidth(null) / xSize][source.getHeight(null) / ySize];
// for (int x = 0; x < source.getWidth(null) / xSize; x++)
// {
// for (int y = 0; y < source.getHeight(null) / ySize; y++)
// {
// Image image = gc.createCompatibleImage(xSize, ySize, Transparency.BITMASK);
// Graphics2D g = (Graphics2D) image.getGraphics();
// g.setComposite(AlphaComposite.Src);
// g.drawImage(source, -x * xSize, -y * ySize, null);
// g.dispose();
// images[x][y] = image;
// }
// }
//
// return images;
// }
//
// }
|
import ch.idsia.benchmark.mario.engine.Art;
|
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.benchmark.mario.engine.sprites;
public class Particle extends Sprite
{
public int life;
public Particle(int x, int y, float xa, float ya)
{
this(x, y, xa, ya, (int) (Math.random() * 2), 0);
}
public Particle(int x, int y, float xa, float ya, int xPic, int yPic)
{
kind = KIND_PARTICLE;
|
// Path: src/main/java/ch/idsia/benchmark/mario/engine/Art.java
// public class Art
// {
// public static Image[][] mario;
// public static Image[][] racoonmario;
// public static Image[][] smallMario;
// public static Image[][] fireMario;
// public static Image[][] enemies;
// public static Image[][] items;
// public static Image[][] level;
// public static Image[][] particles;
// public static Image[][] font;
// public static Image[][] bg;
// public static Image[][] princess;
// // public static Image[][] map;
// // public static Image[][] endScene;
// // public static Image[][] gameOver;
// // public static Image logo;
// // public static Image titleScreen;
// // final static String curDir = System.getProperty("user.dir");
//
// public static void init(GraphicsConfiguration gc)
// {
// try
// {
// mario = cutImage(gc, "resources/mariosheet.png", 32, 32);
// racoonmario = cutImage(gc, "resources/racoonmariosheet.png", 32, 32);
// smallMario = cutImage(gc, "resources/smallmariosheet.png", 16, 16);
// fireMario = cutImage(gc, "resources/firemariosheet.png", 32, 32);
// enemies = cutImage(gc, "resources/enemysheet.png", 16, 32);
// items = cutImage(gc, "resources/itemsheet.png", 16, 16);
// level = cutImage(gc, "resources/mapsheet.png", 16, 16);
// // map = cutImage(gc, "resources/worldmap.png", 16, 16);
// particles = cutImage(gc, "resources/particlesheet.png", 8, 8);
// bg = cutImage(gc, "resources/bgsheet.png", 32, 32);
// // logo = getImage(gc, "resources/logo.gif");
// // titleScreen = getImage(gc, "resources/title.gif");
// font = cutImage(gc, "resources/font.gif", 8, 8);
// princess = cutImage(gc, "resources/princess.png", 32, 32);
// // endScene = cutImage(gc, "resources/endscene.gif", 96, 96);
// // gameOver = cutImage(gc, "resources/gameovergost.gif", 96, 64);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// }
//
// private static Image getImage(GraphicsConfiguration gc, String imageName) throws IOException
// {
// BufferedImage source = null;
// try
// { source = ImageIO.read(Art.class.getResourceAsStream(imageName)); }
// catch (Exception e) { e.printStackTrace(); }
//
// assert source != null;
// Image image = gc.createCompatibleImage(source.getWidth(), source.getHeight(), Transparency.BITMASK);
// Graphics2D g = (Graphics2D) image.getGraphics();
// g.setComposite(AlphaComposite.Src);
// g.drawImage(source, 0, 0, null);
// g.dispose();
// return image;
// }
//
// private static Image[][] cutImage(GraphicsConfiguration gc, String imageName, int xSize, int ySize) throws IOException
// {
// Image source = getImage(gc, imageName);
// Image[][] images = new Image[source.getWidth(null) / xSize][source.getHeight(null) / ySize];
// for (int x = 0; x < source.getWidth(null) / xSize; x++)
// {
// for (int y = 0; y < source.getHeight(null) / ySize; y++)
// {
// Image image = gc.createCompatibleImage(xSize, ySize, Transparency.BITMASK);
// Graphics2D g = (Graphics2D) image.getGraphics();
// g.setComposite(AlphaComposite.Src);
// g.drawImage(source, -x * xSize, -y * ySize, null);
// g.dispose();
// images[x][y] = image;
// }
// }
//
// return images;
// }
//
// }
// Path: src/main/java/ch/idsia/benchmark/mario/engine/sprites/Particle.java
import ch.idsia.benchmark.mario.engine.Art;
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.benchmark.mario.engine.sprites;
public class Particle extends Sprite
{
public int life;
public Particle(int x, int y, float xa, float ya)
{
this(x, y, xa, ya, (int) (Math.random() * 2), 0);
}
public Particle(int x, int y, float xa, float ya, int xPic, int yPic)
{
kind = KIND_PARTICLE;
|
sheet = Art.particles;
|
zerg000000/mario-ai
|
src/main/java/ch/idsia/benchmark/mario/engine/Recorder.java
|
// Path: src/main/java/ch/idsia/tools/ReplayerOptions.java
// public class ReplayerOptions
// {
// public static class Interval implements Serializable
// {
// public int from;
// public int to;
//
// public Interval()
// {
// from = 0;
// to = 0;
// }
//
// public Interval(String interval)
// {
// String[] nums = interval.split(":");
// from = Integer.valueOf(nums[0]);
// to = Integer.valueOf(nums[1]);
// }
//
// public Interval(final int i, final int i1)
// {
// from = i;
// to = i1;
// }
// }
//
// private Queue<Interval> chunks = new LinkedList<Interval>();
// private Queue<String> replays = new LinkedList<String>();
// private String regex = "[a-zA-Z_0-9.-]+(;\\d+:\\d+)*";
//
// public ReplayerOptions(String options)
// {
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(options);
//
// while (matcher.find())
// {
// String group = matcher.group();
// replays.add(group);
// }
// }
//
// public String getNextReplayFile()
// {
// String s = replays.poll();
// if (s == null)
// return null;
//
// String[] subgroups = s.split(";");
// if (subgroups.length == 0)
// return null;
//
// String fileName = subgroups[0];
// chunks.clear();
//
// if (subgroups.length > 1)
// for (int i = 1; i < subgroups.length; i++)
// chunks.add(new Interval(subgroups[i]));
//
// return fileName;
// }
//
// public Interval getNextIntervalInMarioseconds()
// {
// return chunks.poll();
// }
//
// public Interval getNextIntervalInTicks()
// {
// Interval i = chunks.poll();
// Interval res = null;
//
// if (i != null)
// res = new Interval(i.from * GlobalOptions.mariosecondMultiplier, i.to * GlobalOptions.mariosecondMultiplier);
//
// return res;
// }
//
// public boolean hasMoreChunks()
// {
// return !chunks.isEmpty();
// }
//
// public void setChunks(Queue chunks)
// {
// this.chunks = chunks;
// }
// }
|
import java.util.LinkedList;
import java.util.Queue;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import ch.idsia.tools.ReplayerOptions;
import java.io.*;
|
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.benchmark.mario.engine;
/**
* Created by IntelliJ IDEA.
* User: Sergey Karakovskiy, sergey@idsia.ch
* Date: May 5, 2009
* Time: 9:34:33 PM
* Package: ch.idsia.utils
*/
public class Recorder
{
private ZipOutputStream zos;
boolean lastRecordingState = false;
|
// Path: src/main/java/ch/idsia/tools/ReplayerOptions.java
// public class ReplayerOptions
// {
// public static class Interval implements Serializable
// {
// public int from;
// public int to;
//
// public Interval()
// {
// from = 0;
// to = 0;
// }
//
// public Interval(String interval)
// {
// String[] nums = interval.split(":");
// from = Integer.valueOf(nums[0]);
// to = Integer.valueOf(nums[1]);
// }
//
// public Interval(final int i, final int i1)
// {
// from = i;
// to = i1;
// }
// }
//
// private Queue<Interval> chunks = new LinkedList<Interval>();
// private Queue<String> replays = new LinkedList<String>();
// private String regex = "[a-zA-Z_0-9.-]+(;\\d+:\\d+)*";
//
// public ReplayerOptions(String options)
// {
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(options);
//
// while (matcher.find())
// {
// String group = matcher.group();
// replays.add(group);
// }
// }
//
// public String getNextReplayFile()
// {
// String s = replays.poll();
// if (s == null)
// return null;
//
// String[] subgroups = s.split(";");
// if (subgroups.length == 0)
// return null;
//
// String fileName = subgroups[0];
// chunks.clear();
//
// if (subgroups.length > 1)
// for (int i = 1; i < subgroups.length; i++)
// chunks.add(new Interval(subgroups[i]));
//
// return fileName;
// }
//
// public Interval getNextIntervalInMarioseconds()
// {
// return chunks.poll();
// }
//
// public Interval getNextIntervalInTicks()
// {
// Interval i = chunks.poll();
// Interval res = null;
//
// if (i != null)
// res = new Interval(i.from * GlobalOptions.mariosecondMultiplier, i.to * GlobalOptions.mariosecondMultiplier);
//
// return res;
// }
//
// public boolean hasMoreChunks()
// {
// return !chunks.isEmpty();
// }
//
// public void setChunks(Queue chunks)
// {
// this.chunks = chunks;
// }
// }
// Path: src/main/java/ch/idsia/benchmark/mario/engine/Recorder.java
import java.util.LinkedList;
import java.util.Queue;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import ch.idsia.tools.ReplayerOptions;
import java.io.*;
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.benchmark.mario.engine;
/**
* Created by IntelliJ IDEA.
* User: Sergey Karakovskiy, sergey@idsia.ch
* Date: May 5, 2009
* Time: 9:34:33 PM
* Package: ch.idsia.utils
*/
public class Recorder
{
private ZipOutputStream zos;
boolean lastRecordingState = false;
|
private Queue<ReplayerOptions.Interval> chunks = new LinkedList<ReplayerOptions.Interval>();
|
zerg000000/mario-ai
|
src/main/java/ch/idsia/agents/AmiCoAgent.java
|
// Path: src/main/java/ch/idsia/tools/amico/AmiCoJavaPy.java
// public class AmiCoJavaPy
// {
// public AmiCoJavaPy(String moduleName, String className)
// {
// int res = this.initModule(moduleName, className);
// if (res == 0)
// {
// System.out.println("Java: Python module initialized successfully");
// } else
// throw new Error("Java: Python module initialization failed");
// }
//
// public native int initModule(String moduleName, String className);
//
// public native String getName();
//
// public native void integrateObservation(int[] squashedObservation, int[] squashedEnemies, float[] marioPos, float[] enemiesPos, int[] marioState);
//
// public native int[] getAction();
//
// public native void giveIntermediateReward(final float intermediateReward);
//
// public native void reset();
//
// public native void setObservationDetails(final int rfWidth, final int rfHeight, final int egoRow, final int egoCol);
//
// static
// {
// System.out.println("Java: loading AmiCo...");
// System.loadLibrary("AmiCoJavaPy");
// System.out.println("Java: AmiCo library has been successfully loaded!");
// }
//
// public native void finalizePythonEnvironment();
// }
|
import ch.idsia.benchmark.mario.environments.Environment;
import ch.idsia.tools.amico.AmiCoJavaPy;
|
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.agents;
/**
* Created by IntelliJ IDEA.
* User: Sergey Karakovskiy, sergey at idsia dot ch
* Date: Dec 11, 2009
* Time: 8:29:15 PM
* Package: ch.idsia.controllers.agents
*/
public class AmiCoAgent implements Agent
{
|
// Path: src/main/java/ch/idsia/tools/amico/AmiCoJavaPy.java
// public class AmiCoJavaPy
// {
// public AmiCoJavaPy(String moduleName, String className)
// {
// int res = this.initModule(moduleName, className);
// if (res == 0)
// {
// System.out.println("Java: Python module initialized successfully");
// } else
// throw new Error("Java: Python module initialization failed");
// }
//
// public native int initModule(String moduleName, String className);
//
// public native String getName();
//
// public native void integrateObservation(int[] squashedObservation, int[] squashedEnemies, float[] marioPos, float[] enemiesPos, int[] marioState);
//
// public native int[] getAction();
//
// public native void giveIntermediateReward(final float intermediateReward);
//
// public native void reset();
//
// public native void setObservationDetails(final int rfWidth, final int rfHeight, final int egoRow, final int egoCol);
//
// static
// {
// System.out.println("Java: loading AmiCo...");
// System.loadLibrary("AmiCoJavaPy");
// System.out.println("Java: AmiCo library has been successfully loaded!");
// }
//
// public native void finalizePythonEnvironment();
// }
// Path: src/main/java/ch/idsia/agents/AmiCoAgent.java
import ch.idsia.benchmark.mario.environments.Environment;
import ch.idsia.tools.amico.AmiCoJavaPy;
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.agents;
/**
* Created by IntelliJ IDEA.
* User: Sergey Karakovskiy, sergey at idsia dot ch
* Date: Dec 11, 2009
* Time: 8:29:15 PM
* Package: ch.idsia.controllers.agents
*/
public class AmiCoAgent implements Agent
{
|
static AmiCoJavaPy amicoJavaPy = null;
|
zerg000000/mario-ai
|
src/main/java/ch/idsia/tools/EvaluationInfo.java
|
// Path: src/main/java/ch/idsia/benchmark/tasks/MarioSystemOfValues.java
// public class MarioSystemOfValues extends SystemOfValues
// {
// final public int distance = 1;
// final public int win = 1024;
// final public int mode = 32;
// final public int coins = 16;
// final public int hiddenItems = 24;
// final public int flowerFire = 64; // not used for now
// final public int kills = 42;
// final public int killedByFire = 4;
// final public int killedByShell = 17;
// final public int killedByStomp = 12;
// final public int timeLeft = 8;
// final public int hiddenBlocks = 24;
//
// public interface timeLengthMapping
// {
// final public static int TIGHT = 10;
// final public static int MEDIUM = 20;
// final public static int FLEXIBLE = 30;
// }
// }
//
// Path: src/main/java/ch/idsia/benchmark/tasks/SystemOfValues.java
// public class SystemOfValues
// {
// public int distance = 1;
// public int win = 1024;
// public int mode = 32;
// public int coins = 16;
// public int flowerFire = 64;
// public int kills = 42;
// public int killedByFire = 4;
// public int killedByShell = 17;
// public int killedByStomp = 12;
// public int mushroom = 58;
// public int timeLeft = 8;
// public int hiddenBlock = 24;
// public int greenMushroom = 58;
// // For Intermediate rewards only
// public int stomp = 10;
// }
|
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import ch.idsia.benchmark.mario.engine.sprites.Mario;
import ch.idsia.benchmark.tasks.MarioSystemOfValues;
import ch.idsia.benchmark.tasks.SystemOfValues;
|
public int killsByStomp = MagicNumberUnDef;
public int killsTotal = MagicNumberUnDef;
public int marioMode = MagicNumberUnDef;
public int marioStatus = MagicNumberUnDef;
public int mushroomsDevoured = MagicNumberUnDef;
public int greenMushroomsDevoured = MagicNumberUnDef;
public int coinsGained = MagicNumberUnDef;
public int timeLeft = MagicNumberUnDef;
public int timeSpent = MagicNumberUnDef;
public int hiddenBlocksFound = MagicNumberUnDef;
private String taskName = "NoTaskNameSpecified";
public int totalNumberOfCoins = MagicNumberUnDef;
public int totalNumberOfHiddenBlocks = MagicNumberUnDef;
public int totalNumberOfMushrooms = MagicNumberUnDef;
public int totalNumberOfFlowers = MagicNumberUnDef;
public int totalNumberOfCreatures = MagicNumberUnDef; //including spiky flowers
public long bytecodeInstructions = MagicNumberUnDef;
public int levelLength = MagicNumberUnDef;
public int collisionsWithCreatures = MagicNumberUnDef;
private static final int[] retFloatArray = new int[EvaluationInfo.numberOfElements];
private static final int[] zeros = new int[EvaluationInfo.numberOfElements];
public String Memo = "";
private static final DecimalFormat df = new DecimalFormat("#.##");
|
// Path: src/main/java/ch/idsia/benchmark/tasks/MarioSystemOfValues.java
// public class MarioSystemOfValues extends SystemOfValues
// {
// final public int distance = 1;
// final public int win = 1024;
// final public int mode = 32;
// final public int coins = 16;
// final public int hiddenItems = 24;
// final public int flowerFire = 64; // not used for now
// final public int kills = 42;
// final public int killedByFire = 4;
// final public int killedByShell = 17;
// final public int killedByStomp = 12;
// final public int timeLeft = 8;
// final public int hiddenBlocks = 24;
//
// public interface timeLengthMapping
// {
// final public static int TIGHT = 10;
// final public static int MEDIUM = 20;
// final public static int FLEXIBLE = 30;
// }
// }
//
// Path: src/main/java/ch/idsia/benchmark/tasks/SystemOfValues.java
// public class SystemOfValues
// {
// public int distance = 1;
// public int win = 1024;
// public int mode = 32;
// public int coins = 16;
// public int flowerFire = 64;
// public int kills = 42;
// public int killedByFire = 4;
// public int killedByShell = 17;
// public int killedByStomp = 12;
// public int mushroom = 58;
// public int timeLeft = 8;
// public int hiddenBlock = 24;
// public int greenMushroom = 58;
// // For Intermediate rewards only
// public int stomp = 10;
// }
// Path: src/main/java/ch/idsia/tools/EvaluationInfo.java
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import ch.idsia.benchmark.mario.engine.sprites.Mario;
import ch.idsia.benchmark.tasks.MarioSystemOfValues;
import ch.idsia.benchmark.tasks.SystemOfValues;
public int killsByStomp = MagicNumberUnDef;
public int killsTotal = MagicNumberUnDef;
public int marioMode = MagicNumberUnDef;
public int marioStatus = MagicNumberUnDef;
public int mushroomsDevoured = MagicNumberUnDef;
public int greenMushroomsDevoured = MagicNumberUnDef;
public int coinsGained = MagicNumberUnDef;
public int timeLeft = MagicNumberUnDef;
public int timeSpent = MagicNumberUnDef;
public int hiddenBlocksFound = MagicNumberUnDef;
private String taskName = "NoTaskNameSpecified";
public int totalNumberOfCoins = MagicNumberUnDef;
public int totalNumberOfHiddenBlocks = MagicNumberUnDef;
public int totalNumberOfMushrooms = MagicNumberUnDef;
public int totalNumberOfFlowers = MagicNumberUnDef;
public int totalNumberOfCreatures = MagicNumberUnDef; //including spiky flowers
public long bytecodeInstructions = MagicNumberUnDef;
public int levelLength = MagicNumberUnDef;
public int collisionsWithCreatures = MagicNumberUnDef;
private static final int[] retFloatArray = new int[EvaluationInfo.numberOfElements];
private static final int[] zeros = new int[EvaluationInfo.numberOfElements];
public String Memo = "";
private static final DecimalFormat df = new DecimalFormat("#.##");
|
private static MarioSystemOfValues marioSystemOfValues = new MarioSystemOfValues();
|
zerg000000/mario-ai
|
src/main/java/ch/idsia/tools/EvaluationInfo.java
|
// Path: src/main/java/ch/idsia/benchmark/tasks/MarioSystemOfValues.java
// public class MarioSystemOfValues extends SystemOfValues
// {
// final public int distance = 1;
// final public int win = 1024;
// final public int mode = 32;
// final public int coins = 16;
// final public int hiddenItems = 24;
// final public int flowerFire = 64; // not used for now
// final public int kills = 42;
// final public int killedByFire = 4;
// final public int killedByShell = 17;
// final public int killedByStomp = 12;
// final public int timeLeft = 8;
// final public int hiddenBlocks = 24;
//
// public interface timeLengthMapping
// {
// final public static int TIGHT = 10;
// final public static int MEDIUM = 20;
// final public static int FLEXIBLE = 30;
// }
// }
//
// Path: src/main/java/ch/idsia/benchmark/tasks/SystemOfValues.java
// public class SystemOfValues
// {
// public int distance = 1;
// public int win = 1024;
// public int mode = 32;
// public int coins = 16;
// public int flowerFire = 64;
// public int kills = 42;
// public int killedByFire = 4;
// public int killedByShell = 17;
// public int killedByStomp = 12;
// public int mushroom = 58;
// public int timeLeft = 8;
// public int hiddenBlock = 24;
// public int greenMushroom = 58;
// // For Intermediate rewards only
// public int stomp = 10;
// }
|
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import ch.idsia.benchmark.mario.engine.sprites.Mario;
import ch.idsia.benchmark.tasks.MarioSystemOfValues;
import ch.idsia.benchmark.tasks.SystemOfValues;
|
public long bytecodeInstructions = MagicNumberUnDef;
public int levelLength = MagicNumberUnDef;
public int collisionsWithCreatures = MagicNumberUnDef;
private static final int[] retFloatArray = new int[EvaluationInfo.numberOfElements];
private static final int[] zeros = new int[EvaluationInfo.numberOfElements];
public String Memo = "";
private static final DecimalFormat df = new DecimalFormat("#.##");
private static MarioSystemOfValues marioSystemOfValues = new MarioSystemOfValues();
public int[][] marioTrace;
public String marioTraceFileName;
private long evaluationStarted = 0;
private long evaluationFinished = 0;
private long evaluationLasted = 0;
public EvaluationInfo()
{
System.arraycopy(EvaluationInfo.zeros, 0, retFloatArray, 0, EvaluationInfo.numberOfElements);
}
public int computeBasicFitness()
{
return distancePassedPhys - timeSpent + coinsGained + marioStatus * marioSystemOfValues.win;
}
|
// Path: src/main/java/ch/idsia/benchmark/tasks/MarioSystemOfValues.java
// public class MarioSystemOfValues extends SystemOfValues
// {
// final public int distance = 1;
// final public int win = 1024;
// final public int mode = 32;
// final public int coins = 16;
// final public int hiddenItems = 24;
// final public int flowerFire = 64; // not used for now
// final public int kills = 42;
// final public int killedByFire = 4;
// final public int killedByShell = 17;
// final public int killedByStomp = 12;
// final public int timeLeft = 8;
// final public int hiddenBlocks = 24;
//
// public interface timeLengthMapping
// {
// final public static int TIGHT = 10;
// final public static int MEDIUM = 20;
// final public static int FLEXIBLE = 30;
// }
// }
//
// Path: src/main/java/ch/idsia/benchmark/tasks/SystemOfValues.java
// public class SystemOfValues
// {
// public int distance = 1;
// public int win = 1024;
// public int mode = 32;
// public int coins = 16;
// public int flowerFire = 64;
// public int kills = 42;
// public int killedByFire = 4;
// public int killedByShell = 17;
// public int killedByStomp = 12;
// public int mushroom = 58;
// public int timeLeft = 8;
// public int hiddenBlock = 24;
// public int greenMushroom = 58;
// // For Intermediate rewards only
// public int stomp = 10;
// }
// Path: src/main/java/ch/idsia/tools/EvaluationInfo.java
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import ch.idsia.benchmark.mario.engine.sprites.Mario;
import ch.idsia.benchmark.tasks.MarioSystemOfValues;
import ch.idsia.benchmark.tasks.SystemOfValues;
public long bytecodeInstructions = MagicNumberUnDef;
public int levelLength = MagicNumberUnDef;
public int collisionsWithCreatures = MagicNumberUnDef;
private static final int[] retFloatArray = new int[EvaluationInfo.numberOfElements];
private static final int[] zeros = new int[EvaluationInfo.numberOfElements];
public String Memo = "";
private static final DecimalFormat df = new DecimalFormat("#.##");
private static MarioSystemOfValues marioSystemOfValues = new MarioSystemOfValues();
public int[][] marioTrace;
public String marioTraceFileName;
private long evaluationStarted = 0;
private long evaluationFinished = 0;
private long evaluationLasted = 0;
public EvaluationInfo()
{
System.arraycopy(EvaluationInfo.zeros, 0, retFloatArray, 0, EvaluationInfo.numberOfElements);
}
public int computeBasicFitness()
{
return distancePassedPhys - timeSpent + coinsGained + marioStatus * marioSystemOfValues.win;
}
|
public int computeWeightedFitness(SystemOfValues sov)
|
zerg000000/mario-ai
|
src/main/java/ch/idsia/benchmark/mario/engine/sprites/CoinAnim.java
|
// Path: src/main/java/ch/idsia/benchmark/mario/engine/Art.java
// public class Art
// {
// public static Image[][] mario;
// public static Image[][] racoonmario;
// public static Image[][] smallMario;
// public static Image[][] fireMario;
// public static Image[][] enemies;
// public static Image[][] items;
// public static Image[][] level;
// public static Image[][] particles;
// public static Image[][] font;
// public static Image[][] bg;
// public static Image[][] princess;
// // public static Image[][] map;
// // public static Image[][] endScene;
// // public static Image[][] gameOver;
// // public static Image logo;
// // public static Image titleScreen;
// // final static String curDir = System.getProperty("user.dir");
//
// public static void init(GraphicsConfiguration gc)
// {
// try
// {
// mario = cutImage(gc, "resources/mariosheet.png", 32, 32);
// racoonmario = cutImage(gc, "resources/racoonmariosheet.png", 32, 32);
// smallMario = cutImage(gc, "resources/smallmariosheet.png", 16, 16);
// fireMario = cutImage(gc, "resources/firemariosheet.png", 32, 32);
// enemies = cutImage(gc, "resources/enemysheet.png", 16, 32);
// items = cutImage(gc, "resources/itemsheet.png", 16, 16);
// level = cutImage(gc, "resources/mapsheet.png", 16, 16);
// // map = cutImage(gc, "resources/worldmap.png", 16, 16);
// particles = cutImage(gc, "resources/particlesheet.png", 8, 8);
// bg = cutImage(gc, "resources/bgsheet.png", 32, 32);
// // logo = getImage(gc, "resources/logo.gif");
// // titleScreen = getImage(gc, "resources/title.gif");
// font = cutImage(gc, "resources/font.gif", 8, 8);
// princess = cutImage(gc, "resources/princess.png", 32, 32);
// // endScene = cutImage(gc, "resources/endscene.gif", 96, 96);
// // gameOver = cutImage(gc, "resources/gameovergost.gif", 96, 64);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// }
//
// private static Image getImage(GraphicsConfiguration gc, String imageName) throws IOException
// {
// BufferedImage source = null;
// try
// { source = ImageIO.read(Art.class.getResourceAsStream(imageName)); }
// catch (Exception e) { e.printStackTrace(); }
//
// assert source != null;
// Image image = gc.createCompatibleImage(source.getWidth(), source.getHeight(), Transparency.BITMASK);
// Graphics2D g = (Graphics2D) image.getGraphics();
// g.setComposite(AlphaComposite.Src);
// g.drawImage(source, 0, 0, null);
// g.dispose();
// return image;
// }
//
// private static Image[][] cutImage(GraphicsConfiguration gc, String imageName, int xSize, int ySize) throws IOException
// {
// Image source = getImage(gc, imageName);
// Image[][] images = new Image[source.getWidth(null) / xSize][source.getHeight(null) / ySize];
// for (int x = 0; x < source.getWidth(null) / xSize; x++)
// {
// for (int y = 0; y < source.getHeight(null) / ySize; y++)
// {
// Image image = gc.createCompatibleImage(xSize, ySize, Transparency.BITMASK);
// Graphics2D g = (Graphics2D) image.getGraphics();
// g.setComposite(AlphaComposite.Src);
// g.drawImage(source, -x * xSize, -y * ySize, null);
// g.dispose();
// images[x][y] = image;
// }
// }
//
// return images;
// }
//
// }
|
import ch.idsia.benchmark.mario.engine.Art;
|
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.benchmark.mario.engine.sprites;
public class CoinAnim extends Sprite
{
private int life = 16;
public CoinAnim(int xTile, int yTile)
{
kind = KIND_COIN_ANIM;
|
// Path: src/main/java/ch/idsia/benchmark/mario/engine/Art.java
// public class Art
// {
// public static Image[][] mario;
// public static Image[][] racoonmario;
// public static Image[][] smallMario;
// public static Image[][] fireMario;
// public static Image[][] enemies;
// public static Image[][] items;
// public static Image[][] level;
// public static Image[][] particles;
// public static Image[][] font;
// public static Image[][] bg;
// public static Image[][] princess;
// // public static Image[][] map;
// // public static Image[][] endScene;
// // public static Image[][] gameOver;
// // public static Image logo;
// // public static Image titleScreen;
// // final static String curDir = System.getProperty("user.dir");
//
// public static void init(GraphicsConfiguration gc)
// {
// try
// {
// mario = cutImage(gc, "resources/mariosheet.png", 32, 32);
// racoonmario = cutImage(gc, "resources/racoonmariosheet.png", 32, 32);
// smallMario = cutImage(gc, "resources/smallmariosheet.png", 16, 16);
// fireMario = cutImage(gc, "resources/firemariosheet.png", 32, 32);
// enemies = cutImage(gc, "resources/enemysheet.png", 16, 32);
// items = cutImage(gc, "resources/itemsheet.png", 16, 16);
// level = cutImage(gc, "resources/mapsheet.png", 16, 16);
// // map = cutImage(gc, "resources/worldmap.png", 16, 16);
// particles = cutImage(gc, "resources/particlesheet.png", 8, 8);
// bg = cutImage(gc, "resources/bgsheet.png", 32, 32);
// // logo = getImage(gc, "resources/logo.gif");
// // titleScreen = getImage(gc, "resources/title.gif");
// font = cutImage(gc, "resources/font.gif", 8, 8);
// princess = cutImage(gc, "resources/princess.png", 32, 32);
// // endScene = cutImage(gc, "resources/endscene.gif", 96, 96);
// // gameOver = cutImage(gc, "resources/gameovergost.gif", 96, 64);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// }
//
// private static Image getImage(GraphicsConfiguration gc, String imageName) throws IOException
// {
// BufferedImage source = null;
// try
// { source = ImageIO.read(Art.class.getResourceAsStream(imageName)); }
// catch (Exception e) { e.printStackTrace(); }
//
// assert source != null;
// Image image = gc.createCompatibleImage(source.getWidth(), source.getHeight(), Transparency.BITMASK);
// Graphics2D g = (Graphics2D) image.getGraphics();
// g.setComposite(AlphaComposite.Src);
// g.drawImage(source, 0, 0, null);
// g.dispose();
// return image;
// }
//
// private static Image[][] cutImage(GraphicsConfiguration gc, String imageName, int xSize, int ySize) throws IOException
// {
// Image source = getImage(gc, imageName);
// Image[][] images = new Image[source.getWidth(null) / xSize][source.getHeight(null) / ySize];
// for (int x = 0; x < source.getWidth(null) / xSize; x++)
// {
// for (int y = 0; y < source.getHeight(null) / ySize; y++)
// {
// Image image = gc.createCompatibleImage(xSize, ySize, Transparency.BITMASK);
// Graphics2D g = (Graphics2D) image.getGraphics();
// g.setComposite(AlphaComposite.Src);
// g.drawImage(source, -x * xSize, -y * ySize, null);
// g.dispose();
// images[x][y] = image;
// }
// }
//
// return images;
// }
//
// }
// Path: src/main/java/ch/idsia/benchmark/mario/engine/sprites/CoinAnim.java
import ch.idsia.benchmark.mario.engine.Art;
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.benchmark.mario.engine.sprites;
public class CoinAnim extends Sprite
{
private int life = 16;
public CoinAnim(int xTile, int yTile)
{
kind = KIND_COIN_ANIM;
|
sheet = Art.level;
|
zerg000000/mario-ai
|
src/main/java/ch/idsia/benchmark/mario/engine/mapedit/LevelEditView.java
|
// Path: src/main/java/ch/idsia/benchmark/mario/engine/Art.java
// public class Art
// {
// public static Image[][] mario;
// public static Image[][] racoonmario;
// public static Image[][] smallMario;
// public static Image[][] fireMario;
// public static Image[][] enemies;
// public static Image[][] items;
// public static Image[][] level;
// public static Image[][] particles;
// public static Image[][] font;
// public static Image[][] bg;
// public static Image[][] princess;
// // public static Image[][] map;
// // public static Image[][] endScene;
// // public static Image[][] gameOver;
// // public static Image logo;
// // public static Image titleScreen;
// // final static String curDir = System.getProperty("user.dir");
//
// public static void init(GraphicsConfiguration gc)
// {
// try
// {
// mario = cutImage(gc, "resources/mariosheet.png", 32, 32);
// racoonmario = cutImage(gc, "resources/racoonmariosheet.png", 32, 32);
// smallMario = cutImage(gc, "resources/smallmariosheet.png", 16, 16);
// fireMario = cutImage(gc, "resources/firemariosheet.png", 32, 32);
// enemies = cutImage(gc, "resources/enemysheet.png", 16, 32);
// items = cutImage(gc, "resources/itemsheet.png", 16, 16);
// level = cutImage(gc, "resources/mapsheet.png", 16, 16);
// // map = cutImage(gc, "resources/worldmap.png", 16, 16);
// particles = cutImage(gc, "resources/particlesheet.png", 8, 8);
// bg = cutImage(gc, "resources/bgsheet.png", 32, 32);
// // logo = getImage(gc, "resources/logo.gif");
// // titleScreen = getImage(gc, "resources/title.gif");
// font = cutImage(gc, "resources/font.gif", 8, 8);
// princess = cutImage(gc, "resources/princess.png", 32, 32);
// // endScene = cutImage(gc, "resources/endscene.gif", 96, 96);
// // gameOver = cutImage(gc, "resources/gameovergost.gif", 96, 64);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// }
//
// private static Image getImage(GraphicsConfiguration gc, String imageName) throws IOException
// {
// BufferedImage source = null;
// try
// { source = ImageIO.read(Art.class.getResourceAsStream(imageName)); }
// catch (Exception e) { e.printStackTrace(); }
//
// assert source != null;
// Image image = gc.createCompatibleImage(source.getWidth(), source.getHeight(), Transparency.BITMASK);
// Graphics2D g = (Graphics2D) image.getGraphics();
// g.setComposite(AlphaComposite.Src);
// g.drawImage(source, 0, 0, null);
// g.dispose();
// return image;
// }
//
// private static Image[][] cutImage(GraphicsConfiguration gc, String imageName, int xSize, int ySize) throws IOException
// {
// Image source = getImage(gc, imageName);
// Image[][] images = new Image[source.getWidth(null) / xSize][source.getHeight(null) / ySize];
// for (int x = 0; x < source.getWidth(null) / xSize; x++)
// {
// for (int y = 0; y < source.getHeight(null) / ySize; y++)
// {
// Image image = gc.createCompatibleImage(xSize, ySize, Transparency.BITMASK);
// Graphics2D g = (Graphics2D) image.getGraphics();
// g.setComposite(AlphaComposite.Src);
// g.drawImage(source, -x * xSize, -y * ySize, null);
// g.dispose();
// images[x][y] = image;
// }
// }
//
// return images;
// }
//
// }
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import ch.idsia.benchmark.mario.engine.Art;
import ch.idsia.benchmark.mario.engine.LevelRenderer;
import ch.idsia.benchmark.mario.engine.level.Level;
|
this.tilePicker = tilePicker;
level = new Level(256, 15);
Dimension size = new Dimension(level.length * 16, level.height * 16);
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
addMouseListener(this);
addMouseMotionListener(this);
}
public void setLevel(Level level)
{
this.level = level;
Dimension size = new Dimension(level.length * 16, level.height * 16);
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
repaint();
levelRenderer.setLevel(level);
}
public Level getLevel()
{
return level;
}
public void addNotify()
{
super.addNotify();
|
// Path: src/main/java/ch/idsia/benchmark/mario/engine/Art.java
// public class Art
// {
// public static Image[][] mario;
// public static Image[][] racoonmario;
// public static Image[][] smallMario;
// public static Image[][] fireMario;
// public static Image[][] enemies;
// public static Image[][] items;
// public static Image[][] level;
// public static Image[][] particles;
// public static Image[][] font;
// public static Image[][] bg;
// public static Image[][] princess;
// // public static Image[][] map;
// // public static Image[][] endScene;
// // public static Image[][] gameOver;
// // public static Image logo;
// // public static Image titleScreen;
// // final static String curDir = System.getProperty("user.dir");
//
// public static void init(GraphicsConfiguration gc)
// {
// try
// {
// mario = cutImage(gc, "resources/mariosheet.png", 32, 32);
// racoonmario = cutImage(gc, "resources/racoonmariosheet.png", 32, 32);
// smallMario = cutImage(gc, "resources/smallmariosheet.png", 16, 16);
// fireMario = cutImage(gc, "resources/firemariosheet.png", 32, 32);
// enemies = cutImage(gc, "resources/enemysheet.png", 16, 32);
// items = cutImage(gc, "resources/itemsheet.png", 16, 16);
// level = cutImage(gc, "resources/mapsheet.png", 16, 16);
// // map = cutImage(gc, "resources/worldmap.png", 16, 16);
// particles = cutImage(gc, "resources/particlesheet.png", 8, 8);
// bg = cutImage(gc, "resources/bgsheet.png", 32, 32);
// // logo = getImage(gc, "resources/logo.gif");
// // titleScreen = getImage(gc, "resources/title.gif");
// font = cutImage(gc, "resources/font.gif", 8, 8);
// princess = cutImage(gc, "resources/princess.png", 32, 32);
// // endScene = cutImage(gc, "resources/endscene.gif", 96, 96);
// // gameOver = cutImage(gc, "resources/gameovergost.gif", 96, 64);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// }
//
// private static Image getImage(GraphicsConfiguration gc, String imageName) throws IOException
// {
// BufferedImage source = null;
// try
// { source = ImageIO.read(Art.class.getResourceAsStream(imageName)); }
// catch (Exception e) { e.printStackTrace(); }
//
// assert source != null;
// Image image = gc.createCompatibleImage(source.getWidth(), source.getHeight(), Transparency.BITMASK);
// Graphics2D g = (Graphics2D) image.getGraphics();
// g.setComposite(AlphaComposite.Src);
// g.drawImage(source, 0, 0, null);
// g.dispose();
// return image;
// }
//
// private static Image[][] cutImage(GraphicsConfiguration gc, String imageName, int xSize, int ySize) throws IOException
// {
// Image source = getImage(gc, imageName);
// Image[][] images = new Image[source.getWidth(null) / xSize][source.getHeight(null) / ySize];
// for (int x = 0; x < source.getWidth(null) / xSize; x++)
// {
// for (int y = 0; y < source.getHeight(null) / ySize; y++)
// {
// Image image = gc.createCompatibleImage(xSize, ySize, Transparency.BITMASK);
// Graphics2D g = (Graphics2D) image.getGraphics();
// g.setComposite(AlphaComposite.Src);
// g.drawImage(source, -x * xSize, -y * ySize, null);
// g.dispose();
// images[x][y] = image;
// }
// }
//
// return images;
// }
//
// }
// Path: src/main/java/ch/idsia/benchmark/mario/engine/mapedit/LevelEditView.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import ch.idsia.benchmark.mario.engine.Art;
import ch.idsia.benchmark.mario.engine.LevelRenderer;
import ch.idsia.benchmark.mario.engine.level.Level;
this.tilePicker = tilePicker;
level = new Level(256, 15);
Dimension size = new Dimension(level.length * 16, level.height * 16);
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
addMouseListener(this);
addMouseMotionListener(this);
}
public void setLevel(Level level)
{
this.level = level;
Dimension size = new Dimension(level.length * 16, level.height * 16);
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
repaint();
levelRenderer.setLevel(level);
}
public Level getLevel()
{
return level;
}
public void addNotify()
{
super.addNotify();
|
Art.init(getGraphicsConfiguration());
|
zerg000000/mario-ai
|
src/main/java/ch/idsia/tools/ReplayerOptions.java
|
// Path: src/main/java/ch/idsia/benchmark/mario/engine/GlobalOptions.java
// public abstract class GlobalOptions
// {
// public static final int primaryVerionUID = 0;
// public static final int minorVerionUID = 1;
// public static final int minorSubVerionID = 9;
//
// public static boolean areLabels = false;
// public static boolean isCameraCenteredOnMario = false;
// public static Integer FPS = 24;
// public static int MaxFPS = 100;
// public static boolean areFrozenCreatures = false;
//
// public static boolean isVisualization = true;
// public static boolean isGameplayStopped = false;
// public static boolean isFly = false;
//
// private static GameViewer GameViewer = null;
// // public static boolean isTimer = true;
//
// public static int mariosecondMultiplier = 15;
//
// public static boolean isPowerRestoration;
//
// // required for rendering grid in ch/idsia/benchmark/mario/engine/sprites/Sprite.java
// public static int receptiveFieldWidth = 19;
// public static int receptiveFieldHeight = 19;
// public static int marioEgoCol = 9;
// public static int marioEgoRow = 9;
//
// private static MarioVisualComponent marioVisualComponent;
// public static int VISUAL_COMPONENT_WIDTH = 320;
// public static int VISUAL_COMPONENT_HEIGHT = 240;
//
// public static boolean isShowReceptiveField = false;
// public static boolean isScale2x = false;
// public static boolean isRecording = false;
// public static boolean isReplaying = false;
//
// public static int getPrimaryVersionUID()
// {
// return primaryVerionUID;
// }
//
// public static int getMinorVersionUID()
// {
// return minorVerionUID;
// }
//
// public static int getMinorSubVersionID()
// {
// return minorSubVerionID;
// }
//
// public static String getBenchmarkName()
// {
// return "[~ Mario AI Benchmark ~" + GlobalOptions.getVersionUID() + "]";
// }
//
// public static String getVersionUID()
// {
// return " " + getPrimaryVersionUID() + "." + getMinorVersionUID() + "." + getMinorSubVersionID();
// }
//
// public static void registerMarioVisualComponent(MarioVisualComponent mc)
// {
// marioVisualComponent = mc;
// }
//
// public static void registerGameViewer(GameViewer gv)
// {
// GameViewer = gv;
// }
//
// public static void AdjustMarioVisualComponentFPS()
// {
// if (marioVisualComponent != null)
// marioVisualComponent.adjustFPS();
// }
//
// public static void gameViewerTick()
// {
// if (GameViewer != null)
// GameViewer.tick();
// }
//
// public static String getDateTime(Long d)
// {
// final DateFormat dateFormat = (d == null) ? new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:ms") :
// new SimpleDateFormat("HH:mm:ss:ms");
// if (d != null)
// dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
// final Date date = (d == null) ? new Date() : new Date(d);
// return dateFormat.format(date);
// }
//
// final static private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
//
// public static String getTimeStamp()
// {
// return dateFormat.format(new Date());
// }
//
// public static void changeScale2x()
// {
// if (marioVisualComponent == null)
// return;
//
// isScale2x = !isScale2x;
// marioVisualComponent.width *= isScale2x ? 2 : 0.5;
// marioVisualComponent.height *= isScale2x ? 2 : 0.5;
// marioVisualComponent.changeScale2x();
// }
// }
|
import java.util.LinkedList;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ch.idsia.benchmark.mario.engine.GlobalOptions;
import java.io.Serializable;
|
{
String s = replays.poll();
if (s == null)
return null;
String[] subgroups = s.split(";");
if (subgroups.length == 0)
return null;
String fileName = subgroups[0];
chunks.clear();
if (subgroups.length > 1)
for (int i = 1; i < subgroups.length; i++)
chunks.add(new Interval(subgroups[i]));
return fileName;
}
public Interval getNextIntervalInMarioseconds()
{
return chunks.poll();
}
public Interval getNextIntervalInTicks()
{
Interval i = chunks.poll();
Interval res = null;
if (i != null)
|
// Path: src/main/java/ch/idsia/benchmark/mario/engine/GlobalOptions.java
// public abstract class GlobalOptions
// {
// public static final int primaryVerionUID = 0;
// public static final int minorVerionUID = 1;
// public static final int minorSubVerionID = 9;
//
// public static boolean areLabels = false;
// public static boolean isCameraCenteredOnMario = false;
// public static Integer FPS = 24;
// public static int MaxFPS = 100;
// public static boolean areFrozenCreatures = false;
//
// public static boolean isVisualization = true;
// public static boolean isGameplayStopped = false;
// public static boolean isFly = false;
//
// private static GameViewer GameViewer = null;
// // public static boolean isTimer = true;
//
// public static int mariosecondMultiplier = 15;
//
// public static boolean isPowerRestoration;
//
// // required for rendering grid in ch/idsia/benchmark/mario/engine/sprites/Sprite.java
// public static int receptiveFieldWidth = 19;
// public static int receptiveFieldHeight = 19;
// public static int marioEgoCol = 9;
// public static int marioEgoRow = 9;
//
// private static MarioVisualComponent marioVisualComponent;
// public static int VISUAL_COMPONENT_WIDTH = 320;
// public static int VISUAL_COMPONENT_HEIGHT = 240;
//
// public static boolean isShowReceptiveField = false;
// public static boolean isScale2x = false;
// public static boolean isRecording = false;
// public static boolean isReplaying = false;
//
// public static int getPrimaryVersionUID()
// {
// return primaryVerionUID;
// }
//
// public static int getMinorVersionUID()
// {
// return minorVerionUID;
// }
//
// public static int getMinorSubVersionID()
// {
// return minorSubVerionID;
// }
//
// public static String getBenchmarkName()
// {
// return "[~ Mario AI Benchmark ~" + GlobalOptions.getVersionUID() + "]";
// }
//
// public static String getVersionUID()
// {
// return " " + getPrimaryVersionUID() + "." + getMinorVersionUID() + "." + getMinorSubVersionID();
// }
//
// public static void registerMarioVisualComponent(MarioVisualComponent mc)
// {
// marioVisualComponent = mc;
// }
//
// public static void registerGameViewer(GameViewer gv)
// {
// GameViewer = gv;
// }
//
// public static void AdjustMarioVisualComponentFPS()
// {
// if (marioVisualComponent != null)
// marioVisualComponent.adjustFPS();
// }
//
// public static void gameViewerTick()
// {
// if (GameViewer != null)
// GameViewer.tick();
// }
//
// public static String getDateTime(Long d)
// {
// final DateFormat dateFormat = (d == null) ? new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:ms") :
// new SimpleDateFormat("HH:mm:ss:ms");
// if (d != null)
// dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
// final Date date = (d == null) ? new Date() : new Date(d);
// return dateFormat.format(date);
// }
//
// final static private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
//
// public static String getTimeStamp()
// {
// return dateFormat.format(new Date());
// }
//
// public static void changeScale2x()
// {
// if (marioVisualComponent == null)
// return;
//
// isScale2x = !isScale2x;
// marioVisualComponent.width *= isScale2x ? 2 : 0.5;
// marioVisualComponent.height *= isScale2x ? 2 : 0.5;
// marioVisualComponent.changeScale2x();
// }
// }
// Path: src/main/java/ch/idsia/tools/ReplayerOptions.java
import java.util.LinkedList;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ch.idsia.benchmark.mario.engine.GlobalOptions;
import java.io.Serializable;
{
String s = replays.poll();
if (s == null)
return null;
String[] subgroups = s.split(";");
if (subgroups.length == 0)
return null;
String fileName = subgroups[0];
chunks.clear();
if (subgroups.length > 1)
for (int i = 1; i < subgroups.length; i++)
chunks.add(new Interval(subgroups[i]));
return fileName;
}
public Interval getNextIntervalInMarioseconds()
{
return chunks.poll();
}
public Interval getNextIntervalInTicks()
{
Interval i = chunks.poll();
Interval res = null;
if (i != null)
|
res = new Interval(i.from * GlobalOptions.mariosecondMultiplier, i.to * GlobalOptions.mariosecondMultiplier);
|
zerg000000/mario-ai
|
src/main/java/ch/idsia/agents/controllers/ReplayAgent.java
|
// Path: src/main/java/ch/idsia/benchmark/mario/engine/Replayer.java
// public class Replayer
// {
// private ZipFile zf = null;
// private ZipEntry ze = null;
// private BufferedInputStream fis;
// private ReplayerOptions options;
//
// public Replayer(String replayOptions)
// {
// this.options = new ReplayerOptions(replayOptions);
// }
//
// public boolean openNextReplayFile() throws IOException
// {
// // if (zf != null)
// // zf.close();
//
// String fileName = options.getNextReplayFile();
// if (fileName == null)
// return false;
//
// if (!fileName.endsWith(".zip"))
// fileName += ".zip";
//
// zf = new ZipFile(fileName);
// ze = null;
// fis = null;
//
// try
// {
// openFile("chunks");
// options.setChunks((Queue) readObject());
// } catch (Exception ignored)
// {} //if file with replay chunks not found, than use user specified chunks
//
// return true;
// }
//
// public void openFile(String filename) throws Exception
// {
// ze = zf.getEntry(filename);
//
// if (ze == null)
// throw new Exception("[Mario AI EXCEPTION] : File <" + filename + "> not found in the archive");
// }
//
// private void openBufferedInputStream() throws IOException
// {
// fis = new BufferedInputStream(zf.getInputStream(ze));
// }
//
// public boolean[] readAction() throws IOException
// {
// if (fis == null)
// openBufferedInputStream();
//
// boolean[] buffer = new boolean[Environment.numberOfKeys];
// // int count = fis.read(buffer, 0, size);
// byte actions = (byte) fis.read();
// for (int i = 0; i < Environment.numberOfKeys; i++)
// {
// if ((actions & (1 << i)) > 0)
// buffer[i] = true;
// else
// buffer[i] = false;
// }
//
// if (actions == -1)
// buffer = null;
//
// return buffer;
// }
//
// public Object readObject() throws IOException, ClassNotFoundException
// {
// ObjectInputStream ois = new ObjectInputStream(zf.getInputStream(ze));
// Object res = ois.readObject();
// // ois.close();
//
// return res;
// }
//
// public void closeFile() throws IOException
// {
// // fis.close();
// }
//
// public void closeReplayFile() throws IOException
// {
// zf.close();
// }
//
// public boolean hasMoreChunks()
// {
// return options.hasMoreChunks();
// }
//
// public int actionsFileSize()
// {
// int size = (int) ze.getSize();
// if (size == -1)
// size = Integer.MAX_VALUE;
// return size;
// }
//
// public ReplayerOptions.Interval getNextIntervalInMarioseconds()
// {
// return options.getNextIntervalInMarioseconds();
// }
//
// public ReplayerOptions.Interval getNextIntervalInTicks()
// {
// return options.getNextIntervalInTicks();
// }
// }
|
import java.io.IOException;
import ch.idsia.agents.Agent;
import ch.idsia.benchmark.mario.engine.Replayer;
import ch.idsia.benchmark.mario.environments.Environment;
|
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.agents.controllers;
/**
* Created by IntelliJ IDEA.
* User: Sergey Karakovskiy, sergey.karakovskiy@gmail.com
* Date: Oct 9, 2010
* Time: 2:08:47 AM
* Package: ch.idsia.agents.controllers
*/
public class ReplayAgent implements Agent
{
|
// Path: src/main/java/ch/idsia/benchmark/mario/engine/Replayer.java
// public class Replayer
// {
// private ZipFile zf = null;
// private ZipEntry ze = null;
// private BufferedInputStream fis;
// private ReplayerOptions options;
//
// public Replayer(String replayOptions)
// {
// this.options = new ReplayerOptions(replayOptions);
// }
//
// public boolean openNextReplayFile() throws IOException
// {
// // if (zf != null)
// // zf.close();
//
// String fileName = options.getNextReplayFile();
// if (fileName == null)
// return false;
//
// if (!fileName.endsWith(".zip"))
// fileName += ".zip";
//
// zf = new ZipFile(fileName);
// ze = null;
// fis = null;
//
// try
// {
// openFile("chunks");
// options.setChunks((Queue) readObject());
// } catch (Exception ignored)
// {} //if file with replay chunks not found, than use user specified chunks
//
// return true;
// }
//
// public void openFile(String filename) throws Exception
// {
// ze = zf.getEntry(filename);
//
// if (ze == null)
// throw new Exception("[Mario AI EXCEPTION] : File <" + filename + "> not found in the archive");
// }
//
// private void openBufferedInputStream() throws IOException
// {
// fis = new BufferedInputStream(zf.getInputStream(ze));
// }
//
// public boolean[] readAction() throws IOException
// {
// if (fis == null)
// openBufferedInputStream();
//
// boolean[] buffer = new boolean[Environment.numberOfKeys];
// // int count = fis.read(buffer, 0, size);
// byte actions = (byte) fis.read();
// for (int i = 0; i < Environment.numberOfKeys; i++)
// {
// if ((actions & (1 << i)) > 0)
// buffer[i] = true;
// else
// buffer[i] = false;
// }
//
// if (actions == -1)
// buffer = null;
//
// return buffer;
// }
//
// public Object readObject() throws IOException, ClassNotFoundException
// {
// ObjectInputStream ois = new ObjectInputStream(zf.getInputStream(ze));
// Object res = ois.readObject();
// // ois.close();
//
// return res;
// }
//
// public void closeFile() throws IOException
// {
// // fis.close();
// }
//
// public void closeReplayFile() throws IOException
// {
// zf.close();
// }
//
// public boolean hasMoreChunks()
// {
// return options.hasMoreChunks();
// }
//
// public int actionsFileSize()
// {
// int size = (int) ze.getSize();
// if (size == -1)
// size = Integer.MAX_VALUE;
// return size;
// }
//
// public ReplayerOptions.Interval getNextIntervalInMarioseconds()
// {
// return options.getNextIntervalInMarioseconds();
// }
//
// public ReplayerOptions.Interval getNextIntervalInTicks()
// {
// return options.getNextIntervalInTicks();
// }
// }
// Path: src/main/java/ch/idsia/agents/controllers/ReplayAgent.java
import java.io.IOException;
import ch.idsia.agents.Agent;
import ch.idsia.benchmark.mario.engine.Replayer;
import ch.idsia.benchmark.mario.environments.Environment;
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.agents.controllers;
/**
* Created by IntelliJ IDEA.
* User: Sergey Karakovskiy, sergey.karakovskiy@gmail.com
* Date: Oct 9, 2010
* Time: 2:08:47 AM
* Package: ch.idsia.agents.controllers
*/
public class ReplayAgent implements Agent
{
|
private Replayer replayer;
|
zerg000000/mario-ai
|
src/main/java/ch/idsia/agents/SRNESLearningAgent.java
|
// Path: src/main/java/ch/idsia/benchmark/tasks/LearningTask.java
// public class LearningTask extends BasicTask implements Task
// {
// private static final long EVALUATION_QUOTA = 100000;
// private long currentEvaluation = 0;
// public int uid;
//
// private String fileTimeStamp = "-uid-" + uid + "-" + GlobalOptions.getTimeStamp();
// private int fitnessEvaluations = 0;
//
// public LearningTask(MarioAIOptions marioAIOptions)
// {
// super(marioAIOptions);
// }
//
// public void reset(MarioAIOptions marioAIOptions)
// {
// options = marioAIOptions;
// environment.reset(marioAIOptions);
// }
//
// public int evaluate(Agent agent)
// {
// if (currentEvaluation++ > EVALUATION_QUOTA)
// return 0;
// options.setAgent(agent);
// environment.reset(options);
// fitnessEvaluations++; // TODO : remove either or two currentEvaluation or fitnessEvaluations
// this.runSingleEpisode(1);
// return this.getEvaluationInfo().computeWeightedFitness();
// }
//
// public static long getEvaluationQuota()
// {return LearningTask.EVALUATION_QUOTA;}
//
// public void dumpFitnessEvaluation(float fitness, String fileName)
// {
// try
// {
// BufferedWriter out = new BufferedWriter(new FileWriter(fileName + fileTimeStamp + ".txt", true));
// out.write(this.fitnessEvaluations + " " + fitness + "\n");
// out.close();
// } catch (IOException e)
// {
// e.printStackTrace();
// }
// }
//
// }
//
// Path: src/main/java/ch/idsia/benchmark/tasks/Task.java
// public interface Task
// {
// public int evaluate(final Agent controller);
//
// public void setOptionsAndReset(final MarioAIOptions options);
//
// public void setOptionsAndReset(final String options);
//
// void reset();
//
// void doEpisodes(final int amount, final boolean verbose, final int repetitionsOfSingleEpisode);
//
// boolean isFinished();
//
// public String getName();
//
// public void printStatistics();
// }
|
import ch.idsia.benchmark.tasks.Task;
import ch.idsia.evolution.ea.ES;
import ch.idsia.agents.learning.MediumSRNAgent;
import ch.idsia.benchmark.mario.environments.Environment;
import ch.idsia.benchmark.tasks.LearningTask;
|
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.agents;
/**
* Created by IntelliJ IDEA.
* User: odin
* Date: Jul 27, 2010
* Time: 9:40:09 PM
*/
public class SRNESLearningAgent implements LearningAgent
{
private MediumSRNAgent agent;
Agent bestAgent;
private static float bestScore = 0;
|
// Path: src/main/java/ch/idsia/benchmark/tasks/LearningTask.java
// public class LearningTask extends BasicTask implements Task
// {
// private static final long EVALUATION_QUOTA = 100000;
// private long currentEvaluation = 0;
// public int uid;
//
// private String fileTimeStamp = "-uid-" + uid + "-" + GlobalOptions.getTimeStamp();
// private int fitnessEvaluations = 0;
//
// public LearningTask(MarioAIOptions marioAIOptions)
// {
// super(marioAIOptions);
// }
//
// public void reset(MarioAIOptions marioAIOptions)
// {
// options = marioAIOptions;
// environment.reset(marioAIOptions);
// }
//
// public int evaluate(Agent agent)
// {
// if (currentEvaluation++ > EVALUATION_QUOTA)
// return 0;
// options.setAgent(agent);
// environment.reset(options);
// fitnessEvaluations++; // TODO : remove either or two currentEvaluation or fitnessEvaluations
// this.runSingleEpisode(1);
// return this.getEvaluationInfo().computeWeightedFitness();
// }
//
// public static long getEvaluationQuota()
// {return LearningTask.EVALUATION_QUOTA;}
//
// public void dumpFitnessEvaluation(float fitness, String fileName)
// {
// try
// {
// BufferedWriter out = new BufferedWriter(new FileWriter(fileName + fileTimeStamp + ".txt", true));
// out.write(this.fitnessEvaluations + " " + fitness + "\n");
// out.close();
// } catch (IOException e)
// {
// e.printStackTrace();
// }
// }
//
// }
//
// Path: src/main/java/ch/idsia/benchmark/tasks/Task.java
// public interface Task
// {
// public int evaluate(final Agent controller);
//
// public void setOptionsAndReset(final MarioAIOptions options);
//
// public void setOptionsAndReset(final String options);
//
// void reset();
//
// void doEpisodes(final int amount, final boolean verbose, final int repetitionsOfSingleEpisode);
//
// boolean isFinished();
//
// public String getName();
//
// public void printStatistics();
// }
// Path: src/main/java/ch/idsia/agents/SRNESLearningAgent.java
import ch.idsia.benchmark.tasks.Task;
import ch.idsia.evolution.ea.ES;
import ch.idsia.agents.learning.MediumSRNAgent;
import ch.idsia.benchmark.mario.environments.Environment;
import ch.idsia.benchmark.tasks.LearningTask;
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.agents;
/**
* Created by IntelliJ IDEA.
* User: odin
* Date: Jul 27, 2010
* Time: 9:40:09 PM
*/
public class SRNESLearningAgent implements LearningAgent
{
private MediumSRNAgent agent;
Agent bestAgent;
private static float bestScore = 0;
|
private Task task;
|
zerg000000/mario-ai
|
src/main/java/ch/idsia/agents/SRNESLearningAgent.java
|
// Path: src/main/java/ch/idsia/benchmark/tasks/LearningTask.java
// public class LearningTask extends BasicTask implements Task
// {
// private static final long EVALUATION_QUOTA = 100000;
// private long currentEvaluation = 0;
// public int uid;
//
// private String fileTimeStamp = "-uid-" + uid + "-" + GlobalOptions.getTimeStamp();
// private int fitnessEvaluations = 0;
//
// public LearningTask(MarioAIOptions marioAIOptions)
// {
// super(marioAIOptions);
// }
//
// public void reset(MarioAIOptions marioAIOptions)
// {
// options = marioAIOptions;
// environment.reset(marioAIOptions);
// }
//
// public int evaluate(Agent agent)
// {
// if (currentEvaluation++ > EVALUATION_QUOTA)
// return 0;
// options.setAgent(agent);
// environment.reset(options);
// fitnessEvaluations++; // TODO : remove either or two currentEvaluation or fitnessEvaluations
// this.runSingleEpisode(1);
// return this.getEvaluationInfo().computeWeightedFitness();
// }
//
// public static long getEvaluationQuota()
// {return LearningTask.EVALUATION_QUOTA;}
//
// public void dumpFitnessEvaluation(float fitness, String fileName)
// {
// try
// {
// BufferedWriter out = new BufferedWriter(new FileWriter(fileName + fileTimeStamp + ".txt", true));
// out.write(this.fitnessEvaluations + " " + fitness + "\n");
// out.close();
// } catch (IOException e)
// {
// e.printStackTrace();
// }
// }
//
// }
//
// Path: src/main/java/ch/idsia/benchmark/tasks/Task.java
// public interface Task
// {
// public int evaluate(final Agent controller);
//
// public void setOptionsAndReset(final MarioAIOptions options);
//
// public void setOptionsAndReset(final String options);
//
// void reset();
//
// void doEpisodes(final int amount, final boolean verbose, final int repetitionsOfSingleEpisode);
//
// boolean isFinished();
//
// public String getName();
//
// public void printStatistics();
// }
|
import ch.idsia.benchmark.tasks.Task;
import ch.idsia.evolution.ea.ES;
import ch.idsia.agents.learning.MediumSRNAgent;
import ch.idsia.benchmark.mario.environments.Environment;
import ch.idsia.benchmark.tasks.LearningTask;
|
{
this.currentEvaluation++;
int localBestScore = 0;
for (int gen = 0; gen < generations; gen++)
{
System.out.println(gen + " generation");
es.nextGeneration();
float fitn = es.getBestFitnesses()[0];
if (fitn > bestScore)
{
bestScore = fitn;
bestAgent = (Agent) es.getBests()[0];
}
}
}
public void giveReward(float r)
{
}
public void newEpisode()
{
task = null;
agent.reset();
}
|
// Path: src/main/java/ch/idsia/benchmark/tasks/LearningTask.java
// public class LearningTask extends BasicTask implements Task
// {
// private static final long EVALUATION_QUOTA = 100000;
// private long currentEvaluation = 0;
// public int uid;
//
// private String fileTimeStamp = "-uid-" + uid + "-" + GlobalOptions.getTimeStamp();
// private int fitnessEvaluations = 0;
//
// public LearningTask(MarioAIOptions marioAIOptions)
// {
// super(marioAIOptions);
// }
//
// public void reset(MarioAIOptions marioAIOptions)
// {
// options = marioAIOptions;
// environment.reset(marioAIOptions);
// }
//
// public int evaluate(Agent agent)
// {
// if (currentEvaluation++ > EVALUATION_QUOTA)
// return 0;
// options.setAgent(agent);
// environment.reset(options);
// fitnessEvaluations++; // TODO : remove either or two currentEvaluation or fitnessEvaluations
// this.runSingleEpisode(1);
// return this.getEvaluationInfo().computeWeightedFitness();
// }
//
// public static long getEvaluationQuota()
// {return LearningTask.EVALUATION_QUOTA;}
//
// public void dumpFitnessEvaluation(float fitness, String fileName)
// {
// try
// {
// BufferedWriter out = new BufferedWriter(new FileWriter(fileName + fileTimeStamp + ".txt", true));
// out.write(this.fitnessEvaluations + " " + fitness + "\n");
// out.close();
// } catch (IOException e)
// {
// e.printStackTrace();
// }
// }
//
// }
//
// Path: src/main/java/ch/idsia/benchmark/tasks/Task.java
// public interface Task
// {
// public int evaluate(final Agent controller);
//
// public void setOptionsAndReset(final MarioAIOptions options);
//
// public void setOptionsAndReset(final String options);
//
// void reset();
//
// void doEpisodes(final int amount, final boolean verbose, final int repetitionsOfSingleEpisode);
//
// boolean isFinished();
//
// public String getName();
//
// public void printStatistics();
// }
// Path: src/main/java/ch/idsia/agents/SRNESLearningAgent.java
import ch.idsia.benchmark.tasks.Task;
import ch.idsia.evolution.ea.ES;
import ch.idsia.agents.learning.MediumSRNAgent;
import ch.idsia.benchmark.mario.environments.Environment;
import ch.idsia.benchmark.tasks.LearningTask;
{
this.currentEvaluation++;
int localBestScore = 0;
for (int gen = 0; gen < generations; gen++)
{
System.out.println(gen + " generation");
es.nextGeneration();
float fitn = es.getBestFitnesses()[0];
if (fitn > bestScore)
{
bestScore = fitn;
bestAgent = (Agent) es.getBests()[0];
}
}
}
public void giveReward(float r)
{
}
public void newEpisode()
{
task = null;
agent.reset();
}
|
public void setLearningTask(LearningTask learningTask)
|
zerg000000/mario-ai
|
src/main/java/ch/idsia/agents/controllers/human/CheaterKeyboardAgent.java
|
// Path: src/main/java/ch/idsia/benchmark/mario/engine/GlobalOptions.java
// public abstract class GlobalOptions
// {
// public static final int primaryVerionUID = 0;
// public static final int minorVerionUID = 1;
// public static final int minorSubVerionID = 9;
//
// public static boolean areLabels = false;
// public static boolean isCameraCenteredOnMario = false;
// public static Integer FPS = 24;
// public static int MaxFPS = 100;
// public static boolean areFrozenCreatures = false;
//
// public static boolean isVisualization = true;
// public static boolean isGameplayStopped = false;
// public static boolean isFly = false;
//
// private static GameViewer GameViewer = null;
// // public static boolean isTimer = true;
//
// public static int mariosecondMultiplier = 15;
//
// public static boolean isPowerRestoration;
//
// // required for rendering grid in ch/idsia/benchmark/mario/engine/sprites/Sprite.java
// public static int receptiveFieldWidth = 19;
// public static int receptiveFieldHeight = 19;
// public static int marioEgoCol = 9;
// public static int marioEgoRow = 9;
//
// private static MarioVisualComponent marioVisualComponent;
// public static int VISUAL_COMPONENT_WIDTH = 320;
// public static int VISUAL_COMPONENT_HEIGHT = 240;
//
// public static boolean isShowReceptiveField = false;
// public static boolean isScale2x = false;
// public static boolean isRecording = false;
// public static boolean isReplaying = false;
//
// public static int getPrimaryVersionUID()
// {
// return primaryVerionUID;
// }
//
// public static int getMinorVersionUID()
// {
// return minorVerionUID;
// }
//
// public static int getMinorSubVersionID()
// {
// return minorSubVerionID;
// }
//
// public static String getBenchmarkName()
// {
// return "[~ Mario AI Benchmark ~" + GlobalOptions.getVersionUID() + "]";
// }
//
// public static String getVersionUID()
// {
// return " " + getPrimaryVersionUID() + "." + getMinorVersionUID() + "." + getMinorSubVersionID();
// }
//
// public static void registerMarioVisualComponent(MarioVisualComponent mc)
// {
// marioVisualComponent = mc;
// }
//
// public static void registerGameViewer(GameViewer gv)
// {
// GameViewer = gv;
// }
//
// public static void AdjustMarioVisualComponentFPS()
// {
// if (marioVisualComponent != null)
// marioVisualComponent.adjustFPS();
// }
//
// public static void gameViewerTick()
// {
// if (GameViewer != null)
// GameViewer.tick();
// }
//
// public static String getDateTime(Long d)
// {
// final DateFormat dateFormat = (d == null) ? new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:ms") :
// new SimpleDateFormat("HH:mm:ss:ms");
// if (d != null)
// dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
// final Date date = (d == null) ? new Date() : new Date(d);
// return dateFormat.format(date);
// }
//
// final static private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
//
// public static String getTimeStamp()
// {
// return dateFormat.format(new Date());
// }
//
// public static void changeScale2x()
// {
// if (marioVisualComponent == null)
// return;
//
// isScale2x = !isScale2x;
// marioVisualComponent.width *= isScale2x ? 2 : 0.5;
// marioVisualComponent.height *= isScale2x ? 2 : 0.5;
// marioVisualComponent.changeScale2x();
// }
// }
|
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import ch.idsia.agents.Agent;
import ch.idsia.benchmark.mario.engine.GlobalOptions;
import ch.idsia.benchmark.mario.environments.Environment;
|
{
// move your coffee away from the keyboard..
Action = new boolean[16];
}
public void setObservationDetails(final int rfWidth, final int rfHeight, final int egoRow, final int egoCol)
{}
public String getName() { return Name; }
public void setName(String name) { Name = name; }
public void keyPressed(KeyEvent e)
{
toggleKey(e.getKeyCode(), true);
}
public void keyReleased(KeyEvent e)
{
toggleKey(e.getKeyCode(), false);
}
private void toggleKey(int keyCode, boolean isPressed)
{
switch (keyCode)
{
//Cheats;
case KeyEvent.VK_D:
if (isPressed)
|
// Path: src/main/java/ch/idsia/benchmark/mario/engine/GlobalOptions.java
// public abstract class GlobalOptions
// {
// public static final int primaryVerionUID = 0;
// public static final int minorVerionUID = 1;
// public static final int minorSubVerionID = 9;
//
// public static boolean areLabels = false;
// public static boolean isCameraCenteredOnMario = false;
// public static Integer FPS = 24;
// public static int MaxFPS = 100;
// public static boolean areFrozenCreatures = false;
//
// public static boolean isVisualization = true;
// public static boolean isGameplayStopped = false;
// public static boolean isFly = false;
//
// private static GameViewer GameViewer = null;
// // public static boolean isTimer = true;
//
// public static int mariosecondMultiplier = 15;
//
// public static boolean isPowerRestoration;
//
// // required for rendering grid in ch/idsia/benchmark/mario/engine/sprites/Sprite.java
// public static int receptiveFieldWidth = 19;
// public static int receptiveFieldHeight = 19;
// public static int marioEgoCol = 9;
// public static int marioEgoRow = 9;
//
// private static MarioVisualComponent marioVisualComponent;
// public static int VISUAL_COMPONENT_WIDTH = 320;
// public static int VISUAL_COMPONENT_HEIGHT = 240;
//
// public static boolean isShowReceptiveField = false;
// public static boolean isScale2x = false;
// public static boolean isRecording = false;
// public static boolean isReplaying = false;
//
// public static int getPrimaryVersionUID()
// {
// return primaryVerionUID;
// }
//
// public static int getMinorVersionUID()
// {
// return minorVerionUID;
// }
//
// public static int getMinorSubVersionID()
// {
// return minorSubVerionID;
// }
//
// public static String getBenchmarkName()
// {
// return "[~ Mario AI Benchmark ~" + GlobalOptions.getVersionUID() + "]";
// }
//
// public static String getVersionUID()
// {
// return " " + getPrimaryVersionUID() + "." + getMinorVersionUID() + "." + getMinorSubVersionID();
// }
//
// public static void registerMarioVisualComponent(MarioVisualComponent mc)
// {
// marioVisualComponent = mc;
// }
//
// public static void registerGameViewer(GameViewer gv)
// {
// GameViewer = gv;
// }
//
// public static void AdjustMarioVisualComponentFPS()
// {
// if (marioVisualComponent != null)
// marioVisualComponent.adjustFPS();
// }
//
// public static void gameViewerTick()
// {
// if (GameViewer != null)
// GameViewer.tick();
// }
//
// public static String getDateTime(Long d)
// {
// final DateFormat dateFormat = (d == null) ? new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:ms") :
// new SimpleDateFormat("HH:mm:ss:ms");
// if (d != null)
// dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
// final Date date = (d == null) ? new Date() : new Date(d);
// return dateFormat.format(date);
// }
//
// final static private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
//
// public static String getTimeStamp()
// {
// return dateFormat.format(new Date());
// }
//
// public static void changeScale2x()
// {
// if (marioVisualComponent == null)
// return;
//
// isScale2x = !isScale2x;
// marioVisualComponent.width *= isScale2x ? 2 : 0.5;
// marioVisualComponent.height *= isScale2x ? 2 : 0.5;
// marioVisualComponent.changeScale2x();
// }
// }
// Path: src/main/java/ch/idsia/agents/controllers/human/CheaterKeyboardAgent.java
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import ch.idsia.agents.Agent;
import ch.idsia.benchmark.mario.engine.GlobalOptions;
import ch.idsia.benchmark.mario.environments.Environment;
{
// move your coffee away from the keyboard..
Action = new boolean[16];
}
public void setObservationDetails(final int rfWidth, final int rfHeight, final int egoRow, final int egoCol)
{}
public String getName() { return Name; }
public void setName(String name) { Name = name; }
public void keyPressed(KeyEvent e)
{
toggleKey(e.getKeyCode(), true);
}
public void keyReleased(KeyEvent e)
{
toggleKey(e.getKeyCode(), false);
}
private void toggleKey(int keyCode, boolean isPressed)
{
switch (keyCode)
{
//Cheats;
case KeyEvent.VK_D:
if (isPressed)
|
GlobalOptions.gameViewerTick();
|
qyxxjd/AndroidBasicProject
|
app/src/main/java/com/classic/simple/fragment/ImageFragment.java
|
// Path: classic/src/main/java/com/classic/core/fragment/BaseFragment.java
// public abstract class BaseFragment extends Fragment
// implements IFragment, IRegister, View.OnClickListener, EasyPermissions.PermissionCallbacks {
// private static final String SP_NAME = "firstConfig";
// private static final String STATE_IS_HIDDEN = "isHidden";
//
// protected Activity mActivity;
//
// @Override public void onAttach(Context context) {
// super.onAttach(context);
// mActivity = getActivity();
// }
//
// @Override public void onSaveInstanceState(Bundle outState) {
// super.onSaveInstanceState(outState);
// outState.putBoolean(STATE_IS_HIDDEN, isHidden());
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View parentView = inflater.inflate(getLayoutResId(), container, false);
// SharedPreferencesUtil spUtil = new SharedPreferencesUtil(mActivity, SP_NAME);
// final String simpleName = this.getClass().getSimpleName();
// if (spUtil.getBooleanValue(simpleName, true)) {
// onFirst();
// spUtil.putBooleanValue(simpleName, false);
// }
// initData();
// initView(parentView, savedInstanceState);
// return parentView;
// }
//
//
// @Override public void onViewCreated(View view, Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
// if(savedInstanceState != null){
// boolean isHidden = savedInstanceState.getBoolean(STATE_IS_HIDDEN);
// FragmentTransaction transaction = getFragmentManager().beginTransaction();
// if(isHidden){
// transaction.hide(this);
// onFragmentHide();
// } else {
// transaction.show(this);
// onFragmentShow();
// }
// transaction.commit();
// }
// register();
// }
//
//
// @Override public void onDestroyView() {
// unRegister();
// super.onDestroyView();
// }
//
// @Override public void onRequestPermissionsResult(
// int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
// }
//
// @Override public void onFirst() { }
// @Override public void initData() { }
// @Override public void initView(View parentView, Bundle savedInstanceState) { }
// @Override public void register() { }
// @Override public void unRegister() { }
// @Override public void onFragmentShow() { }
// @Override public void onFragmentHide() { }
// @Override public void showProgress() { }
// @Override public void hideProgress() { }
// @Override public void viewClick(View v) { }
// @Override public void onPermissionsGranted(int requestCode, List<String> perms) { }
// @Override public void onPermissionsDenied(int requestCode, List<String> perms) { }
//
// @Override public void onClick(View v) {
// viewClick(v);
// }
// }
//
// Path: classic/src/main/java/com/classic/core/utils/ToastUtil.java
// public final class ToastUtil {
// private ToastUtil() {}
//
//
// public static void showToast(Context context, String text) {
// Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
// }
//
//
// public static void showToast(Context context, int resId) {
// Toast.makeText(context, context.getResources().getText(resId),
// Toast.LENGTH_SHORT).show();
// }
//
//
// public static void showLongToast(Context context, String text) {
// Toast.makeText(context, text, Toast.LENGTH_LONG).show();
// }
//
//
// public static void showLongToast(Context context, int resId) {
// Toast.makeText(context, context.getResources().getText(resId),
// Toast.LENGTH_LONG).show();
// }
// }
|
import com.classic.core.fragment.BaseFragment;
import com.classic.core.utils.ToastUtil;
import com.classic.simple.R;
|
package com.classic.simple.fragment;
public class ImageFragment extends BaseFragment {
@Override public int getLayoutResId() {
return R.layout.fragment_image;
}
@Override public void onFragmentShow() {
super.onFragmentShow();
|
// Path: classic/src/main/java/com/classic/core/fragment/BaseFragment.java
// public abstract class BaseFragment extends Fragment
// implements IFragment, IRegister, View.OnClickListener, EasyPermissions.PermissionCallbacks {
// private static final String SP_NAME = "firstConfig";
// private static final String STATE_IS_HIDDEN = "isHidden";
//
// protected Activity mActivity;
//
// @Override public void onAttach(Context context) {
// super.onAttach(context);
// mActivity = getActivity();
// }
//
// @Override public void onSaveInstanceState(Bundle outState) {
// super.onSaveInstanceState(outState);
// outState.putBoolean(STATE_IS_HIDDEN, isHidden());
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View parentView = inflater.inflate(getLayoutResId(), container, false);
// SharedPreferencesUtil spUtil = new SharedPreferencesUtil(mActivity, SP_NAME);
// final String simpleName = this.getClass().getSimpleName();
// if (spUtil.getBooleanValue(simpleName, true)) {
// onFirst();
// spUtil.putBooleanValue(simpleName, false);
// }
// initData();
// initView(parentView, savedInstanceState);
// return parentView;
// }
//
//
// @Override public void onViewCreated(View view, Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
// if(savedInstanceState != null){
// boolean isHidden = savedInstanceState.getBoolean(STATE_IS_HIDDEN);
// FragmentTransaction transaction = getFragmentManager().beginTransaction();
// if(isHidden){
// transaction.hide(this);
// onFragmentHide();
// } else {
// transaction.show(this);
// onFragmentShow();
// }
// transaction.commit();
// }
// register();
// }
//
//
// @Override public void onDestroyView() {
// unRegister();
// super.onDestroyView();
// }
//
// @Override public void onRequestPermissionsResult(
// int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
// }
//
// @Override public void onFirst() { }
// @Override public void initData() { }
// @Override public void initView(View parentView, Bundle savedInstanceState) { }
// @Override public void register() { }
// @Override public void unRegister() { }
// @Override public void onFragmentShow() { }
// @Override public void onFragmentHide() { }
// @Override public void showProgress() { }
// @Override public void hideProgress() { }
// @Override public void viewClick(View v) { }
// @Override public void onPermissionsGranted(int requestCode, List<String> perms) { }
// @Override public void onPermissionsDenied(int requestCode, List<String> perms) { }
//
// @Override public void onClick(View v) {
// viewClick(v);
// }
// }
//
// Path: classic/src/main/java/com/classic/core/utils/ToastUtil.java
// public final class ToastUtil {
// private ToastUtil() {}
//
//
// public static void showToast(Context context, String text) {
// Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
// }
//
//
// public static void showToast(Context context, int resId) {
// Toast.makeText(context, context.getResources().getText(resId),
// Toast.LENGTH_SHORT).show();
// }
//
//
// public static void showLongToast(Context context, String text) {
// Toast.makeText(context, text, Toast.LENGTH_LONG).show();
// }
//
//
// public static void showLongToast(Context context, int resId) {
// Toast.makeText(context, context.getResources().getText(resId),
// Toast.LENGTH_LONG).show();
// }
// }
// Path: app/src/main/java/com/classic/simple/fragment/ImageFragment.java
import com.classic.core.fragment.BaseFragment;
import com.classic.core.utils.ToastUtil;
import com.classic.simple.R;
package com.classic.simple.fragment;
public class ImageFragment extends BaseFragment {
@Override public int getLayoutResId() {
return R.layout.fragment_image;
}
@Override public void onFragmentShow() {
super.onFragmentShow();
|
ToastUtil.showToast(getActivity(), "ImageFragment --> onFragmentShow()");
|
qyxxjd/AndroidBasicProject
|
app/src/main/java/com/classic/simple/utils/NewsDataSource.java
|
// Path: app/src/main/java/com/classic/simple/model/News.java
// public class News {
//
// /** 单图布局样式 */
// public static final int TYPE_SINGLE_PICTURE = 0;
// /** 多图布局样式 */
// public static final int TYPE_MULTIPLE_PICTURE = 1;
// /** 无图布局样式 */
// public static final int TYPE_NONE_PICTURE = 2;
//
// private String title;
// private String intro;
// private String coverUrl;
// private String author;
// private long releaseTime;
// private int newsType;
//
// public News(){}
//
// public News(int newsType, String author, String title, String intro) {
// this(newsType,author,title,intro,"");
// }
//
// public News(int newsType, String author, String title, String intro, String coverUrl) {
// this.newsType = newsType;
// this.author = author;
// this.title = title;
// this.intro = intro;
// this.coverUrl = coverUrl;
// this.releaseTime = System.currentTimeMillis();
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getIntro() {
// return intro;
// }
//
// public void setIntro(String intro) {
// this.intro = intro;
// }
//
// public String getCoverUrl() {
// return coverUrl;
// }
//
// public void setCoverUrl(String coverUrl) {
// this.coverUrl = coverUrl;
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public long getReleaseTime() {
// return releaseTime;
// }
//
// public void setReleaseTime(long releaseTime) {
// this.releaseTime = releaseTime;
// }
//
// public int getNewsType() {
// return newsType;
// }
//
// public void setNewsType(int newsType) {
// this.newsType = newsType;
// }
// }
|
import com.classic.simple.model.News;
import java.util.ArrayList;
|
package com.classic.simple.utils;
public final class NewsDataSource {
private static final String AUTHOR = "续写经典";
|
// Path: app/src/main/java/com/classic/simple/model/News.java
// public class News {
//
// /** 单图布局样式 */
// public static final int TYPE_SINGLE_PICTURE = 0;
// /** 多图布局样式 */
// public static final int TYPE_MULTIPLE_PICTURE = 1;
// /** 无图布局样式 */
// public static final int TYPE_NONE_PICTURE = 2;
//
// private String title;
// private String intro;
// private String coverUrl;
// private String author;
// private long releaseTime;
// private int newsType;
//
// public News(){}
//
// public News(int newsType, String author, String title, String intro) {
// this(newsType,author,title,intro,"");
// }
//
// public News(int newsType, String author, String title, String intro, String coverUrl) {
// this.newsType = newsType;
// this.author = author;
// this.title = title;
// this.intro = intro;
// this.coverUrl = coverUrl;
// this.releaseTime = System.currentTimeMillis();
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getIntro() {
// return intro;
// }
//
// public void setIntro(String intro) {
// this.intro = intro;
// }
//
// public String getCoverUrl() {
// return coverUrl;
// }
//
// public void setCoverUrl(String coverUrl) {
// this.coverUrl = coverUrl;
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public long getReleaseTime() {
// return releaseTime;
// }
//
// public void setReleaseTime(long releaseTime) {
// this.releaseTime = releaseTime;
// }
//
// public int getNewsType() {
// return newsType;
// }
//
// public void setNewsType(int newsType) {
// this.newsType = newsType;
// }
// }
// Path: app/src/main/java/com/classic/simple/utils/NewsDataSource.java
import com.classic.simple.model.News;
import java.util.ArrayList;
package com.classic.simple.utils;
public final class NewsDataSource {
private static final String AUTHOR = "续写经典";
|
private static ArrayList<News> newsList;
|
qyxxjd/AndroidBasicProject
|
classic/src/main/java/com/classic/core/utils/PackageUtil.java
|
// Path: classic/src/main/java/com/classic/core/utils/ShellUtil.java
// public static class CommandResult {
//
// /** result of command **/
// public int result;
// /** success message of command result **/
// public String successMsg;
// /** error message of command result **/
// public String errorMsg;
//
// public CommandResult(int result) {
// this.result = result;
// }
//
// public CommandResult(int result, String successMsg, String errorMsg) {
// this.result = result;
// this.successMsg = successMsg;
// this.errorMsg = errorMsg;
// }
// }
|
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import com.classic.core.utils.ShellUtil.CommandResult;
import java.io.File;
import java.util.List;
|
* 后台安装apk(需要root权限)
* Attentions:
* <ul>
* <li>Don't call this on the ui thread, it may costs some times.</li>
* <li>You should add android.permission.INSTALL_PACKAGES in manifest, so no need to request root
* permission, if you are system app.</li>
* </ul>
*
* @param context
* @param filePath file path of package
* @param pmParams pm install params
* @return {@link PackageUtil#INSTALL_SUCCEEDED} means install success, other means failed. details see
* {@link PackageUtil}.INSTALL_FAILED_*. same to {@link PackageManager}.INSTALL_*
*/
public static int installSilent(Context context, String filePath, String pmParams) {
if (filePath == null || filePath.length() == 0) {
return INSTALL_FAILED_INVALID_URI;
}
File file = new File(filePath);
if (file == null || file.length() <= 0 || !file.exists() || !file.isFile()) {
return INSTALL_FAILED_INVALID_URI;
}
/**
* if context is system app, don't need root permission, but should add <uses-permission
* android:name="android.permission.INSTALL_PACKAGES" /> in mainfest
**/
StringBuilder command = new StringBuilder().append("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install ")
.append(pmParams == null ? "" : pmParams).append(" ").append(filePath.replace(" ", "\\ "));
|
// Path: classic/src/main/java/com/classic/core/utils/ShellUtil.java
// public static class CommandResult {
//
// /** result of command **/
// public int result;
// /** success message of command result **/
// public String successMsg;
// /** error message of command result **/
// public String errorMsg;
//
// public CommandResult(int result) {
// this.result = result;
// }
//
// public CommandResult(int result, String successMsg, String errorMsg) {
// this.result = result;
// this.successMsg = successMsg;
// this.errorMsg = errorMsg;
// }
// }
// Path: classic/src/main/java/com/classic/core/utils/PackageUtil.java
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import com.classic.core.utils.ShellUtil.CommandResult;
import java.io.File;
import java.util.List;
* 后台安装apk(需要root权限)
* Attentions:
* <ul>
* <li>Don't call this on the ui thread, it may costs some times.</li>
* <li>You should add android.permission.INSTALL_PACKAGES in manifest, so no need to request root
* permission, if you are system app.</li>
* </ul>
*
* @param context
* @param filePath file path of package
* @param pmParams pm install params
* @return {@link PackageUtil#INSTALL_SUCCEEDED} means install success, other means failed. details see
* {@link PackageUtil}.INSTALL_FAILED_*. same to {@link PackageManager}.INSTALL_*
*/
public static int installSilent(Context context, String filePath, String pmParams) {
if (filePath == null || filePath.length() == 0) {
return INSTALL_FAILED_INVALID_URI;
}
File file = new File(filePath);
if (file == null || file.length() <= 0 || !file.exists() || !file.isFile()) {
return INSTALL_FAILED_INVALID_URI;
}
/**
* if context is system app, don't need root permission, but should add <uses-permission
* android:name="android.permission.INSTALL_PACKAGES" /> in mainfest
**/
StringBuilder command = new StringBuilder().append("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install ")
.append(pmParams == null ? "" : pmParams).append(" ").append(filePath.replace(" ", "\\ "));
|
CommandResult commandResult = ShellUtil.execCommand(command.toString(),
|
qyxxjd/AndroidBasicProject
|
app/src/main/java/com/classic/simple/fragment/TextFragment.java
|
// Path: classic/src/main/java/com/classic/core/fragment/BaseFragment.java
// public abstract class BaseFragment extends Fragment
// implements IFragment, IRegister, View.OnClickListener, EasyPermissions.PermissionCallbacks {
// private static final String SP_NAME = "firstConfig";
// private static final String STATE_IS_HIDDEN = "isHidden";
//
// protected Activity mActivity;
//
// @Override public void onAttach(Context context) {
// super.onAttach(context);
// mActivity = getActivity();
// }
//
// @Override public void onSaveInstanceState(Bundle outState) {
// super.onSaveInstanceState(outState);
// outState.putBoolean(STATE_IS_HIDDEN, isHidden());
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View parentView = inflater.inflate(getLayoutResId(), container, false);
// SharedPreferencesUtil spUtil = new SharedPreferencesUtil(mActivity, SP_NAME);
// final String simpleName = this.getClass().getSimpleName();
// if (spUtil.getBooleanValue(simpleName, true)) {
// onFirst();
// spUtil.putBooleanValue(simpleName, false);
// }
// initData();
// initView(parentView, savedInstanceState);
// return parentView;
// }
//
//
// @Override public void onViewCreated(View view, Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
// if(savedInstanceState != null){
// boolean isHidden = savedInstanceState.getBoolean(STATE_IS_HIDDEN);
// FragmentTransaction transaction = getFragmentManager().beginTransaction();
// if(isHidden){
// transaction.hide(this);
// onFragmentHide();
// } else {
// transaction.show(this);
// onFragmentShow();
// }
// transaction.commit();
// }
// register();
// }
//
//
// @Override public void onDestroyView() {
// unRegister();
// super.onDestroyView();
// }
//
// @Override public void onRequestPermissionsResult(
// int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
// }
//
// @Override public void onFirst() { }
// @Override public void initData() { }
// @Override public void initView(View parentView, Bundle savedInstanceState) { }
// @Override public void register() { }
// @Override public void unRegister() { }
// @Override public void onFragmentShow() { }
// @Override public void onFragmentHide() { }
// @Override public void showProgress() { }
// @Override public void hideProgress() { }
// @Override public void viewClick(View v) { }
// @Override public void onPermissionsGranted(int requestCode, List<String> perms) { }
// @Override public void onPermissionsDenied(int requestCode, List<String> perms) { }
//
// @Override public void onClick(View v) {
// viewClick(v);
// }
// }
//
// Path: classic/src/main/java/com/classic/core/utils/ToastUtil.java
// public final class ToastUtil {
// private ToastUtil() {}
//
//
// public static void showToast(Context context, String text) {
// Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
// }
//
//
// public static void showToast(Context context, int resId) {
// Toast.makeText(context, context.getResources().getText(resId),
// Toast.LENGTH_SHORT).show();
// }
//
//
// public static void showLongToast(Context context, String text) {
// Toast.makeText(context, text, Toast.LENGTH_LONG).show();
// }
//
//
// public static void showLongToast(Context context, int resId) {
// Toast.makeText(context, context.getResources().getText(resId),
// Toast.LENGTH_LONG).show();
// }
// }
|
import com.classic.core.fragment.BaseFragment;
import com.classic.core.utils.ToastUtil;
import com.classic.simple.R;
|
package com.classic.simple.fragment;
public class TextFragment extends BaseFragment {
@Override public int getLayoutResId() {
return R.layout.fragment_text;
}
@Override public void onFragmentShow() {
super.onFragmentShow();
|
// Path: classic/src/main/java/com/classic/core/fragment/BaseFragment.java
// public abstract class BaseFragment extends Fragment
// implements IFragment, IRegister, View.OnClickListener, EasyPermissions.PermissionCallbacks {
// private static final String SP_NAME = "firstConfig";
// private static final String STATE_IS_HIDDEN = "isHidden";
//
// protected Activity mActivity;
//
// @Override public void onAttach(Context context) {
// super.onAttach(context);
// mActivity = getActivity();
// }
//
// @Override public void onSaveInstanceState(Bundle outState) {
// super.onSaveInstanceState(outState);
// outState.putBoolean(STATE_IS_HIDDEN, isHidden());
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View parentView = inflater.inflate(getLayoutResId(), container, false);
// SharedPreferencesUtil spUtil = new SharedPreferencesUtil(mActivity, SP_NAME);
// final String simpleName = this.getClass().getSimpleName();
// if (spUtil.getBooleanValue(simpleName, true)) {
// onFirst();
// spUtil.putBooleanValue(simpleName, false);
// }
// initData();
// initView(parentView, savedInstanceState);
// return parentView;
// }
//
//
// @Override public void onViewCreated(View view, Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
// if(savedInstanceState != null){
// boolean isHidden = savedInstanceState.getBoolean(STATE_IS_HIDDEN);
// FragmentTransaction transaction = getFragmentManager().beginTransaction();
// if(isHidden){
// transaction.hide(this);
// onFragmentHide();
// } else {
// transaction.show(this);
// onFragmentShow();
// }
// transaction.commit();
// }
// register();
// }
//
//
// @Override public void onDestroyView() {
// unRegister();
// super.onDestroyView();
// }
//
// @Override public void onRequestPermissionsResult(
// int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
// }
//
// @Override public void onFirst() { }
// @Override public void initData() { }
// @Override public void initView(View parentView, Bundle savedInstanceState) { }
// @Override public void register() { }
// @Override public void unRegister() { }
// @Override public void onFragmentShow() { }
// @Override public void onFragmentHide() { }
// @Override public void showProgress() { }
// @Override public void hideProgress() { }
// @Override public void viewClick(View v) { }
// @Override public void onPermissionsGranted(int requestCode, List<String> perms) { }
// @Override public void onPermissionsDenied(int requestCode, List<String> perms) { }
//
// @Override public void onClick(View v) {
// viewClick(v);
// }
// }
//
// Path: classic/src/main/java/com/classic/core/utils/ToastUtil.java
// public final class ToastUtil {
// private ToastUtil() {}
//
//
// public static void showToast(Context context, String text) {
// Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
// }
//
//
// public static void showToast(Context context, int resId) {
// Toast.makeText(context, context.getResources().getText(resId),
// Toast.LENGTH_SHORT).show();
// }
//
//
// public static void showLongToast(Context context, String text) {
// Toast.makeText(context, text, Toast.LENGTH_LONG).show();
// }
//
//
// public static void showLongToast(Context context, int resId) {
// Toast.makeText(context, context.getResources().getText(resId),
// Toast.LENGTH_LONG).show();
// }
// }
// Path: app/src/main/java/com/classic/simple/fragment/TextFragment.java
import com.classic.core.fragment.BaseFragment;
import com.classic.core.utils.ToastUtil;
import com.classic.simple.R;
package com.classic.simple.fragment;
public class TextFragment extends BaseFragment {
@Override public int getLayoutResId() {
return R.layout.fragment_text;
}
@Override public void onFragmentShow() {
super.onFragmentShow();
|
ToastUtil.showToast(getActivity(), "TextFragment --> onFragmentShow()");
|
qyxxjd/AndroidBasicProject
|
classic/src/main/java/com/classic/core/activity/BaseActivityStack.java
|
// Path: classic/src/main/java/com/classic/core/interfaces/IActivity.java
// public interface IActivity {
// int DESTROY = 0x00;
// int STOP = 0x01;
// int PAUSE = 0x02;
// int RESUME = 0x03;
//
// /**
// * 获取布局文件
// */
// int getLayoutResId();
//
// /** 第一次启动会执行此方法 */
// void onFirst();
//
// /**
// * 此方法会在setContentView之前调用
// */
// void initPre();
//
// /**
// * 初始化数据
// */
// void initData();
//
// /**
// * 初始化控件
// */
// void initView(Bundle savedInstanceState);
//
// /**
// * 点击事件回调方法
// */
// void viewClick(View v);
//
// /**
// * 显示进度条
// */
// void showProgress();
//
// /**
// * 隐藏进度条
// */
// void hideProgress();
//
// /**
// * 跳转指定activity,并关闭当前activity
// */
// void skipActivity(Activity aty, Class<?> cls);
//
// /**
// * 跳转指定activity,并关闭当前activity
// */
// void skipActivity(Activity aty, Intent it);
//
// /**
// * 跳转指定activity,并关闭当前activity
// */
// void skipActivity(Activity aty, Class<?> cls, Bundle extras);
//
// /**
// * 跳转activity
// */
// void startActivity(Activity aty, Class<?> cls);
//
// /**
// * 跳转activity
// */
// void startActivity(Activity aty, Intent it);
//
// /**
// * 跳转activity
// */
// void startActivity(Activity aty, Class<?> cls, Bundle extras);
// }
|
import android.app.Activity;
import android.content.Context;
import com.classic.core.interfaces.IActivity;
import java.util.Stack;
|
package com.classic.core.activity;
/**
* Activity栈管理
*
* @author 续写经典
* @version 1.0 2015/11/4
*/
public final class BaseActivityStack {
private BaseActivityStack() { }
|
// Path: classic/src/main/java/com/classic/core/interfaces/IActivity.java
// public interface IActivity {
// int DESTROY = 0x00;
// int STOP = 0x01;
// int PAUSE = 0x02;
// int RESUME = 0x03;
//
// /**
// * 获取布局文件
// */
// int getLayoutResId();
//
// /** 第一次启动会执行此方法 */
// void onFirst();
//
// /**
// * 此方法会在setContentView之前调用
// */
// void initPre();
//
// /**
// * 初始化数据
// */
// void initData();
//
// /**
// * 初始化控件
// */
// void initView(Bundle savedInstanceState);
//
// /**
// * 点击事件回调方法
// */
// void viewClick(View v);
//
// /**
// * 显示进度条
// */
// void showProgress();
//
// /**
// * 隐藏进度条
// */
// void hideProgress();
//
// /**
// * 跳转指定activity,并关闭当前activity
// */
// void skipActivity(Activity aty, Class<?> cls);
//
// /**
// * 跳转指定activity,并关闭当前activity
// */
// void skipActivity(Activity aty, Intent it);
//
// /**
// * 跳转指定activity,并关闭当前activity
// */
// void skipActivity(Activity aty, Class<?> cls, Bundle extras);
//
// /**
// * 跳转activity
// */
// void startActivity(Activity aty, Class<?> cls);
//
// /**
// * 跳转activity
// */
// void startActivity(Activity aty, Intent it);
//
// /**
// * 跳转activity
// */
// void startActivity(Activity aty, Class<?> cls, Bundle extras);
// }
// Path: classic/src/main/java/com/classic/core/activity/BaseActivityStack.java
import android.app.Activity;
import android.content.Context;
import com.classic.core.interfaces.IActivity;
import java.util.Stack;
package com.classic.core.activity;
/**
* Activity栈管理
*
* @author 续写经典
* @version 1.0 2015/11/4
*/
public final class BaseActivityStack {
private BaseActivityStack() { }
|
private static Stack<IActivity> sActivityStack;
|
qyxxjd/AndroidBasicProject
|
app/src/main/java/com/classic/simple/model/Demo.java
|
// Path: classic/src/main/java/com/classic/core/utils/DataUtil.java
// public final class DataUtil {
// private DataUtil() { }
//
// /** 检查数组是否为空(去掉前后空格) */
// public static boolean isEmpty(String string) {
// return (string == null || string.length() == 0 || string.trim().length() == 0);
// }
//
// /** 获取字符串长度(去掉前后空格) */
// public static int getSize(String string) {
// return string == null ? 0 : string.trim().length();
// }
//
// /** 检查数组是否为空 */
// public static <V> boolean isEmpty(V[] sourceArray) {
// return (sourceArray == null || sourceArray.length == 0);
// }
//
// /** 获取数组长度 */
// public static <V> int getSize(V[] sourceArray) {
// return sourceArray == null ? 0 : sourceArray.length;
// }
//
// /** 检查Collection是否为空 */
// public static <V> boolean isEmpty(Collection<V> c) {
// return (c == null || c.size() == 0);
// }
//
// /** 获取Collection长度 */
// public static <V> int getSize(Collection<V> c) {
// return c == null ? 0 : c.size();
// }
//
// /** 检查List是否为空 */
// public static <V> boolean isEmpty(List<V> sourceList) {
// return (sourceList == null || sourceList.size() == 0);
// }
//
// /** 获取List长度 */
// public static <V> int getSize(List<V> sourceList) {
// return sourceList == null ? 0 : sourceList.size();
// }
//
// /** 检查Map是否为空 */
// public static <K, V> boolean isEmpty(Map<K, V> sourceMap) {
// return (sourceMap == null || sourceMap.size() == 0);
// }
//
// /** 获取Map长度 */
// public static <K, V> int getSize(Map<K, V> sourceMap) {
// return sourceMap == null ? 0 : sourceMap.size();
// }
// }
|
import android.graphics.Color;
import com.classic.core.utils.DataUtil;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
|
package com.classic.simple.model;
/**
* @author 续写经典
* @date 2015/11/7
*/
public class Demo implements Serializable {
public static final int TYPE_SPLASH = 0x00;
public static final int TYPE_ADAPTER = 0x01;
public static final int TYPE_CRASH = 0x02;
public static final int TYPE_FRAGMENT = 0x03;
public static final int TYPE_PERMISSIONS = 0x04;
public String title;
public int bgColor;
public int type;
public Demo() {
}
public Demo(String title, int bgColor, int type) {
this.title = title;
this.bgColor = bgColor;
this.type = type;
}
private static List<Demo> demos;
public static List<Demo> getDemos() {
|
// Path: classic/src/main/java/com/classic/core/utils/DataUtil.java
// public final class DataUtil {
// private DataUtil() { }
//
// /** 检查数组是否为空(去掉前后空格) */
// public static boolean isEmpty(String string) {
// return (string == null || string.length() == 0 || string.trim().length() == 0);
// }
//
// /** 获取字符串长度(去掉前后空格) */
// public static int getSize(String string) {
// return string == null ? 0 : string.trim().length();
// }
//
// /** 检查数组是否为空 */
// public static <V> boolean isEmpty(V[] sourceArray) {
// return (sourceArray == null || sourceArray.length == 0);
// }
//
// /** 获取数组长度 */
// public static <V> int getSize(V[] sourceArray) {
// return sourceArray == null ? 0 : sourceArray.length;
// }
//
// /** 检查Collection是否为空 */
// public static <V> boolean isEmpty(Collection<V> c) {
// return (c == null || c.size() == 0);
// }
//
// /** 获取Collection长度 */
// public static <V> int getSize(Collection<V> c) {
// return c == null ? 0 : c.size();
// }
//
// /** 检查List是否为空 */
// public static <V> boolean isEmpty(List<V> sourceList) {
// return (sourceList == null || sourceList.size() == 0);
// }
//
// /** 获取List长度 */
// public static <V> int getSize(List<V> sourceList) {
// return sourceList == null ? 0 : sourceList.size();
// }
//
// /** 检查Map是否为空 */
// public static <K, V> boolean isEmpty(Map<K, V> sourceMap) {
// return (sourceMap == null || sourceMap.size() == 0);
// }
//
// /** 获取Map长度 */
// public static <K, V> int getSize(Map<K, V> sourceMap) {
// return sourceMap == null ? 0 : sourceMap.size();
// }
// }
// Path: app/src/main/java/com/classic/simple/model/Demo.java
import android.graphics.Color;
import com.classic.core.utils.DataUtil;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
package com.classic.simple.model;
/**
* @author 续写经典
* @date 2015/11/7
*/
public class Demo implements Serializable {
public static final int TYPE_SPLASH = 0x00;
public static final int TYPE_ADAPTER = 0x01;
public static final int TYPE_CRASH = 0x02;
public static final int TYPE_FRAGMENT = 0x03;
public static final int TYPE_PERMISSIONS = 0x04;
public String title;
public int bgColor;
public int type;
public Demo() {
}
public Demo(String title, int bgColor, int type) {
this.title = title;
this.bgColor = bgColor;
this.type = type;
}
private static List<Demo> demos;
public static List<Demo> getDemos() {
|
if (DataUtil.isEmpty(demos)) {
|
qyxxjd/AndroidBasicProject
|
app/src/main/java/com/classic/simple/activity/FragmentActivity.java
|
// Path: app/src/main/java/com/classic/simple/fragment/ImageFragment.java
// public class ImageFragment extends BaseFragment {
//
// @Override public int getLayoutResId() {
// return R.layout.fragment_image;
// }
//
// @Override public void onFragmentShow() {
// super.onFragmentShow();
// ToastUtil.showToast(getActivity(), "ImageFragment --> onFragmentShow()");
// }
//
// @Override public void onFragmentHide() {
// super.onFragmentHide();
// ToastUtil.showToast(getActivity(), "ImageFragment --> onFragmentHide()");
// }
// }
//
// Path: app/src/main/java/com/classic/simple/fragment/TextFragment.java
// public class TextFragment extends BaseFragment {
//
// @Override public int getLayoutResId() {
// return R.layout.fragment_text;
// }
//
// @Override public void onFragmentShow() {
// super.onFragmentShow();
// ToastUtil.showToast(getActivity(), "TextFragment --> onFragmentShow()");
// }
//
// @Override public void onFragmentHide() {
// super.onFragmentHide();
// ToastUtil.showToast(getActivity(), "TextFragment --> onFragmentHide()");
// }
// }
|
import android.os.Bundle;
import butterknife.OnClick;
import com.classic.simple.R;
import com.classic.simple.fragment.ImageFragment;
import com.classic.simple.fragment.TextFragment;
|
package com.classic.simple.activity;
public class FragmentActivity extends AppBaseActivity {
private ImageFragment mImageFragment;
|
// Path: app/src/main/java/com/classic/simple/fragment/ImageFragment.java
// public class ImageFragment extends BaseFragment {
//
// @Override public int getLayoutResId() {
// return R.layout.fragment_image;
// }
//
// @Override public void onFragmentShow() {
// super.onFragmentShow();
// ToastUtil.showToast(getActivity(), "ImageFragment --> onFragmentShow()");
// }
//
// @Override public void onFragmentHide() {
// super.onFragmentHide();
// ToastUtil.showToast(getActivity(), "ImageFragment --> onFragmentHide()");
// }
// }
//
// Path: app/src/main/java/com/classic/simple/fragment/TextFragment.java
// public class TextFragment extends BaseFragment {
//
// @Override public int getLayoutResId() {
// return R.layout.fragment_text;
// }
//
// @Override public void onFragmentShow() {
// super.onFragmentShow();
// ToastUtil.showToast(getActivity(), "TextFragment --> onFragmentShow()");
// }
//
// @Override public void onFragmentHide() {
// super.onFragmentHide();
// ToastUtil.showToast(getActivity(), "TextFragment --> onFragmentHide()");
// }
// }
// Path: app/src/main/java/com/classic/simple/activity/FragmentActivity.java
import android.os.Bundle;
import butterknife.OnClick;
import com.classic.simple.R;
import com.classic.simple.fragment.ImageFragment;
import com.classic.simple.fragment.TextFragment;
package com.classic.simple.activity;
public class FragmentActivity extends AppBaseActivity {
private ImageFragment mImageFragment;
|
private TextFragment mTextFragment;
|
qyxxjd/AndroidBasicProject
|
classic/src/main/java/com/classic/core/exception/CrashHandler.java
|
// Path: classic/src/main/java/com/classic/core/interfaces/ICrashProcess.java
// public interface ICrashProcess {
//
// void onException(Thread thread, Throwable exception) throws Exception;
// }
|
import com.classic.core.interfaces.ICrashProcess;
|
package com.classic.core.exception;
/**
* 异常信息收集
*
* @author 续写经典
* @version 1.0 2015/11/3
*/
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static CrashHandler sInstance;
|
// Path: classic/src/main/java/com/classic/core/interfaces/ICrashProcess.java
// public interface ICrashProcess {
//
// void onException(Thread thread, Throwable exception) throws Exception;
// }
// Path: classic/src/main/java/com/classic/core/exception/CrashHandler.java
import com.classic.core.interfaces.ICrashProcess;
package com.classic.core.exception;
/**
* 异常信息收集
*
* @author 续写经典
* @version 1.0 2015/11/3
*/
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static CrashHandler sInstance;
|
private ICrashProcess mCrashProcess;
|
yshahun/gc-log-parser
|
src/main/java/ys/gclog/parser/GCLogParser.java
|
// Path: src/main/java/ys/gclog/parser/extract/ExtractContext.java
// public class ExtractContext {
//
// private final List<LogExtractor> extractors = new ArrayList<>();
// private final List<LogExtractor> availableExtractors;
//
// public ExtractContext(List<LogExtractor> availableExtractors) {
// this.availableExtractors = availableExtractors;
// }
//
// public List<LogExtractor> getExtractors() {
// return extractors;
// }
//
// public List<LogExtractor> getAvailableExtractors() {
// return availableExtractors;
// }
// }
//
// Path: src/main/java/ys/gclog/parser/extract/Extractors.java
// public final class Extractors {
//
// private static final List<LogExtractor> PRIMARY_EXTRACTORS =
// Collections.unmodifiableList(Arrays.asList(
// new SimpleMinorCollectionExtractor(),
// new SimpleFullCollectionExtractor(),
// new DetailedMinorCollectionExtractor(),
// new DetailedFullCollectionExtractor(),
// new CmsCollectorExtractor(),
// new G1CollectorExtractor()));
//
// private static final List<LogExtractor> SECONDARY_EXTRACTORS =
// Collections.unmodifiableList(Arrays.asList(
// new SerialYoungCollectorExtractor(),
// new ParallelYoungCollectorExtractor(),
// new ParallelNewYoungCollectorExtractor(),
// new SerialOldCollectorExtractor(),
// new ParallelOldCollectorExtractor(),
// new PermGenCollectorExtractor(),
// new MetaspaceCollectorExtractor()));
//
// private Extractors() {}
//
// public static List<LogExtractor> primaryExtractors() {
// return PRIMARY_EXTRACTORS;
// }
//
// public static List<LogExtractor> secondaryExtractors() {
// return SECONDARY_EXTRACTORS;
// }
// }
//
// Path: src/main/java/ys/gclog/parser/extract/LogExtractor.java
// public interface LogExtractor {
//
// String REGEX_DECIMAL = "(\\d+\\.\\d+)";
// String REGEX_TIME = REGEX_DECIMAL;
// /**
// * Regular expression for the date field, e.g. {@code 2015-01-15T12:30:38.059+0300}.
// */
// String REGEX_DATE = "(\\d+-\\d+-\\d+T\\d+:\\d+:\\d+\\.\\d+\\+\\d+)";
// String REGEX_MEMORY_AT = "(\\d+)K\\((\\d+)K\\)";
// String REGEX_MEMORY_FROM_TO_KB = "(\\d+)K->(\\d+)K\\((\\d+)K\\)";
// String REGEX_MEMORY_FROM_TO_MB = "(\\d+)M->(\\d+)M\\((\\d+)M\\)";
// String REGEX_MEMORY_WITH_TOTAL_FROM_TO = String.format(
// "%s[BKM]\\(%s[BKM]\\)->%s[BKM]\\(%s[BKM]\\)",
// REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL);
// String REGEX_MEMORY_WITHOUT_TOTAL_FROM_TO =
// String.format("%s[BKM]->%s[BKM]", REGEX_DECIMAL, REGEX_DECIMAL);
// String REGEX_TIMES = String.format("\\[Times: user=%s sys=%s, real=%s secs]",
// REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL);
//
// boolean accept(String log);
//
// Optional<Map<String, String>> extract(String log, ExtractContext context);
//
// static void putIfNotNull(Map<String, String> map, String key, String value) {
// if (value != null) {
// map.put(key, value);
// }
// }
// }
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import ys.gclog.parser.extract.ExtractContext;
import ys.gclog.parser.extract.Extractors;
import ys.gclog.parser.extract.LogExtractor;
|
/*
* Copyright 2015 Yauheni Shahun
*
* 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 ys.gclog.parser;
public class GCLogParser {
private static final Logger logger = Logger.getLogger(GCLogParser.class.getName());
private static final Pattern PATTERN_IDENT = Pattern.compile("^\\s+");
public List<String> parse(InputStream input) throws IOException {
return parse(input, false);
}
public List<String> parse(InputStream input, boolean isVerbose) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
|
// Path: src/main/java/ys/gclog/parser/extract/ExtractContext.java
// public class ExtractContext {
//
// private final List<LogExtractor> extractors = new ArrayList<>();
// private final List<LogExtractor> availableExtractors;
//
// public ExtractContext(List<LogExtractor> availableExtractors) {
// this.availableExtractors = availableExtractors;
// }
//
// public List<LogExtractor> getExtractors() {
// return extractors;
// }
//
// public List<LogExtractor> getAvailableExtractors() {
// return availableExtractors;
// }
// }
//
// Path: src/main/java/ys/gclog/parser/extract/Extractors.java
// public final class Extractors {
//
// private static final List<LogExtractor> PRIMARY_EXTRACTORS =
// Collections.unmodifiableList(Arrays.asList(
// new SimpleMinorCollectionExtractor(),
// new SimpleFullCollectionExtractor(),
// new DetailedMinorCollectionExtractor(),
// new DetailedFullCollectionExtractor(),
// new CmsCollectorExtractor(),
// new G1CollectorExtractor()));
//
// private static final List<LogExtractor> SECONDARY_EXTRACTORS =
// Collections.unmodifiableList(Arrays.asList(
// new SerialYoungCollectorExtractor(),
// new ParallelYoungCollectorExtractor(),
// new ParallelNewYoungCollectorExtractor(),
// new SerialOldCollectorExtractor(),
// new ParallelOldCollectorExtractor(),
// new PermGenCollectorExtractor(),
// new MetaspaceCollectorExtractor()));
//
// private Extractors() {}
//
// public static List<LogExtractor> primaryExtractors() {
// return PRIMARY_EXTRACTORS;
// }
//
// public static List<LogExtractor> secondaryExtractors() {
// return SECONDARY_EXTRACTORS;
// }
// }
//
// Path: src/main/java/ys/gclog/parser/extract/LogExtractor.java
// public interface LogExtractor {
//
// String REGEX_DECIMAL = "(\\d+\\.\\d+)";
// String REGEX_TIME = REGEX_DECIMAL;
// /**
// * Regular expression for the date field, e.g. {@code 2015-01-15T12:30:38.059+0300}.
// */
// String REGEX_DATE = "(\\d+-\\d+-\\d+T\\d+:\\d+:\\d+\\.\\d+\\+\\d+)";
// String REGEX_MEMORY_AT = "(\\d+)K\\((\\d+)K\\)";
// String REGEX_MEMORY_FROM_TO_KB = "(\\d+)K->(\\d+)K\\((\\d+)K\\)";
// String REGEX_MEMORY_FROM_TO_MB = "(\\d+)M->(\\d+)M\\((\\d+)M\\)";
// String REGEX_MEMORY_WITH_TOTAL_FROM_TO = String.format(
// "%s[BKM]\\(%s[BKM]\\)->%s[BKM]\\(%s[BKM]\\)",
// REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL);
// String REGEX_MEMORY_WITHOUT_TOTAL_FROM_TO =
// String.format("%s[BKM]->%s[BKM]", REGEX_DECIMAL, REGEX_DECIMAL);
// String REGEX_TIMES = String.format("\\[Times: user=%s sys=%s, real=%s secs]",
// REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL);
//
// boolean accept(String log);
//
// Optional<Map<String, String>> extract(String log, ExtractContext context);
//
// static void putIfNotNull(Map<String, String> map, String key, String value) {
// if (value != null) {
// map.put(key, value);
// }
// }
// }
// Path: src/main/java/ys/gclog/parser/GCLogParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import ys.gclog.parser.extract.ExtractContext;
import ys.gclog.parser.extract.Extractors;
import ys.gclog.parser.extract.LogExtractor;
/*
* Copyright 2015 Yauheni Shahun
*
* 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 ys.gclog.parser;
public class GCLogParser {
private static final Logger logger = Logger.getLogger(GCLogParser.class.getName());
private static final Pattern PATTERN_IDENT = Pattern.compile("^\\s+");
public List<String> parse(InputStream input) throws IOException {
return parse(input, false);
}
public List<String> parse(InputStream input, boolean isVerbose) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
|
List<LogExtractor> extractors = new ArrayList<LogExtractor>();
|
yshahun/gc-log-parser
|
src/main/java/ys/gclog/parser/GCLogParser.java
|
// Path: src/main/java/ys/gclog/parser/extract/ExtractContext.java
// public class ExtractContext {
//
// private final List<LogExtractor> extractors = new ArrayList<>();
// private final List<LogExtractor> availableExtractors;
//
// public ExtractContext(List<LogExtractor> availableExtractors) {
// this.availableExtractors = availableExtractors;
// }
//
// public List<LogExtractor> getExtractors() {
// return extractors;
// }
//
// public List<LogExtractor> getAvailableExtractors() {
// return availableExtractors;
// }
// }
//
// Path: src/main/java/ys/gclog/parser/extract/Extractors.java
// public final class Extractors {
//
// private static final List<LogExtractor> PRIMARY_EXTRACTORS =
// Collections.unmodifiableList(Arrays.asList(
// new SimpleMinorCollectionExtractor(),
// new SimpleFullCollectionExtractor(),
// new DetailedMinorCollectionExtractor(),
// new DetailedFullCollectionExtractor(),
// new CmsCollectorExtractor(),
// new G1CollectorExtractor()));
//
// private static final List<LogExtractor> SECONDARY_EXTRACTORS =
// Collections.unmodifiableList(Arrays.asList(
// new SerialYoungCollectorExtractor(),
// new ParallelYoungCollectorExtractor(),
// new ParallelNewYoungCollectorExtractor(),
// new SerialOldCollectorExtractor(),
// new ParallelOldCollectorExtractor(),
// new PermGenCollectorExtractor(),
// new MetaspaceCollectorExtractor()));
//
// private Extractors() {}
//
// public static List<LogExtractor> primaryExtractors() {
// return PRIMARY_EXTRACTORS;
// }
//
// public static List<LogExtractor> secondaryExtractors() {
// return SECONDARY_EXTRACTORS;
// }
// }
//
// Path: src/main/java/ys/gclog/parser/extract/LogExtractor.java
// public interface LogExtractor {
//
// String REGEX_DECIMAL = "(\\d+\\.\\d+)";
// String REGEX_TIME = REGEX_DECIMAL;
// /**
// * Regular expression for the date field, e.g. {@code 2015-01-15T12:30:38.059+0300}.
// */
// String REGEX_DATE = "(\\d+-\\d+-\\d+T\\d+:\\d+:\\d+\\.\\d+\\+\\d+)";
// String REGEX_MEMORY_AT = "(\\d+)K\\((\\d+)K\\)";
// String REGEX_MEMORY_FROM_TO_KB = "(\\d+)K->(\\d+)K\\((\\d+)K\\)";
// String REGEX_MEMORY_FROM_TO_MB = "(\\d+)M->(\\d+)M\\((\\d+)M\\)";
// String REGEX_MEMORY_WITH_TOTAL_FROM_TO = String.format(
// "%s[BKM]\\(%s[BKM]\\)->%s[BKM]\\(%s[BKM]\\)",
// REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL);
// String REGEX_MEMORY_WITHOUT_TOTAL_FROM_TO =
// String.format("%s[BKM]->%s[BKM]", REGEX_DECIMAL, REGEX_DECIMAL);
// String REGEX_TIMES = String.format("\\[Times: user=%s sys=%s, real=%s secs]",
// REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL);
//
// boolean accept(String log);
//
// Optional<Map<String, String>> extract(String log, ExtractContext context);
//
// static void putIfNotNull(Map<String, String> map, String key, String value) {
// if (value != null) {
// map.put(key, value);
// }
// }
// }
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import ys.gclog.parser.extract.ExtractContext;
import ys.gclog.parser.extract.Extractors;
import ys.gclog.parser.extract.LogExtractor;
|
/*
* Copyright 2015 Yauheni Shahun
*
* 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 ys.gclog.parser;
public class GCLogParser {
private static final Logger logger = Logger.getLogger(GCLogParser.class.getName());
private static final Pattern PATTERN_IDENT = Pattern.compile("^\\s+");
public List<String> parse(InputStream input) throws IOException {
return parse(input, false);
}
public List<String> parse(InputStream input, boolean isVerbose) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
List<LogExtractor> extractors = new ArrayList<LogExtractor>();
|
// Path: src/main/java/ys/gclog/parser/extract/ExtractContext.java
// public class ExtractContext {
//
// private final List<LogExtractor> extractors = new ArrayList<>();
// private final List<LogExtractor> availableExtractors;
//
// public ExtractContext(List<LogExtractor> availableExtractors) {
// this.availableExtractors = availableExtractors;
// }
//
// public List<LogExtractor> getExtractors() {
// return extractors;
// }
//
// public List<LogExtractor> getAvailableExtractors() {
// return availableExtractors;
// }
// }
//
// Path: src/main/java/ys/gclog/parser/extract/Extractors.java
// public final class Extractors {
//
// private static final List<LogExtractor> PRIMARY_EXTRACTORS =
// Collections.unmodifiableList(Arrays.asList(
// new SimpleMinorCollectionExtractor(),
// new SimpleFullCollectionExtractor(),
// new DetailedMinorCollectionExtractor(),
// new DetailedFullCollectionExtractor(),
// new CmsCollectorExtractor(),
// new G1CollectorExtractor()));
//
// private static final List<LogExtractor> SECONDARY_EXTRACTORS =
// Collections.unmodifiableList(Arrays.asList(
// new SerialYoungCollectorExtractor(),
// new ParallelYoungCollectorExtractor(),
// new ParallelNewYoungCollectorExtractor(),
// new SerialOldCollectorExtractor(),
// new ParallelOldCollectorExtractor(),
// new PermGenCollectorExtractor(),
// new MetaspaceCollectorExtractor()));
//
// private Extractors() {}
//
// public static List<LogExtractor> primaryExtractors() {
// return PRIMARY_EXTRACTORS;
// }
//
// public static List<LogExtractor> secondaryExtractors() {
// return SECONDARY_EXTRACTORS;
// }
// }
//
// Path: src/main/java/ys/gclog/parser/extract/LogExtractor.java
// public interface LogExtractor {
//
// String REGEX_DECIMAL = "(\\d+\\.\\d+)";
// String REGEX_TIME = REGEX_DECIMAL;
// /**
// * Regular expression for the date field, e.g. {@code 2015-01-15T12:30:38.059+0300}.
// */
// String REGEX_DATE = "(\\d+-\\d+-\\d+T\\d+:\\d+:\\d+\\.\\d+\\+\\d+)";
// String REGEX_MEMORY_AT = "(\\d+)K\\((\\d+)K\\)";
// String REGEX_MEMORY_FROM_TO_KB = "(\\d+)K->(\\d+)K\\((\\d+)K\\)";
// String REGEX_MEMORY_FROM_TO_MB = "(\\d+)M->(\\d+)M\\((\\d+)M\\)";
// String REGEX_MEMORY_WITH_TOTAL_FROM_TO = String.format(
// "%s[BKM]\\(%s[BKM]\\)->%s[BKM]\\(%s[BKM]\\)",
// REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL);
// String REGEX_MEMORY_WITHOUT_TOTAL_FROM_TO =
// String.format("%s[BKM]->%s[BKM]", REGEX_DECIMAL, REGEX_DECIMAL);
// String REGEX_TIMES = String.format("\\[Times: user=%s sys=%s, real=%s secs]",
// REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL);
//
// boolean accept(String log);
//
// Optional<Map<String, String>> extract(String log, ExtractContext context);
//
// static void putIfNotNull(Map<String, String> map, String key, String value) {
// if (value != null) {
// map.put(key, value);
// }
// }
// }
// Path: src/main/java/ys/gclog/parser/GCLogParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import ys.gclog.parser.extract.ExtractContext;
import ys.gclog.parser.extract.Extractors;
import ys.gclog.parser.extract.LogExtractor;
/*
* Copyright 2015 Yauheni Shahun
*
* 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 ys.gclog.parser;
public class GCLogParser {
private static final Logger logger = Logger.getLogger(GCLogParser.class.getName());
private static final Pattern PATTERN_IDENT = Pattern.compile("^\\s+");
public List<String> parse(InputStream input) throws IOException {
return parse(input, false);
}
public List<String> parse(InputStream input, boolean isVerbose) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
List<LogExtractor> extractors = new ArrayList<LogExtractor>();
|
Map<LogExtractor, ExtractContext> contexts = new HashMap<>();
|
yshahun/gc-log-parser
|
src/main/java/ys/gclog/parser/GCLogParser.java
|
// Path: src/main/java/ys/gclog/parser/extract/ExtractContext.java
// public class ExtractContext {
//
// private final List<LogExtractor> extractors = new ArrayList<>();
// private final List<LogExtractor> availableExtractors;
//
// public ExtractContext(List<LogExtractor> availableExtractors) {
// this.availableExtractors = availableExtractors;
// }
//
// public List<LogExtractor> getExtractors() {
// return extractors;
// }
//
// public List<LogExtractor> getAvailableExtractors() {
// return availableExtractors;
// }
// }
//
// Path: src/main/java/ys/gclog/parser/extract/Extractors.java
// public final class Extractors {
//
// private static final List<LogExtractor> PRIMARY_EXTRACTORS =
// Collections.unmodifiableList(Arrays.asList(
// new SimpleMinorCollectionExtractor(),
// new SimpleFullCollectionExtractor(),
// new DetailedMinorCollectionExtractor(),
// new DetailedFullCollectionExtractor(),
// new CmsCollectorExtractor(),
// new G1CollectorExtractor()));
//
// private static final List<LogExtractor> SECONDARY_EXTRACTORS =
// Collections.unmodifiableList(Arrays.asList(
// new SerialYoungCollectorExtractor(),
// new ParallelYoungCollectorExtractor(),
// new ParallelNewYoungCollectorExtractor(),
// new SerialOldCollectorExtractor(),
// new ParallelOldCollectorExtractor(),
// new PermGenCollectorExtractor(),
// new MetaspaceCollectorExtractor()));
//
// private Extractors() {}
//
// public static List<LogExtractor> primaryExtractors() {
// return PRIMARY_EXTRACTORS;
// }
//
// public static List<LogExtractor> secondaryExtractors() {
// return SECONDARY_EXTRACTORS;
// }
// }
//
// Path: src/main/java/ys/gclog/parser/extract/LogExtractor.java
// public interface LogExtractor {
//
// String REGEX_DECIMAL = "(\\d+\\.\\d+)";
// String REGEX_TIME = REGEX_DECIMAL;
// /**
// * Regular expression for the date field, e.g. {@code 2015-01-15T12:30:38.059+0300}.
// */
// String REGEX_DATE = "(\\d+-\\d+-\\d+T\\d+:\\d+:\\d+\\.\\d+\\+\\d+)";
// String REGEX_MEMORY_AT = "(\\d+)K\\((\\d+)K\\)";
// String REGEX_MEMORY_FROM_TO_KB = "(\\d+)K->(\\d+)K\\((\\d+)K\\)";
// String REGEX_MEMORY_FROM_TO_MB = "(\\d+)M->(\\d+)M\\((\\d+)M\\)";
// String REGEX_MEMORY_WITH_TOTAL_FROM_TO = String.format(
// "%s[BKM]\\(%s[BKM]\\)->%s[BKM]\\(%s[BKM]\\)",
// REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL);
// String REGEX_MEMORY_WITHOUT_TOTAL_FROM_TO =
// String.format("%s[BKM]->%s[BKM]", REGEX_DECIMAL, REGEX_DECIMAL);
// String REGEX_TIMES = String.format("\\[Times: user=%s sys=%s, real=%s secs]",
// REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL);
//
// boolean accept(String log);
//
// Optional<Map<String, String>> extract(String log, ExtractContext context);
//
// static void putIfNotNull(Map<String, String> map, String key, String value) {
// if (value != null) {
// map.put(key, value);
// }
// }
// }
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import ys.gclog.parser.extract.ExtractContext;
import ys.gclog.parser.extract.Extractors;
import ys.gclog.parser.extract.LogExtractor;
|
String startLine = reader.readLine();
if (startLine == null) {
return null;
}
buffer.add(startLine);
}
String nextLine = reader.readLine();
while (nextLine != null && PATTERN_IDENT.matcher(nextLine).find()) {
buffer.add(nextLine);
nextLine = reader.readLine();
}
String result = buffer.stream().collect(Collectors.joining("\n"));
buffer.clear();
if (nextLine != null) {
buffer.add(nextLine);
}
return result;
}
private static Optional<Map<String, String>> extract(
String line, List<LogExtractor> extractors, Map<LogExtractor, ExtractContext> contexts) {
for (LogExtractor extractor : extractors) {
Optional<Map<String, String>> option = extractor.extract(line, contexts.get(extractor));
if (option.isPresent()) {
return option;
}
}
|
// Path: src/main/java/ys/gclog/parser/extract/ExtractContext.java
// public class ExtractContext {
//
// private final List<LogExtractor> extractors = new ArrayList<>();
// private final List<LogExtractor> availableExtractors;
//
// public ExtractContext(List<LogExtractor> availableExtractors) {
// this.availableExtractors = availableExtractors;
// }
//
// public List<LogExtractor> getExtractors() {
// return extractors;
// }
//
// public List<LogExtractor> getAvailableExtractors() {
// return availableExtractors;
// }
// }
//
// Path: src/main/java/ys/gclog/parser/extract/Extractors.java
// public final class Extractors {
//
// private static final List<LogExtractor> PRIMARY_EXTRACTORS =
// Collections.unmodifiableList(Arrays.asList(
// new SimpleMinorCollectionExtractor(),
// new SimpleFullCollectionExtractor(),
// new DetailedMinorCollectionExtractor(),
// new DetailedFullCollectionExtractor(),
// new CmsCollectorExtractor(),
// new G1CollectorExtractor()));
//
// private static final List<LogExtractor> SECONDARY_EXTRACTORS =
// Collections.unmodifiableList(Arrays.asList(
// new SerialYoungCollectorExtractor(),
// new ParallelYoungCollectorExtractor(),
// new ParallelNewYoungCollectorExtractor(),
// new SerialOldCollectorExtractor(),
// new ParallelOldCollectorExtractor(),
// new PermGenCollectorExtractor(),
// new MetaspaceCollectorExtractor()));
//
// private Extractors() {}
//
// public static List<LogExtractor> primaryExtractors() {
// return PRIMARY_EXTRACTORS;
// }
//
// public static List<LogExtractor> secondaryExtractors() {
// return SECONDARY_EXTRACTORS;
// }
// }
//
// Path: src/main/java/ys/gclog/parser/extract/LogExtractor.java
// public interface LogExtractor {
//
// String REGEX_DECIMAL = "(\\d+\\.\\d+)";
// String REGEX_TIME = REGEX_DECIMAL;
// /**
// * Regular expression for the date field, e.g. {@code 2015-01-15T12:30:38.059+0300}.
// */
// String REGEX_DATE = "(\\d+-\\d+-\\d+T\\d+:\\d+:\\d+\\.\\d+\\+\\d+)";
// String REGEX_MEMORY_AT = "(\\d+)K\\((\\d+)K\\)";
// String REGEX_MEMORY_FROM_TO_KB = "(\\d+)K->(\\d+)K\\((\\d+)K\\)";
// String REGEX_MEMORY_FROM_TO_MB = "(\\d+)M->(\\d+)M\\((\\d+)M\\)";
// String REGEX_MEMORY_WITH_TOTAL_FROM_TO = String.format(
// "%s[BKM]\\(%s[BKM]\\)->%s[BKM]\\(%s[BKM]\\)",
// REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL);
// String REGEX_MEMORY_WITHOUT_TOTAL_FROM_TO =
// String.format("%s[BKM]->%s[BKM]", REGEX_DECIMAL, REGEX_DECIMAL);
// String REGEX_TIMES = String.format("\\[Times: user=%s sys=%s, real=%s secs]",
// REGEX_DECIMAL, REGEX_DECIMAL, REGEX_DECIMAL);
//
// boolean accept(String log);
//
// Optional<Map<String, String>> extract(String log, ExtractContext context);
//
// static void putIfNotNull(Map<String, String> map, String key, String value) {
// if (value != null) {
// map.put(key, value);
// }
// }
// }
// Path: src/main/java/ys/gclog/parser/GCLogParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import ys.gclog.parser.extract.ExtractContext;
import ys.gclog.parser.extract.Extractors;
import ys.gclog.parser.extract.LogExtractor;
String startLine = reader.readLine();
if (startLine == null) {
return null;
}
buffer.add(startLine);
}
String nextLine = reader.readLine();
while (nextLine != null && PATTERN_IDENT.matcher(nextLine).find()) {
buffer.add(nextLine);
nextLine = reader.readLine();
}
String result = buffer.stream().collect(Collectors.joining("\n"));
buffer.clear();
if (nextLine != null) {
buffer.add(nextLine);
}
return result;
}
private static Optional<Map<String, String>> extract(
String line, List<LogExtractor> extractors, Map<LogExtractor, ExtractContext> contexts) {
for (LogExtractor extractor : extractors) {
Optional<Map<String, String>> option = extractor.extract(line, contexts.get(extractor));
if (option.isPresent()) {
return option;
}
}
|
ExtractContext context = new ExtractContext(Extractors.secondaryExtractors());
|
yshahun/gc-log-parser
|
src/test/java/ys/gclog/parser/GCLogParserTest.java
|
// Path: src/test/java/ys/gclog/LogAware.java
// public interface LogAware {
//
// static InputStream getLog(String name) {
// InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
// if (stream == null) {
// throw new IllegalStateException(String.format("Resource %s is not found.", name));
// }
// return stream;
// }
// }
|
import static org.junit.Assert.assertEquals;
import java.io.InputStream;
import org.junit.Before;
import org.junit.Test;
import ys.gclog.LogAware;
|
package ys.gclog.parser;
public class GCLogParserTest {
private GCLogParser parser;
@Before
public void setUp() {
parser = new GCLogParser();
}
/*
* Serial collector, Java 7.
*/
@Test
public void testParse_java7_serial() throws Exception {
|
// Path: src/test/java/ys/gclog/LogAware.java
// public interface LogAware {
//
// static InputStream getLog(String name) {
// InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
// if (stream == null) {
// throw new IllegalStateException(String.format("Resource %s is not found.", name));
// }
// return stream;
// }
// }
// Path: src/test/java/ys/gclog/parser/GCLogParserTest.java
import static org.junit.Assert.assertEquals;
import java.io.InputStream;
import org.junit.Before;
import org.junit.Test;
import ys.gclog.LogAware;
package ys.gclog.parser;
public class GCLogParserTest {
private GCLogParser parser;
@Before
public void setUp() {
parser = new GCLogParser();
}
/*
* Serial collector, Java 7.
*/
@Test
public void testParse_java7_serial() throws Exception {
|
try (InputStream input = LogAware.getLog("gc-7-serial-01.log")) {
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/ViewCreator.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/Factory.java
// public interface Factory<T> {
// T create();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.factory.Factory;
import com.benny.library.autoadapter.viewholder.IViewHolder;
|
package com.benny.library.autoadapter.viewcreator;
/**
* Created by benny on 2/15/16.
*/
public class ViewCreator<T> implements IViewCreator<T> {
private int resId;
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/Factory.java
// public interface Factory<T> {
// T create();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/ViewCreator.java
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.factory.Factory;
import com.benny.library.autoadapter.viewholder.IViewHolder;
package com.benny.library.autoadapter.viewcreator;
/**
* Created by benny on 2/15/16.
*/
public class ViewCreator<T> implements IViewCreator<T> {
private int resId;
|
private Factory<? extends IViewHolder<T>> factory;
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/ViewCreator.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/Factory.java
// public interface Factory<T> {
// T create();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.factory.Factory;
import com.benny.library.autoadapter.viewholder.IViewHolder;
|
package com.benny.library.autoadapter.viewcreator;
/**
* Created by benny on 2/15/16.
*/
public class ViewCreator<T> implements IViewCreator<T> {
private int resId;
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/Factory.java
// public interface Factory<T> {
// T create();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/ViewCreator.java
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.factory.Factory;
import com.benny.library.autoadapter.viewholder.IViewHolder;
package com.benny.library.autoadapter.viewcreator;
/**
* Created by benny on 2/15/16.
*/
public class ViewCreator<T> implements IViewCreator<T> {
private int resId;
|
private Factory<? extends IViewHolder<T>> factory;
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/SimpleAdapterItemAccessor.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
|
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import java.util.ArrayList;
import java.util.List;
|
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class SimpleAdapterItemAccessor<T> implements IAdapterItemAccessor<T> {
private List<T> data;
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/SimpleAdapterItemAccessor.java
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import java.util.ArrayList;
import java.util.List;
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class SimpleAdapterItemAccessor<T> implements IAdapterItemAccessor<T> {
private List<T> data;
|
DataSetChangedNotifier changedNotifier;
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoFragmentPagerAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
|
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
|
package com.benny.library.autoadapter;
/**
* Created by benny on 2/27/16.
*/
public class AutoFragmentPagerAdapter extends FragmentPagerAdapter {
protected IAdapterItemAccessor<Fragment> itemAccessor;
public AutoFragmentPagerAdapter(FragmentManager fragmentManager, IAdapterItemAccessor<Fragment> itemAccessor) {
super(fragmentManager);
this.itemAccessor = itemAccessor;
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoFragmentPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
package com.benny.library.autoadapter;
/**
* Created by benny on 2/27/16.
*/
public class AutoFragmentPagerAdapter extends FragmentPagerAdapter {
protected IAdapterItemAccessor<Fragment> itemAccessor;
public AutoFragmentPagerAdapter(FragmentManager fragmentManager, IAdapterItemAccessor<Fragment> itemAccessor) {
super(fragmentManager);
this.itemAccessor = itemAccessor;
|
itemAccessor.setDataSetChangedNotifier(new DataSetChangedNotifier() {
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoRecyclerPagingAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/AdapterPagingCompleteListener.java
// public interface AdapterPagingCompleteListener {
// void onPagingComplete(boolean hasNextPage);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/AdapterPagingListener.java
// public interface AdapterPagingListener<T> {
// void onLoadPage(AdapterPagingCompleteListener receiver, T previous, int position);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
|
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.benny.library.autoadapter.listener.AdapterPagingCompleteListener;
import com.benny.library.autoadapter.listener.AdapterPagingListener;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import java.util.List;
|
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoRecyclerPagingAdapter<T> extends AutoRecyclerAdapter<T> implements AdapterPagingCompleteListener {
private AdapterPagingListener<T> pagingListener;
private boolean hasNextPage = true;
private boolean loading = false;
private Handler handler = new Handler();
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/AdapterPagingCompleteListener.java
// public interface AdapterPagingCompleteListener {
// void onPagingComplete(boolean hasNextPage);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/AdapterPagingListener.java
// public interface AdapterPagingListener<T> {
// void onLoadPage(AdapterPagingCompleteListener receiver, T previous, int position);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoRecyclerPagingAdapter.java
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.benny.library.autoadapter.listener.AdapterPagingCompleteListener;
import com.benny.library.autoadapter.listener.AdapterPagingListener;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import java.util.List;
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoRecyclerPagingAdapter<T> extends AutoRecyclerAdapter<T> implements AdapterPagingCompleteListener {
private AdapterPagingListener<T> pagingListener;
private boolean hasNextPage = true;
private boolean loading = false;
private Handler handler = new Handler();
|
public AutoRecyclerPagingAdapter(IAdapterItemAccessor<T> itemAccessor, IViewCreator<T> viewCreator) {
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoListAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
|
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoListAdapter<T> extends BaseAdapter {
private AdapterView.OnItemClickListener itemClickListener;
private AdapterView.OnItemLongClickListener itemLongClickListener;
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoListAdapter.java
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoListAdapter<T> extends BaseAdapter {
private AdapterView.OnItemClickListener itemClickListener;
private AdapterView.OnItemLongClickListener itemLongClickListener;
|
private IViewCreator<T> viewCreator;
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoListAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
|
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoListAdapter<T> extends BaseAdapter {
private AdapterView.OnItemClickListener itemClickListener;
private AdapterView.OnItemLongClickListener itemLongClickListener;
private IViewCreator<T> viewCreator;
protected IAdapterItemAccessor<T> itemAccessor;
public AutoListAdapter(IAdapterItemAccessor<T> itemAccessor, IViewCreator<T> viewCreator) {
this.viewCreator = viewCreator;
this.itemAccessor = itemAccessor;
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoListAdapter.java
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoListAdapter<T> extends BaseAdapter {
private AdapterView.OnItemClickListener itemClickListener;
private AdapterView.OnItemLongClickListener itemLongClickListener;
private IViewCreator<T> viewCreator;
protected IAdapterItemAccessor<T> itemAccessor;
public AutoListAdapter(IAdapterItemAccessor<T> itemAccessor, IViewCreator<T> viewCreator) {
this.viewCreator = viewCreator;
this.itemAccessor = itemAccessor;
|
itemAccessor.setDataSetChangedNotifier(new DataSetChangedNotifier() {
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoListAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
|
@SuppressWarnings("unchecked")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = viewCreator.view(parent);
}
if(itemClickListener != null) {
final View finalView = convertView;
final int finalPosition = position;
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemClickListener.onItemClick(null, finalView, finalPosition, 0);
}
});
}
if(itemLongClickListener != null) {
final View finalView = convertView;
final int finalPosition = position;
convertView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
itemLongClickListener.onItemLongClick(null, finalView, finalPosition, 0);
return true;
}
});
}
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoListAdapter.java
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
@SuppressWarnings("unchecked")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = viewCreator.view(parent);
}
if(itemClickListener != null) {
final View finalView = convertView;
final int finalPosition = position;
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemClickListener.onItemClick(null, finalView, finalPosition, 0);
}
});
}
if(itemLongClickListener != null) {
final View finalView = convertView;
final int finalPosition = position;
convertView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
itemLongClickListener.onItemLongClick(null, finalView, finalPosition, 0);
return true;
}
});
}
|
((IViewHolder<T>)convertView.getTag()).onDataChange(new DataGetter<T>(getItem(position - 1), getItem(position), getItem(position + 1)), position);
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoListAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
|
@SuppressWarnings("unchecked")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = viewCreator.view(parent);
}
if(itemClickListener != null) {
final View finalView = convertView;
final int finalPosition = position;
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemClickListener.onItemClick(null, finalView, finalPosition, 0);
}
});
}
if(itemLongClickListener != null) {
final View finalView = convertView;
final int finalPosition = position;
convertView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
itemLongClickListener.onItemLongClick(null, finalView, finalPosition, 0);
return true;
}
});
}
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoListAdapter.java
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
@SuppressWarnings("unchecked")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = viewCreator.view(parent);
}
if(itemClickListener != null) {
final View finalView = convertView;
final int finalPosition = position;
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemClickListener.onItemClick(null, finalView, finalPosition, 0);
}
});
}
if(itemLongClickListener != null) {
final View finalView = convertView;
final int finalPosition = position;
convertView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
itemLongClickListener.onItemLongClick(null, finalView, finalPosition, 0);
return true;
}
});
}
|
((IViewHolder<T>)convertView.getTag()).onDataChange(new DataGetter<T>(getItem(position - 1), getItem(position), getItem(position + 1)), position);
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/factory/MockViewHolerFactory.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/MockViewHolder.java
// public class MockViewHolder<T> implements IViewHolder<T> {
// @Override
// public void bind(View view) {
// }
//
// @Override
// public void onDataChange(DataGetter<T> getter, int position) {
// }
// }
|
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import com.benny.library.autoadapter.viewholder.MockViewHolder;
|
package com.benny.library.autoadapter.factory;
/**
* Created by benny on 2/27/16.
*/
public class MockViewHolerFactory<T> implements Factory<IViewHolder<T>> {
@Override
public IViewHolder<T> create() {
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/MockViewHolder.java
// public class MockViewHolder<T> implements IViewHolder<T> {
// @Override
// public void bind(View view) {
// }
//
// @Override
// public void onDataChange(DataGetter<T> getter, int position) {
// }
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/MockViewHolerFactory.java
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import com.benny.library.autoadapter.viewholder.MockViewHolder;
package com.benny.library.autoadapter.factory;
/**
* Created by benny on 2/27/16.
*/
public class MockViewHolerFactory<T> implements Factory<IViewHolder<T>> {
@Override
public IViewHolder<T> create() {
|
return new MockViewHolder<T>();
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoRecyclerAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
|
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoRecyclerAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private AdapterView.OnItemClickListener itemClickListener;
private AdapterView.OnItemLongClickListener itemLongClickListener;
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoRecyclerAdapter.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoRecyclerAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private AdapterView.OnItemClickListener itemClickListener;
private AdapterView.OnItemLongClickListener itemLongClickListener;
|
private IViewCreator<T> viewCreator;
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoRecyclerAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
|
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoRecyclerAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private AdapterView.OnItemClickListener itemClickListener;
private AdapterView.OnItemLongClickListener itemLongClickListener;
private IViewCreator<T> viewCreator;
protected View emptyView;
protected IAdapterItemAccessor<T> itemAccessor;
public AutoRecyclerAdapter(IAdapterItemAccessor<T> itemAccessor, IViewCreator<T> viewCreator) {
this.viewCreator = viewCreator;
this.itemAccessor = itemAccessor;
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoRecyclerAdapter.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoRecyclerAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private AdapterView.OnItemClickListener itemClickListener;
private AdapterView.OnItemLongClickListener itemLongClickListener;
private IViewCreator<T> viewCreator;
protected View emptyView;
protected IAdapterItemAccessor<T> itemAccessor;
public AutoRecyclerAdapter(IAdapterItemAccessor<T> itemAccessor, IViewCreator<T> viewCreator) {
this.viewCreator = viewCreator;
this.itemAccessor = itemAccessor;
|
itemAccessor.setDataSetChangedNotifier(new DataSetChangedNotifier() {
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoRecyclerAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
|
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoRecyclerAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private AdapterView.OnItemClickListener itemClickListener;
private AdapterView.OnItemLongClickListener itemLongClickListener;
private IViewCreator<T> viewCreator;
protected View emptyView;
protected IAdapterItemAccessor<T> itemAccessor;
public AutoRecyclerAdapter(IAdapterItemAccessor<T> itemAccessor, IViewCreator<T> viewCreator) {
this.viewCreator = viewCreator;
this.itemAccessor = itemAccessor;
itemAccessor.setDataSetChangedNotifier(new DataSetChangedNotifier() {
@Override
public void notifyDataSetChanged() {
AutoRecyclerAdapter.this.notifyDataSetChanged();
}
});
}
public AutoRecyclerAdapter(List<T> items, IViewCreator<T> viewCreator) {
this(new SimpleAdapterItemAccessor<T>(items), viewCreator);
}
protected RecyclerView.ViewHolder createViewHolder(View itemView) {
return new ViewHolder(itemView);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
return createViewHolder(viewCreator.view(viewGroup));
}
@SuppressWarnings("unchecked")
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoRecyclerAdapter.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoRecyclerAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private AdapterView.OnItemClickListener itemClickListener;
private AdapterView.OnItemLongClickListener itemLongClickListener;
private IViewCreator<T> viewCreator;
protected View emptyView;
protected IAdapterItemAccessor<T> itemAccessor;
public AutoRecyclerAdapter(IAdapterItemAccessor<T> itemAccessor, IViewCreator<T> viewCreator) {
this.viewCreator = viewCreator;
this.itemAccessor = itemAccessor;
itemAccessor.setDataSetChangedNotifier(new DataSetChangedNotifier() {
@Override
public void notifyDataSetChanged() {
AutoRecyclerAdapter.this.notifyDataSetChanged();
}
});
}
public AutoRecyclerAdapter(List<T> items, IViewCreator<T> viewCreator) {
this(new SimpleAdapterItemAccessor<T>(items), viewCreator);
}
protected RecyclerView.ViewHolder createViewHolder(View itemView) {
return new ViewHolder(itemView);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
return createViewHolder(viewCreator.view(viewGroup));
}
@SuppressWarnings("unchecked")
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
|
((ViewHolder)viewHolder).notifyDataChange(new DataGetter<T>(getItem(position - 1), getItem(position), getItem(position + 1)), position);
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoRecyclerAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
|
public void setEmptyView(View view) {
emptyView = view;
}
protected class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(final View itemView) {
super(itemView);
if(itemClickListener != null) {
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemClickListener.onItemClick(null, itemView, getLayoutPosition(), 0);
}
});
}
if(itemLongClickListener != null) {
itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
itemLongClickListener.onItemLongClick(null, itemView, getLayoutPosition(), 0);
return true;
}
});
}
}
@SuppressWarnings("unchecked")
void notifyDataChange(DataGetter<T> getter, int position) {
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoRecyclerAdapter.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
public void setEmptyView(View view) {
emptyView = view;
}
protected class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(final View itemView) {
super(itemView);
if(itemClickListener != null) {
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemClickListener.onItemClick(null, itemView, getLayoutPosition(), 0);
}
});
}
if(itemLongClickListener != null) {
itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
itemLongClickListener.onItemLongClick(null, itemView, getLayoutPosition(), 0);
return true;
}
});
}
}
@SuppressWarnings("unchecked")
void notifyDataChange(DataGetter<T> getter, int position) {
|
((IViewHolder<T>)itemView.getTag()).onDataChange(getter, position);
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoListPagingAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/AdapterPagingCompleteListener.java
// public interface AdapterPagingCompleteListener {
// void onPagingComplete(boolean hasNextPage);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/AdapterPagingListener.java
// public interface AdapterPagingListener<T> {
// void onLoadPage(AdapterPagingCompleteListener receiver, T previous, int position);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
|
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.listener.AdapterPagingCompleteListener;
import com.benny.library.autoadapter.listener.AdapterPagingListener;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import java.util.List;
|
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoListPagingAdapter<T> extends AutoListAdapter<T> implements AdapterPagingCompleteListener {
private boolean hasNextPage = true;
private boolean loading = false;
private Handler handler = new Handler();
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/AdapterPagingCompleteListener.java
// public interface AdapterPagingCompleteListener {
// void onPagingComplete(boolean hasNextPage);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/AdapterPagingListener.java
// public interface AdapterPagingListener<T> {
// void onLoadPage(AdapterPagingCompleteListener receiver, T previous, int position);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoListPagingAdapter.java
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.listener.AdapterPagingCompleteListener;
import com.benny.library.autoadapter.listener.AdapterPagingListener;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import java.util.List;
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoListPagingAdapter<T> extends AutoListAdapter<T> implements AdapterPagingCompleteListener {
private boolean hasNextPage = true;
private boolean loading = false;
private Handler handler = new Handler();
|
private AdapterPagingListener<T> pagingListener;
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoListPagingAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/AdapterPagingCompleteListener.java
// public interface AdapterPagingCompleteListener {
// void onPagingComplete(boolean hasNextPage);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/AdapterPagingListener.java
// public interface AdapterPagingListener<T> {
// void onLoadPage(AdapterPagingCompleteListener receiver, T previous, int position);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
|
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.listener.AdapterPagingCompleteListener;
import com.benny.library.autoadapter.listener.AdapterPagingListener;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import java.util.List;
|
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoListPagingAdapter<T> extends AutoListAdapter<T> implements AdapterPagingCompleteListener {
private boolean hasNextPage = true;
private boolean loading = false;
private Handler handler = new Handler();
private AdapterPagingListener<T> pagingListener;
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/AdapterPagingCompleteListener.java
// public interface AdapterPagingCompleteListener {
// void onPagingComplete(boolean hasNextPage);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/AdapterPagingListener.java
// public interface AdapterPagingListener<T> {
// void onLoadPage(AdapterPagingCompleteListener receiver, T previous, int position);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoListPagingAdapter.java
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.listener.AdapterPagingCompleteListener;
import com.benny.library.autoadapter.listener.AdapterPagingListener;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import java.util.List;
package com.benny.library.autoadapter;
/**
* Created by benny on 2/26/16.
*/
public class AutoListPagingAdapter<T> extends AutoListAdapter<T> implements AdapterPagingCompleteListener {
private boolean hasNextPage = true;
private boolean loading = false;
private Handler handler = new Handler();
private AdapterPagingListener<T> pagingListener;
|
public AutoListPagingAdapter(IAdapterItemAccessor<T> itemAccessor, IViewCreator<T> viewCreator) {
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/ViewCreatorCollection.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/Factory.java
// public interface Factory<T> {
// T create();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/MockViewHolerFactory.java
// public class MockViewHolerFactory<T> implements Factory<IViewHolder<T>> {
// @Override
// public IViewHolder<T> create() {
// return new MockViewHolder<T>();
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/utils/Func3.java
// public interface Func3<T1, T2, T3, R> {
// R call(T1 t1, T2 t2, T3 t3);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/MockViewHolder.java
// public class MockViewHolder<T> implements IViewHolder<T> {
// @Override
// public void bind(View view) {
// }
//
// @Override
// public void onDataChange(DataGetter<T> getter, int position) {
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.factory.Factory;
import com.benny.library.autoadapter.factory.MockViewHolerFactory;
import com.benny.library.autoadapter.utils.Func3;
import com.benny.library.autoadapter.viewholder.MockViewHolder;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.ArrayList;
import java.util.List;
|
package com.benny.library.autoadapter.viewcreator;
/**
* Created by benny on 2/15/16.
*/
public class ViewCreatorCollection<T> implements IViewCreator<T> {
private int lastViewType = -1;
private List<ViewTypeFilter<T> > viewTypeFilters = new ArrayList<ViewTypeFilter<T>>();
protected ViewCreatorCollection(List<ViewTypeFilter<T> > viewTypeFilters) {
this.viewTypeFilters = viewTypeFilters;
}
private ViewTypeFilter<T> filter(T data, int position, int itemCount) {
for(ViewTypeFilter<T> viewTypeFilter : viewTypeFilters) {
if(viewTypeFilter.canProcess(data, position, itemCount)) return viewTypeFilter;
}
throw new RuntimeException("can not process view type for: " + data.toString());
}
@Override
public View view(ViewGroup container) {
int index = (lastViewType != -1) ? lastViewType : viewTypeFilters.size() - 1;
return viewTypeFilters.get(index).creator.view(container);
}
@Override
public int viewTypeFor(T data, int position, int itemCount) {
lastViewType = filter(data, position, itemCount).viewType;
return lastViewType;
}
@Override
public int viewTypeCount() {
return viewTypeFilters.size();
}
public static class ViewTypeFilter<T> {
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/Factory.java
// public interface Factory<T> {
// T create();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/MockViewHolerFactory.java
// public class MockViewHolerFactory<T> implements Factory<IViewHolder<T>> {
// @Override
// public IViewHolder<T> create() {
// return new MockViewHolder<T>();
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/utils/Func3.java
// public interface Func3<T1, T2, T3, R> {
// R call(T1 t1, T2 t2, T3 t3);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/MockViewHolder.java
// public class MockViewHolder<T> implements IViewHolder<T> {
// @Override
// public void bind(View view) {
// }
//
// @Override
// public void onDataChange(DataGetter<T> getter, int position) {
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/ViewCreatorCollection.java
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.factory.Factory;
import com.benny.library.autoadapter.factory.MockViewHolerFactory;
import com.benny.library.autoadapter.utils.Func3;
import com.benny.library.autoadapter.viewholder.MockViewHolder;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.ArrayList;
import java.util.List;
package com.benny.library.autoadapter.viewcreator;
/**
* Created by benny on 2/15/16.
*/
public class ViewCreatorCollection<T> implements IViewCreator<T> {
private int lastViewType = -1;
private List<ViewTypeFilter<T> > viewTypeFilters = new ArrayList<ViewTypeFilter<T>>();
protected ViewCreatorCollection(List<ViewTypeFilter<T> > viewTypeFilters) {
this.viewTypeFilters = viewTypeFilters;
}
private ViewTypeFilter<T> filter(T data, int position, int itemCount) {
for(ViewTypeFilter<T> viewTypeFilter : viewTypeFilters) {
if(viewTypeFilter.canProcess(data, position, itemCount)) return viewTypeFilter;
}
throw new RuntimeException("can not process view type for: " + data.toString());
}
@Override
public View view(ViewGroup container) {
int index = (lastViewType != -1) ? lastViewType : viewTypeFilters.size() - 1;
return viewTypeFilters.get(index).creator.view(container);
}
@Override
public int viewTypeFor(T data, int position, int itemCount) {
lastViewType = filter(data, position, itemCount).viewType;
return lastViewType;
}
@Override
public int viewTypeCount() {
return viewTypeFilters.size();
}
public static class ViewTypeFilter<T> {
|
public Func3<T, Integer, Integer, Boolean> filter;
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/ViewCreatorCollection.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/Factory.java
// public interface Factory<T> {
// T create();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/MockViewHolerFactory.java
// public class MockViewHolerFactory<T> implements Factory<IViewHolder<T>> {
// @Override
// public IViewHolder<T> create() {
// return new MockViewHolder<T>();
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/utils/Func3.java
// public interface Func3<T1, T2, T3, R> {
// R call(T1 t1, T2 t2, T3 t3);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/MockViewHolder.java
// public class MockViewHolder<T> implements IViewHolder<T> {
// @Override
// public void bind(View view) {
// }
//
// @Override
// public void onDataChange(DataGetter<T> getter, int position) {
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.factory.Factory;
import com.benny.library.autoadapter.factory.MockViewHolerFactory;
import com.benny.library.autoadapter.utils.Func3;
import com.benny.library.autoadapter.viewholder.MockViewHolder;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.ArrayList;
import java.util.List;
|
}
public boolean canProcess(T data, int position, int itemCount) {
return filter.call(data, position, itemCount);
}
}
public static class Builder<T> {
private int loadingResId = -1;
private List<ViewTypeFilter<T> > viewTypeFilters = new ArrayList<ViewTypeFilter<T>>();
private IViewCreator<T> defaultViewCreator;
private Func3<T, Integer, Integer, Boolean> alwaysTrue = new Func3<T, Integer, Integer, Boolean>() {
@Override
public Boolean call(T t, Integer integer, Integer integer2) {
return true;
}
};
public Builder<T> loadingResId(int loadingResId) {
this.loadingResId = loadingResId;
return this;
}
public Builder<T> addFilter(IViewCreator<T> viewCreator) {
defaultViewCreator = viewCreator;
return this;
}
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/Factory.java
// public interface Factory<T> {
// T create();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/MockViewHolerFactory.java
// public class MockViewHolerFactory<T> implements Factory<IViewHolder<T>> {
// @Override
// public IViewHolder<T> create() {
// return new MockViewHolder<T>();
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/utils/Func3.java
// public interface Func3<T1, T2, T3, R> {
// R call(T1 t1, T2 t2, T3 t3);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/MockViewHolder.java
// public class MockViewHolder<T> implements IViewHolder<T> {
// @Override
// public void bind(View view) {
// }
//
// @Override
// public void onDataChange(DataGetter<T> getter, int position) {
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/ViewCreatorCollection.java
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.factory.Factory;
import com.benny.library.autoadapter.factory.MockViewHolerFactory;
import com.benny.library.autoadapter.utils.Func3;
import com.benny.library.autoadapter.viewholder.MockViewHolder;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.ArrayList;
import java.util.List;
}
public boolean canProcess(T data, int position, int itemCount) {
return filter.call(data, position, itemCount);
}
}
public static class Builder<T> {
private int loadingResId = -1;
private List<ViewTypeFilter<T> > viewTypeFilters = new ArrayList<ViewTypeFilter<T>>();
private IViewCreator<T> defaultViewCreator;
private Func3<T, Integer, Integer, Boolean> alwaysTrue = new Func3<T, Integer, Integer, Boolean>() {
@Override
public Boolean call(T t, Integer integer, Integer integer2) {
return true;
}
};
public Builder<T> loadingResId(int loadingResId) {
this.loadingResId = loadingResId;
return this;
}
public Builder<T> addFilter(IViewCreator<T> viewCreator) {
defaultViewCreator = viewCreator;
return this;
}
|
public Builder<T> addFilter(int resId, Factory<? extends IViewHolder<T>> factory) {
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/ViewCreatorCollection.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/Factory.java
// public interface Factory<T> {
// T create();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/MockViewHolerFactory.java
// public class MockViewHolerFactory<T> implements Factory<IViewHolder<T>> {
// @Override
// public IViewHolder<T> create() {
// return new MockViewHolder<T>();
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/utils/Func3.java
// public interface Func3<T1, T2, T3, R> {
// R call(T1 t1, T2 t2, T3 t3);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/MockViewHolder.java
// public class MockViewHolder<T> implements IViewHolder<T> {
// @Override
// public void bind(View view) {
// }
//
// @Override
// public void onDataChange(DataGetter<T> getter, int position) {
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.factory.Factory;
import com.benny.library.autoadapter.factory.MockViewHolerFactory;
import com.benny.library.autoadapter.utils.Func3;
import com.benny.library.autoadapter.viewholder.MockViewHolder;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.ArrayList;
import java.util.List;
|
}
public boolean canProcess(T data, int position, int itemCount) {
return filter.call(data, position, itemCount);
}
}
public static class Builder<T> {
private int loadingResId = -1;
private List<ViewTypeFilter<T> > viewTypeFilters = new ArrayList<ViewTypeFilter<T>>();
private IViewCreator<T> defaultViewCreator;
private Func3<T, Integer, Integer, Boolean> alwaysTrue = new Func3<T, Integer, Integer, Boolean>() {
@Override
public Boolean call(T t, Integer integer, Integer integer2) {
return true;
}
};
public Builder<T> loadingResId(int loadingResId) {
this.loadingResId = loadingResId;
return this;
}
public Builder<T> addFilter(IViewCreator<T> viewCreator) {
defaultViewCreator = viewCreator;
return this;
}
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/Factory.java
// public interface Factory<T> {
// T create();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/MockViewHolerFactory.java
// public class MockViewHolerFactory<T> implements Factory<IViewHolder<T>> {
// @Override
// public IViewHolder<T> create() {
// return new MockViewHolder<T>();
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/utils/Func3.java
// public interface Func3<T1, T2, T3, R> {
// R call(T1 t1, T2 t2, T3 t3);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/MockViewHolder.java
// public class MockViewHolder<T> implements IViewHolder<T> {
// @Override
// public void bind(View view) {
// }
//
// @Override
// public void onDataChange(DataGetter<T> getter, int position) {
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/ViewCreatorCollection.java
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.factory.Factory;
import com.benny.library.autoadapter.factory.MockViewHolerFactory;
import com.benny.library.autoadapter.utils.Func3;
import com.benny.library.autoadapter.viewholder.MockViewHolder;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.ArrayList;
import java.util.List;
}
public boolean canProcess(T data, int position, int itemCount) {
return filter.call(data, position, itemCount);
}
}
public static class Builder<T> {
private int loadingResId = -1;
private List<ViewTypeFilter<T> > viewTypeFilters = new ArrayList<ViewTypeFilter<T>>();
private IViewCreator<T> defaultViewCreator;
private Func3<T, Integer, Integer, Boolean> alwaysTrue = new Func3<T, Integer, Integer, Boolean>() {
@Override
public Boolean call(T t, Integer integer, Integer integer2) {
return true;
}
};
public Builder<T> loadingResId(int loadingResId) {
this.loadingResId = loadingResId;
return this;
}
public Builder<T> addFilter(IViewCreator<T> viewCreator) {
defaultViewCreator = viewCreator;
return this;
}
|
public Builder<T> addFilter(int resId, Factory<? extends IViewHolder<T>> factory) {
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/ViewCreatorCollection.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/Factory.java
// public interface Factory<T> {
// T create();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/MockViewHolerFactory.java
// public class MockViewHolerFactory<T> implements Factory<IViewHolder<T>> {
// @Override
// public IViewHolder<T> create() {
// return new MockViewHolder<T>();
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/utils/Func3.java
// public interface Func3<T1, T2, T3, R> {
// R call(T1 t1, T2 t2, T3 t3);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/MockViewHolder.java
// public class MockViewHolder<T> implements IViewHolder<T> {
// @Override
// public void bind(View view) {
// }
//
// @Override
// public void onDataChange(DataGetter<T> getter, int position) {
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.factory.Factory;
import com.benny.library.autoadapter.factory.MockViewHolerFactory;
import com.benny.library.autoadapter.utils.Func3;
import com.benny.library.autoadapter.viewholder.MockViewHolder;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.ArrayList;
import java.util.List;
|
return this;
}
public Builder<T> addFilter(IViewCreator<T> viewCreator) {
defaultViewCreator = viewCreator;
return this;
}
public Builder<T> addFilter(int resId, Factory<? extends IViewHolder<T>> factory) {
defaultViewCreator = new ViewCreator<T>(resId, factory);
return this;
}
public Builder<T> addFilter(Func3<T, Integer, Integer, Boolean> filter, int resId, Factory<? extends IViewHolder<T>> factory) {
viewTypeFilters.add(new ViewTypeFilter<T>(filter, new ViewCreator<T>(resId, factory), viewTypeFilters.size()));
return this;
}
public Builder<T> addFilter(Func3<T, Integer, Integer, Boolean> filter, IViewCreator<T> viewCreator) {
viewTypeFilters.add(new ViewTypeFilter<T>(filter, viewCreator, viewTypeFilters.size()));
return this;
}
public ViewCreatorCollection<T> build() {
if(loadingResId != -1) {
viewTypeFilters.add(new ViewTypeFilter<T>(new Func3<T, Integer, Integer, Boolean>() {
@Override
public Boolean call(T data, Integer position, Integer itemCount) {
return data == null && position == itemCount - 1;
}
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/Factory.java
// public interface Factory<T> {
// T create();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/factory/MockViewHolerFactory.java
// public class MockViewHolerFactory<T> implements Factory<IViewHolder<T>> {
// @Override
// public IViewHolder<T> create() {
// return new MockViewHolder<T>();
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/utils/Func3.java
// public interface Func3<T1, T2, T3, R> {
// R call(T1 t1, T2 t2, T3 t3);
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/MockViewHolder.java
// public class MockViewHolder<T> implements IViewHolder<T> {
// @Override
// public void bind(View view) {
// }
//
// @Override
// public void onDataChange(DataGetter<T> getter, int position) {
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/ViewCreatorCollection.java
import android.view.View;
import android.view.ViewGroup;
import com.benny.library.autoadapter.factory.Factory;
import com.benny.library.autoadapter.factory.MockViewHolerFactory;
import com.benny.library.autoadapter.utils.Func3;
import com.benny.library.autoadapter.viewholder.MockViewHolder;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.ArrayList;
import java.util.List;
return this;
}
public Builder<T> addFilter(IViewCreator<T> viewCreator) {
defaultViewCreator = viewCreator;
return this;
}
public Builder<T> addFilter(int resId, Factory<? extends IViewHolder<T>> factory) {
defaultViewCreator = new ViewCreator<T>(resId, factory);
return this;
}
public Builder<T> addFilter(Func3<T, Integer, Integer, Boolean> filter, int resId, Factory<? extends IViewHolder<T>> factory) {
viewTypeFilters.add(new ViewTypeFilter<T>(filter, new ViewCreator<T>(resId, factory), viewTypeFilters.size()));
return this;
}
public Builder<T> addFilter(Func3<T, Integer, Integer, Boolean> filter, IViewCreator<T> viewCreator) {
viewTypeFilters.add(new ViewTypeFilter<T>(filter, viewCreator, viewTypeFilters.size()));
return this;
}
public ViewCreatorCollection<T> build() {
if(loadingResId != -1) {
viewTypeFilters.add(new ViewTypeFilter<T>(new Func3<T, Integer, Integer, Boolean>() {
@Override
public Boolean call(T data, Integer position, Integer itemCount) {
return data == null && position == itemCount - 1;
}
|
}, new ViewCreator<T>(loadingResId, new MockViewHolerFactory<T>()), viewTypeFilters.size()));
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoPagerAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
|
package com.benny.library.autoadapter;
/**
* Created by benny on 2/27/16.
*/
public class AutoPagerAdapter<T> extends PagerAdapter {
private IViewCreator<T> viewCreator;
private AdapterView.OnItemClickListener itemClickListener;
private AdapterView.OnItemLongClickListener itemLongClickListener;
private View emptyView;
protected IAdapterItemAccessor<T> itemAccessor;
public AutoPagerAdapter(IAdapterItemAccessor<T> itemAccessor, IViewCreator<T> viewCreator) {
this.viewCreator = viewCreator;
this.itemAccessor = itemAccessor;
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoPagerAdapter.java
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
package com.benny.library.autoadapter;
/**
* Created by benny on 2/27/16.
*/
public class AutoPagerAdapter<T> extends PagerAdapter {
private IViewCreator<T> viewCreator;
private AdapterView.OnItemClickListener itemClickListener;
private AdapterView.OnItemLongClickListener itemLongClickListener;
private View emptyView;
protected IAdapterItemAccessor<T> itemAccessor;
public AutoPagerAdapter(IAdapterItemAccessor<T> itemAccessor, IViewCreator<T> viewCreator) {
this.viewCreator = viewCreator;
this.itemAccessor = itemAccessor;
|
itemAccessor.setDataSetChangedNotifier(new DataSetChangedNotifier() {
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoPagerAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
|
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@SuppressWarnings("unchecked")
@Override
public Object instantiateItem(ViewGroup container, final int position) {
viewCreator.viewTypeFor(getItem(position), position, getCount());
final View itemView = viewCreator.view(container);
container.addView(itemView);
if(itemClickListener != null) {
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemClickListener.onItemClick(null, itemView, position, 0);
}
});
}
if(itemLongClickListener != null) {
itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
itemLongClickListener.onItemLongClick(null, itemView, position, 0);
return false;
}
});
}
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoPagerAdapter.java
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@SuppressWarnings("unchecked")
@Override
public Object instantiateItem(ViewGroup container, final int position) {
viewCreator.viewTypeFor(getItem(position), position, getCount());
final View itemView = viewCreator.view(container);
container.addView(itemView);
if(itemClickListener != null) {
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemClickListener.onItemClick(null, itemView, position, 0);
}
});
}
if(itemLongClickListener != null) {
itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
itemLongClickListener.onItemLongClick(null, itemView, position, 0);
return false;
}
});
}
|
((IViewHolder<T>)itemView.getTag()).onDataChange(new DataGetter<T>(getItem(position - 1), getItem(position), getItem(position + 1)), position);
|
BennyWang/AutoAdapter
|
autoadapter/src/main/java/com/benny/library/autoadapter/AutoPagerAdapter.java
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
|
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
|
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@SuppressWarnings("unchecked")
@Override
public Object instantiateItem(ViewGroup container, final int position) {
viewCreator.viewTypeFor(getItem(position), position, getCount());
final View itemView = viewCreator.view(container);
container.addView(itemView);
if(itemClickListener != null) {
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemClickListener.onItemClick(null, itemView, position, 0);
}
});
}
if(itemLongClickListener != null) {
itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
itemLongClickListener.onItemLongClick(null, itemView, position, 0);
return false;
}
});
}
|
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/listener/DataSetChangedNotifier.java
// public interface DataSetChangedNotifier {
// void notifyDataSetChanged();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewcreator/IViewCreator.java
// public interface IViewCreator<T> {
// View view(ViewGroup container);
// int viewTypeFor(T data, int position, int itemCount);
// int viewTypeCount();
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/DataGetter.java
// public class DataGetter<T> {
// final public T previous;
// final public T next;
// final public T data;
//
// public DataGetter(T previous, T data, T next) {
// this.previous = previous;
// this.next = next;
// this.data = data;
// }
// }
//
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/viewholder/IViewHolder.java
// public interface IViewHolder<T> {
// void bind(View view);
// void onDataChange(DataGetter<T> getter, int position);
// }
// Path: autoadapter/src/main/java/com/benny/library/autoadapter/AutoPagerAdapter.java
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.benny.library.autoadapter.listener.DataSetChangedNotifier;
import com.benny.library.autoadapter.viewcreator.IViewCreator;
import com.benny.library.autoadapter.viewholder.DataGetter;
import com.benny.library.autoadapter.viewholder.IViewHolder;
import java.util.List;
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@SuppressWarnings("unchecked")
@Override
public Object instantiateItem(ViewGroup container, final int position) {
viewCreator.viewTypeFor(getItem(position), position, getCount());
final View itemView = viewCreator.view(container);
container.addView(itemView);
if(itemClickListener != null) {
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemClickListener.onItemClick(null, itemView, position, 0);
}
});
}
if(itemLongClickListener != null) {
itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
itemLongClickListener.onItemLongClick(null, itemView, position, 0);
return false;
}
});
}
|
((IViewHolder<T>)itemView.getTag()).onDataChange(new DataGetter<T>(getItem(position - 1), getItem(position), getItem(position + 1)), position);
|
OpherV/gitflow4idea
|
src/main/java/gitflow/GitflowMenu.java
|
// Path: src/main/java/gitflow/actions/GitflowPopupGroup.java
// public class GitflowPopupGroup {
//
// Project myProject;
// DefaultActionGroup actionGroup;
// GitRepositoryManager myRepositoryManager;
// List<GitRepository> gitRepositories;
//
// public GitflowPopupGroup(@NotNull Project project, boolean includeAdvanced) {
// myProject = project;
//
// //fetch all the git repositories from the project;
// myRepositoryManager = GitUtil.getRepositoryManager(project);
// gitRepositories = myRepositoryManager.getRepositories();
//
// createActionGroup(includeAdvanced);
// }
//
// /**
// * Generates the popup actions for the widget
// */
// private void createActionGroup(boolean includeAdvanced){
// actionGroup = new DefaultActionGroup(null, false);
//
//
// if (gitRepositories.size() == 1){
// ActionGroup repoActions =
// (new RepoActions(myProject, gitRepositories.get(0)))
// .getRepoActionGroup(includeAdvanced);
// actionGroup.addAll(repoActions);
// }
// else{
// Iterator gitRepositoriesIterator = gitRepositories.iterator();
// while(gitRepositoriesIterator.hasNext()){
// GitRepository repo = (GitRepository) gitRepositoriesIterator.next();
// RepoActions repoActions = new RepoActions(myProject, repo);
// actionGroup.add(repoActions);
// }
// }
// }
//
// public ActionGroup getActionGroup (){
//
// return actionGroup;
// }
// }
|
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import gitflow.actions.GitflowPopupGroup;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
|
package gitflow;
public class GitflowMenu extends ActionGroup {
public GitflowMenu() {
super("Gitflow", true);
}
@NotNull
@Override
public AnAction[] getChildren(@Nullable AnActionEvent anActionEvent) {
if (anActionEvent == null) {
return new AnAction[0];
}
Project project = anActionEvent.getProject();
if (project == null) {
return new AnAction[0];
}
|
// Path: src/main/java/gitflow/actions/GitflowPopupGroup.java
// public class GitflowPopupGroup {
//
// Project myProject;
// DefaultActionGroup actionGroup;
// GitRepositoryManager myRepositoryManager;
// List<GitRepository> gitRepositories;
//
// public GitflowPopupGroup(@NotNull Project project, boolean includeAdvanced) {
// myProject = project;
//
// //fetch all the git repositories from the project;
// myRepositoryManager = GitUtil.getRepositoryManager(project);
// gitRepositories = myRepositoryManager.getRepositories();
//
// createActionGroup(includeAdvanced);
// }
//
// /**
// * Generates the popup actions for the widget
// */
// private void createActionGroup(boolean includeAdvanced){
// actionGroup = new DefaultActionGroup(null, false);
//
//
// if (gitRepositories.size() == 1){
// ActionGroup repoActions =
// (new RepoActions(myProject, gitRepositories.get(0)))
// .getRepoActionGroup(includeAdvanced);
// actionGroup.addAll(repoActions);
// }
// else{
// Iterator gitRepositoriesIterator = gitRepositories.iterator();
// while(gitRepositoriesIterator.hasNext()){
// GitRepository repo = (GitRepository) gitRepositoriesIterator.next();
// RepoActions repoActions = new RepoActions(myProject, repo);
// actionGroup.add(repoActions);
// }
// }
// }
//
// public ActionGroup getActionGroup (){
//
// return actionGroup;
// }
// }
// Path: src/main/java/gitflow/GitflowMenu.java
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import gitflow.actions.GitflowPopupGroup;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package gitflow;
public class GitflowMenu extends ActionGroup {
public GitflowMenu() {
super("Gitflow", true);
}
@NotNull
@Override
public AnAction[] getChildren(@Nullable AnActionEvent anActionEvent) {
if (anActionEvent == null) {
return new AnAction[0];
}
Project project = anActionEvent.getProject();
if (project == null) {
return new AnAction[0];
}
|
GitflowPopupGroup popupGroup = new GitflowPopupGroup(project, true);
|
OpherV/gitflow4idea
|
src/main/java/gitflow/actions/StartFeatureAction.java
|
// Path: src/main/java/gitflow/ui/GitflowStartFeatureDialog.java
// public class GitflowStartFeatureDialog extends AbstractBranchStartDialog {
//
// public GitflowStartFeatureDialog(Project project, GitRepository repo) {
// super(project, repo);
// }
//
// @Override
// protected String getLabel() {
// return "feature";
// }
//
// @Override
// protected String getDefaultBranch() {
// return GitflowConfigUtil.getInstance(getProject(), myRepo).developBranch;
// }
// }
//
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
|
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import gitflow.ui.GitflowStartFeatureDialog;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
|
package gitflow.actions;
public class StartFeatureAction extends AbstractStartAction {
public StartFeatureAction() {
super("Start Feature");
}
public StartFeatureAction(GitRepository repo) {
super(repo, "Start Feature");
}
@Override
public void actionPerformed(AnActionEvent e) {
super.actionPerformed(e);
|
// Path: src/main/java/gitflow/ui/GitflowStartFeatureDialog.java
// public class GitflowStartFeatureDialog extends AbstractBranchStartDialog {
//
// public GitflowStartFeatureDialog(Project project, GitRepository repo) {
// super(project, repo);
// }
//
// @Override
// protected String getLabel() {
// return "feature";
// }
//
// @Override
// protected String getDefaultBranch() {
// return GitflowConfigUtil.getInstance(getProject(), myRepo).developBranch;
// }
// }
//
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
// Path: src/main/java/gitflow/actions/StartFeatureAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import gitflow.ui.GitflowStartFeatureDialog;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package gitflow.actions;
public class StartFeatureAction extends AbstractStartAction {
public StartFeatureAction() {
super("Start Feature");
}
public StartFeatureAction(GitRepository repo) {
super(repo, "Start Feature");
}
@Override
public void actionPerformed(AnActionEvent e) {
super.actionPerformed(e);
|
GitflowStartFeatureDialog dialog = new GitflowStartFeatureDialog(myProject, myRepo);
|
OpherV/gitflow4idea
|
src/main/java/gitflow/actions/StartFeatureAction.java
|
// Path: src/main/java/gitflow/ui/GitflowStartFeatureDialog.java
// public class GitflowStartFeatureDialog extends AbstractBranchStartDialog {
//
// public GitflowStartFeatureDialog(Project project, GitRepository repo) {
// super(project, repo);
// }
//
// @Override
// protected String getLabel() {
// return "feature";
// }
//
// @Override
// protected String getDefaultBranch() {
// return GitflowConfigUtil.getInstance(getProject(), myRepo).developBranch;
// }
// }
//
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
|
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import gitflow.ui.GitflowStartFeatureDialog;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
|
dialog.show();
if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;
final String featureName = dialog.getNewBranchName();
final String baseBranchName = dialog.getBaseBranchName();
this.runAction(e.getProject(), baseBranchName, featureName, null);
}
public void runAction(final Project project, final String baseBranchName, final String featureName, @Nullable final Runnable callInAwtLater){
super.runAction(project, baseBranchName, featureName, callInAwtLater);
new Task.Backgroundable(myProject, "Starting feature " + featureName, false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
final GitCommandResult commandResult = createFeatureBranch(baseBranchName, featureName);
if (callInAwtLater != null && commandResult.success()) {
callInAwtLater.run();
}
}
}.queue();
}
private GitCommandResult createFeatureBranch(String baseBranchName, String featureName) {
GitflowErrorsListener errorListener = new GitflowErrorsListener(myProject);
GitCommandResult result = myGitflow.startFeature(myRepo, featureName, baseBranchName, errorListener);
if (result.success()) {
String startedFeatureMessage = String.format("A new branch '%s%s' was created, based on '%s'", branchUtil.getPrefixFeature(), featureName, baseBranchName);
|
// Path: src/main/java/gitflow/ui/GitflowStartFeatureDialog.java
// public class GitflowStartFeatureDialog extends AbstractBranchStartDialog {
//
// public GitflowStartFeatureDialog(Project project, GitRepository repo) {
// super(project, repo);
// }
//
// @Override
// protected String getLabel() {
// return "feature";
// }
//
// @Override
// protected String getDefaultBranch() {
// return GitflowConfigUtil.getInstance(getProject(), myRepo).developBranch;
// }
// }
//
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
// Path: src/main/java/gitflow/actions/StartFeatureAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import gitflow.ui.GitflowStartFeatureDialog;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
dialog.show();
if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;
final String featureName = dialog.getNewBranchName();
final String baseBranchName = dialog.getBaseBranchName();
this.runAction(e.getProject(), baseBranchName, featureName, null);
}
public void runAction(final Project project, final String baseBranchName, final String featureName, @Nullable final Runnable callInAwtLater){
super.runAction(project, baseBranchName, featureName, callInAwtLater);
new Task.Backgroundable(myProject, "Starting feature " + featureName, false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
final GitCommandResult commandResult = createFeatureBranch(baseBranchName, featureName);
if (callInAwtLater != null && commandResult.success()) {
callInAwtLater.run();
}
}
}.queue();
}
private GitCommandResult createFeatureBranch(String baseBranchName, String featureName) {
GitflowErrorsListener errorListener = new GitflowErrorsListener(myProject);
GitCommandResult result = myGitflow.startFeature(myRepo, featureName, baseBranchName, errorListener);
if (result.success()) {
String startedFeatureMessage = String.format("A new branch '%s%s' was created, based on '%s'", branchUtil.getPrefixFeature(), featureName, baseBranchName);
|
NotifyUtil.notifySuccess(myProject, featureName, startedFeatureMessage);
|
OpherV/gitflow4idea
|
src/main/java/gitflow/actions/StartHotfixAction.java
|
// Path: src/main/java/gitflow/ui/GitflowStartHotfixDialog.java
// public class GitflowStartHotfixDialog extends AbstractBranchStartDialog {
//
// public GitflowStartHotfixDialog(Project project, GitRepository repo) {
// super(project, repo);
// }
//
// protected boolean showBranchFromCombo(){
// return false;
// }
//
// @Override
// protected String getLabel() {
// return "hotfix";
// }
//
// @Override
// protected String getDefaultBranch() {
// return GitflowConfigUtil.getInstance(getProject(), myRepo).masterBranch;
// }
// }
//
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
|
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import gitflow.ui.GitflowStartHotfixDialog;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
|
package gitflow.actions;
public class StartHotfixAction extends AbstractStartAction {
public StartHotfixAction(GitRepository repo) {
super(repo, "Start Hotfix");
}
public StartHotfixAction() {
super("Start Hotfix");
}
@Override
public void actionPerformed(AnActionEvent e) {
super.actionPerformed(e);
|
// Path: src/main/java/gitflow/ui/GitflowStartHotfixDialog.java
// public class GitflowStartHotfixDialog extends AbstractBranchStartDialog {
//
// public GitflowStartHotfixDialog(Project project, GitRepository repo) {
// super(project, repo);
// }
//
// protected boolean showBranchFromCombo(){
// return false;
// }
//
// @Override
// protected String getLabel() {
// return "hotfix";
// }
//
// @Override
// protected String getDefaultBranch() {
// return GitflowConfigUtil.getInstance(getProject(), myRepo).masterBranch;
// }
// }
//
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
// Path: src/main/java/gitflow/actions/StartHotfixAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import gitflow.ui.GitflowStartHotfixDialog;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package gitflow.actions;
public class StartHotfixAction extends AbstractStartAction {
public StartHotfixAction(GitRepository repo) {
super(repo, "Start Hotfix");
}
public StartHotfixAction() {
super("Start Hotfix");
}
@Override
public void actionPerformed(AnActionEvent e) {
super.actionPerformed(e);
|
GitflowStartHotfixDialog dialog = new GitflowStartHotfixDialog(myProject, myRepo);
|
OpherV/gitflow4idea
|
src/main/java/gitflow/actions/StartHotfixAction.java
|
// Path: src/main/java/gitflow/ui/GitflowStartHotfixDialog.java
// public class GitflowStartHotfixDialog extends AbstractBranchStartDialog {
//
// public GitflowStartHotfixDialog(Project project, GitRepository repo) {
// super(project, repo);
// }
//
// protected boolean showBranchFromCombo(){
// return false;
// }
//
// @Override
// protected String getLabel() {
// return "hotfix";
// }
//
// @Override
// protected String getDefaultBranch() {
// return GitflowConfigUtil.getInstance(getProject(), myRepo).masterBranch;
// }
// }
//
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
|
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import gitflow.ui.GitflowStartHotfixDialog;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
|
if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;
final String hotfixName = dialog.getNewBranchName();
final String baseBranchName = dialog.getBaseBranchName();
this.runAction(e.getProject(), baseBranchName, hotfixName, null);
}
public void runAction(final Project project, final String baseBranchName, final String hotfixName, @Nullable final Runnable callInAwtLater){
super.runAction(project, baseBranchName, hotfixName, callInAwtLater);
new Task.Backgroundable(myProject, "Starting hotfix " + hotfixName, false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
final GitCommandResult commandResult = createHotfixBranch(baseBranchName, hotfixName);
if (callInAwtLater != null && commandResult.success()) {
callInAwtLater.run();
}
}
}.queue();
}
private GitCommandResult createHotfixBranch(String baseBranchName, String hotfixBranchName) {
GitflowErrorsListener errorListener = new GitflowErrorsListener(myProject);
GitCommandResult result = myGitflow.startHotfix(myRepo, hotfixBranchName, baseBranchName, errorListener);
if (result.success()) {
String startedHotfixMessage = String.format("A new hotfix '%s%s' was created, based on '%s'",
branchUtil.getPrefixHotfix(), hotfixBranchName, baseBranchName);
|
// Path: src/main/java/gitflow/ui/GitflowStartHotfixDialog.java
// public class GitflowStartHotfixDialog extends AbstractBranchStartDialog {
//
// public GitflowStartHotfixDialog(Project project, GitRepository repo) {
// super(project, repo);
// }
//
// protected boolean showBranchFromCombo(){
// return false;
// }
//
// @Override
// protected String getLabel() {
// return "hotfix";
// }
//
// @Override
// protected String getDefaultBranch() {
// return GitflowConfigUtil.getInstance(getProject(), myRepo).masterBranch;
// }
// }
//
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
// Path: src/main/java/gitflow/actions/StartHotfixAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import gitflow.ui.GitflowStartHotfixDialog;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;
final String hotfixName = dialog.getNewBranchName();
final String baseBranchName = dialog.getBaseBranchName();
this.runAction(e.getProject(), baseBranchName, hotfixName, null);
}
public void runAction(final Project project, final String baseBranchName, final String hotfixName, @Nullable final Runnable callInAwtLater){
super.runAction(project, baseBranchName, hotfixName, callInAwtLater);
new Task.Backgroundable(myProject, "Starting hotfix " + hotfixName, false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
final GitCommandResult commandResult = createHotfixBranch(baseBranchName, hotfixName);
if (callInAwtLater != null && commandResult.success()) {
callInAwtLater.run();
}
}
}.queue();
}
private GitCommandResult createHotfixBranch(String baseBranchName, String hotfixBranchName) {
GitflowErrorsListener errorListener = new GitflowErrorsListener(myProject);
GitCommandResult result = myGitflow.startHotfix(myRepo, hotfixBranchName, baseBranchName, errorListener);
if (result.success()) {
String startedHotfixMessage = String.format("A new hotfix '%s%s' was created, based on '%s'",
branchUtil.getPrefixHotfix(), hotfixBranchName, baseBranchName);
|
NotifyUtil.notifySuccess(myProject, hotfixBranchName, startedHotfixMessage);
|
OpherV/gitflow4idea
|
src/main/java/gitflow/ui/GitflowOptionsForm.java
|
// Path: src/main/java/gitflow/GitflowOptionsFactory.java
// public class GitflowOptionsFactory {
// private static final GitflowOptionsFactory instance = new GitflowOptionsFactory();
// private Map<Enum<TYPE>, ArrayList<Map<String,String>>> options;
// private HashMap<String, HashMap<String,String>> optionsMap;
//
// public enum TYPE {
// FEATURE, RELEASE, HOTFIX, BUGFIX
// }
//
// //private constructor to avoid client applications to use constructor
// private GitflowOptionsFactory(){
// options = new HashMap<Enum<TYPE>, ArrayList<Map<String,String>>>();
// optionsMap = new HashMap<String, HashMap<String,String>>();
//
// addBranchType(TYPE.FEATURE);
// addOption(TYPE.FEATURE, "Fetch from Origin", "fetchFromOrigin" , "-F");
// addOption(TYPE.FEATURE, "Keep Local", "keepLocal", "--keeplocal");
// addOption(TYPE.FEATURE, "Keep Remote", "keepRemote", "--keepremote");
// addOption(TYPE.FEATURE, "Keep branch after performing finish", "keepBranch" , "-k");
// addOption(TYPE.FEATURE, "Do not fast-forward when merging, always create commit", "noFastForward" , "--no-ff");
// addOption(TYPE.FEATURE, "Push on finish feature", "pushOnFinish" , "--push");
// // addOption(TYPE.FEATURE, "Squash feature during merge", "squash" , "-S");
//
// addBranchType(TYPE.RELEASE);
// addOption(TYPE.RELEASE, "Fetch from Origin", "fetchFromOrigin" , "-F");
// addOption(TYPE.RELEASE, "Push on finish release", "pushOnFinish" , "-p");
// addOption(TYPE.RELEASE, "Keep Local", "keepLocal", "--keeplocal");
// addOption(TYPE.RELEASE, "Keep Remote", "keepRemote", "--keepremote");
// addOption(TYPE.RELEASE, "Keep branch after performing finish", "keepBranch" , "-k");
// // addOption(TYPE.RELEASE, "Squash release during merge", "squash" , "-S");
// addOption(TYPE.RELEASE, "Don't tag release", "dontTag" , "-n");
// addOption(TYPE.RELEASE, "Use custom tag commit message", "customTagCommitMessage" , null, DefaultOptions.getOption("RELEASE_customTagCommitMessage") ,"Use %name% for the branch name");
//
// addBranchType(TYPE.HOTFIX);
// addOption(TYPE.HOTFIX, "Fetch from Origin", "fetchFromOrigin" , "-F");
// addOption(TYPE.HOTFIX, "Keep branch after performing finish", "keepBranch" , "-k");
// addOption(TYPE.HOTFIX, "Push on finish Hotfix", "pushOnFinish" , "-p");
// addOption(TYPE.HOTFIX, "Don't tag Hotfix", "dontTag" , "-n");
// addOption(TYPE.HOTFIX, "Use custom hotfix commit message", "customHotfixCommitMessage" , null, DefaultOptions.getOption("HOTFIX_customHotfixCommitMessage") ,"Use %name% for the branch name");
//
// addBranchType(TYPE.BUGFIX);
// addOption(TYPE.BUGFIX, "Fetch from Origin", "fetchFromOrigin" , "-F");
// addOption(TYPE.BUGFIX, "Keep Local", "keepLocal", "--keeplocal");
// addOption(TYPE.BUGFIX, "Keep Remote", "keepRemote", "--keepremote");
// addOption(TYPE.BUGFIX, "Keep branch after performing finish", "keepBranch" , "-k");
// addOption(TYPE.BUGFIX, "Do not fast-forward when merging, always create commit", "noFastForward" , "--no-ff");
// // addOption(TYPE.BUGFIX, "Squash feature during merge", "squash" , "-S");
// }
//
// private void addBranchType(Enum<TYPE> branchType){
// options.put(branchType, new ArrayList<Map<String, String>>());
// }
//
// private void addOption(Enum<TYPE> branchType, String description, String key, @Nullable String flag){
// addOption(branchType, description, key, flag, null, null);
// }
//
// private void addOption(Enum<TYPE> branchType, String description, String key, @Nullable String flag, @Nullable String inputText, @Nullable String toolTip){
// HashMap<String, String> optionMap = new HashMap<String, String>();
// optionMap.put("description", description);
// optionMap.put("key", key);
// if (flag != null){
// optionMap.put("flag", flag);
// }
// if (inputText != null){
// optionMap.put("inputText", inputText);
// }
// if (toolTip != null){
// optionMap.put("toolTip", toolTip);
// }
//
// String optionId = getOptionId(branchType, key);
// optionMap.put("id", optionId);
// optionsMap.put(optionId, optionMap);
//
// options.get(branchType).add(optionMap);
// }
//
// public static Map<Enum<TYPE>, ArrayList<Map<String,String>>> getOptions(){
// return instance.options;
// }
//
// public static String getOptionId(Enum<TYPE> branchType, String key){
// return branchType+"_"+key;
// }
//
// public static HashMap<String,String> getOptionById(String optionId){
// return instance.optionsMap.get(optionId);
// }
// }
|
import gitflow.GitflowOptionsFactory;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
|
package gitflow.ui;
/**
* @author Andreas Vogler (Andreas.Vogler@geneon.de)
* @author Opher Vishnia (opherv@gmail.com)
*/
public class GitflowOptionsForm implements ItemListener {
private JPanel contentPane;
private JPanel releasePanel;
private JPanel featurePanel;
private JPanel hotfixPanel;
private JPanel bugfixPanel;
|
// Path: src/main/java/gitflow/GitflowOptionsFactory.java
// public class GitflowOptionsFactory {
// private static final GitflowOptionsFactory instance = new GitflowOptionsFactory();
// private Map<Enum<TYPE>, ArrayList<Map<String,String>>> options;
// private HashMap<String, HashMap<String,String>> optionsMap;
//
// public enum TYPE {
// FEATURE, RELEASE, HOTFIX, BUGFIX
// }
//
// //private constructor to avoid client applications to use constructor
// private GitflowOptionsFactory(){
// options = new HashMap<Enum<TYPE>, ArrayList<Map<String,String>>>();
// optionsMap = new HashMap<String, HashMap<String,String>>();
//
// addBranchType(TYPE.FEATURE);
// addOption(TYPE.FEATURE, "Fetch from Origin", "fetchFromOrigin" , "-F");
// addOption(TYPE.FEATURE, "Keep Local", "keepLocal", "--keeplocal");
// addOption(TYPE.FEATURE, "Keep Remote", "keepRemote", "--keepremote");
// addOption(TYPE.FEATURE, "Keep branch after performing finish", "keepBranch" , "-k");
// addOption(TYPE.FEATURE, "Do not fast-forward when merging, always create commit", "noFastForward" , "--no-ff");
// addOption(TYPE.FEATURE, "Push on finish feature", "pushOnFinish" , "--push");
// // addOption(TYPE.FEATURE, "Squash feature during merge", "squash" , "-S");
//
// addBranchType(TYPE.RELEASE);
// addOption(TYPE.RELEASE, "Fetch from Origin", "fetchFromOrigin" , "-F");
// addOption(TYPE.RELEASE, "Push on finish release", "pushOnFinish" , "-p");
// addOption(TYPE.RELEASE, "Keep Local", "keepLocal", "--keeplocal");
// addOption(TYPE.RELEASE, "Keep Remote", "keepRemote", "--keepremote");
// addOption(TYPE.RELEASE, "Keep branch after performing finish", "keepBranch" , "-k");
// // addOption(TYPE.RELEASE, "Squash release during merge", "squash" , "-S");
// addOption(TYPE.RELEASE, "Don't tag release", "dontTag" , "-n");
// addOption(TYPE.RELEASE, "Use custom tag commit message", "customTagCommitMessage" , null, DefaultOptions.getOption("RELEASE_customTagCommitMessage") ,"Use %name% for the branch name");
//
// addBranchType(TYPE.HOTFIX);
// addOption(TYPE.HOTFIX, "Fetch from Origin", "fetchFromOrigin" , "-F");
// addOption(TYPE.HOTFIX, "Keep branch after performing finish", "keepBranch" , "-k");
// addOption(TYPE.HOTFIX, "Push on finish Hotfix", "pushOnFinish" , "-p");
// addOption(TYPE.HOTFIX, "Don't tag Hotfix", "dontTag" , "-n");
// addOption(TYPE.HOTFIX, "Use custom hotfix commit message", "customHotfixCommitMessage" , null, DefaultOptions.getOption("HOTFIX_customHotfixCommitMessage") ,"Use %name% for the branch name");
//
// addBranchType(TYPE.BUGFIX);
// addOption(TYPE.BUGFIX, "Fetch from Origin", "fetchFromOrigin" , "-F");
// addOption(TYPE.BUGFIX, "Keep Local", "keepLocal", "--keeplocal");
// addOption(TYPE.BUGFIX, "Keep Remote", "keepRemote", "--keepremote");
// addOption(TYPE.BUGFIX, "Keep branch after performing finish", "keepBranch" , "-k");
// addOption(TYPE.BUGFIX, "Do not fast-forward when merging, always create commit", "noFastForward" , "--no-ff");
// // addOption(TYPE.BUGFIX, "Squash feature during merge", "squash" , "-S");
// }
//
// private void addBranchType(Enum<TYPE> branchType){
// options.put(branchType, new ArrayList<Map<String, String>>());
// }
//
// private void addOption(Enum<TYPE> branchType, String description, String key, @Nullable String flag){
// addOption(branchType, description, key, flag, null, null);
// }
//
// private void addOption(Enum<TYPE> branchType, String description, String key, @Nullable String flag, @Nullable String inputText, @Nullable String toolTip){
// HashMap<String, String> optionMap = new HashMap<String, String>();
// optionMap.put("description", description);
// optionMap.put("key", key);
// if (flag != null){
// optionMap.put("flag", flag);
// }
// if (inputText != null){
// optionMap.put("inputText", inputText);
// }
// if (toolTip != null){
// optionMap.put("toolTip", toolTip);
// }
//
// String optionId = getOptionId(branchType, key);
// optionMap.put("id", optionId);
// optionsMap.put(optionId, optionMap);
//
// options.get(branchType).add(optionMap);
// }
//
// public static Map<Enum<TYPE>, ArrayList<Map<String,String>>> getOptions(){
// return instance.options;
// }
//
// public static String getOptionId(Enum<TYPE> branchType, String key){
// return branchType+"_"+key;
// }
//
// public static HashMap<String,String> getOptionById(String optionId){
// return instance.optionsMap.get(optionId);
// }
// }
// Path: src/main/java/gitflow/ui/GitflowOptionsForm.java
import gitflow.GitflowOptionsFactory;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
package gitflow.ui;
/**
* @author Andreas Vogler (Andreas.Vogler@geneon.de)
* @author Opher Vishnia (opherv@gmail.com)
*/
public class GitflowOptionsForm implements ItemListener {
private JPanel contentPane;
private JPanel releasePanel;
private JPanel featurePanel;
private JPanel hotfixPanel;
private JPanel bugfixPanel;
|
Map<Enum<GitflowOptionsFactory.TYPE>, ArrayList<Map<String,String>>> gitflowOptions;
|
OpherV/gitflow4idea
|
src/main/java/gitflow/actions/GitflowErrorsListener.java
|
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
|
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import gitflow.ui.NotifyUtil;
|
package gitflow.actions;
public class GitflowErrorsListener extends GitflowLineHandler{
boolean hasMergeError=false;
GitflowErrorsListener(Project project){
myProject=project;
}
@Override
public void onLineAvailable(String line, Key outputType) {
if (line.contains("'flow' is not a git command")) {
|
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
// Path: src/main/java/gitflow/actions/GitflowErrorsListener.java
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import gitflow.ui.NotifyUtil;
package gitflow.actions;
public class GitflowErrorsListener extends GitflowLineHandler{
boolean hasMergeError=false;
GitflowErrorsListener(Project project){
myProject=project;
}
@Override
public void onLineAvailable(String line, Key outputType) {
if (line.contains("'flow' is not a git command")) {
|
NotifyUtil.notifyError(myProject, "Error", "Gitflow is not installed");
|
OpherV/gitflow4idea
|
src/main/java/gitflow/actions/ReInitRepoAction.java
|
// Path: src/main/java/gitflow/GitflowInitOptions.java
// public class GitflowInitOptions {
// private boolean useDefaults;
// private String productionBranch;
// private String developmentBranch;
// private String featurePrefix;
// private String releasePrefix;
// private String hotfixPrefix;
// private String bugfixPrefix;
// private String supportPrefix;
// private String versionPrefix;
//
// public boolean isUseDefaults() {
// return useDefaults;
// }
//
// public void setUseDefaults(boolean useDefaults) {
// this.useDefaults = useDefaults;
// }
//
// public String getProductionBranch() {
// return productionBranch;
// }
//
// public void setProductionBranch(String productionBranch) {
// this.productionBranch = productionBranch;
// }
//
// public String getDevelopmentBranch() {
// return developmentBranch;
// }
//
// public void setDevelopmentBranch(String developmentBranch) {
// this.developmentBranch = developmentBranch;
// }
//
// public String getFeaturePrefix() {
// return featurePrefix;
// }
//
// public void setFeaturePrefix(String featurePrefix) {
// this.featurePrefix = featurePrefix;
// }
//
// public String getReleasePrefix() {
// return releasePrefix;
// }
//
// public void setReleasePrefix(String releasePrefix) {
// this.releasePrefix = releasePrefix;
// }
//
// public String getHotfixPrefix() {
// return hotfixPrefix;
// }
//
// public void setHotfixPrefix(String hotfixPrefix) {
// this.hotfixPrefix = hotfixPrefix;
// }
//
// public String getSupportPrefix() {
// return supportPrefix;
// }
//
// public void setSupportPrefix(String supportPrefix) {
// this.supportPrefix = supportPrefix;
// }
//
// public String getBugfixPrefix() {
// return bugfixPrefix;
// }
//
// public void setBugfixPrefix(String bugfixPrefix) {
// this.bugfixPrefix = bugfixPrefix;
// }
//
// public String getVersionPrefix() {
// return versionPrefix;
// }
//
// public void setVersionPrefix(String versionPrefix) {
// this.versionPrefix = versionPrefix;
// }
// }
|
import com.intellij.openapi.actionSystem.AnActionEvent;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import gitflow.GitflowInitOptions;
import org.jetbrains.annotations.NotNull;
|
package gitflow.actions;
public class ReInitRepoAction extends InitRepoAction {
ReInitRepoAction() {
super("Re-init Repo");
}
ReInitRepoAction(GitRepository repo) {
super(repo, "Re-init Repo");
}
@Override
public void update(@NotNull AnActionEvent e) {
gitflow.GitflowBranchUtil branchUtil = gitflow.GitflowBranchUtilManager.getBranchUtil(myRepo);
// Only show when gitflow is setup
if (branchUtil !=null && branchUtil.hasGitflow()) {
e.getPresentation().setEnabledAndVisible(true);
} else {
e.getPresentation().setEnabledAndVisible(false);
}
}
@Override
protected String getSuccessMessage() {
return "Re-initialized gitflow in repo " + myRepo.getRoot().getPresentableName();
}
@Override
|
// Path: src/main/java/gitflow/GitflowInitOptions.java
// public class GitflowInitOptions {
// private boolean useDefaults;
// private String productionBranch;
// private String developmentBranch;
// private String featurePrefix;
// private String releasePrefix;
// private String hotfixPrefix;
// private String bugfixPrefix;
// private String supportPrefix;
// private String versionPrefix;
//
// public boolean isUseDefaults() {
// return useDefaults;
// }
//
// public void setUseDefaults(boolean useDefaults) {
// this.useDefaults = useDefaults;
// }
//
// public String getProductionBranch() {
// return productionBranch;
// }
//
// public void setProductionBranch(String productionBranch) {
// this.productionBranch = productionBranch;
// }
//
// public String getDevelopmentBranch() {
// return developmentBranch;
// }
//
// public void setDevelopmentBranch(String developmentBranch) {
// this.developmentBranch = developmentBranch;
// }
//
// public String getFeaturePrefix() {
// return featurePrefix;
// }
//
// public void setFeaturePrefix(String featurePrefix) {
// this.featurePrefix = featurePrefix;
// }
//
// public String getReleasePrefix() {
// return releasePrefix;
// }
//
// public void setReleasePrefix(String releasePrefix) {
// this.releasePrefix = releasePrefix;
// }
//
// public String getHotfixPrefix() {
// return hotfixPrefix;
// }
//
// public void setHotfixPrefix(String hotfixPrefix) {
// this.hotfixPrefix = hotfixPrefix;
// }
//
// public String getSupportPrefix() {
// return supportPrefix;
// }
//
// public void setSupportPrefix(String supportPrefix) {
// this.supportPrefix = supportPrefix;
// }
//
// public String getBugfixPrefix() {
// return bugfixPrefix;
// }
//
// public void setBugfixPrefix(String bugfixPrefix) {
// this.bugfixPrefix = bugfixPrefix;
// }
//
// public String getVersionPrefix() {
// return versionPrefix;
// }
//
// public void setVersionPrefix(String versionPrefix) {
// this.versionPrefix = versionPrefix;
// }
// }
// Path: src/main/java/gitflow/actions/ReInitRepoAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import gitflow.GitflowInitOptions;
import org.jetbrains.annotations.NotNull;
package gitflow.actions;
public class ReInitRepoAction extends InitRepoAction {
ReInitRepoAction() {
super("Re-init Repo");
}
ReInitRepoAction(GitRepository repo) {
super(repo, "Re-init Repo");
}
@Override
public void update(@NotNull AnActionEvent e) {
gitflow.GitflowBranchUtil branchUtil = gitflow.GitflowBranchUtilManager.getBranchUtil(myRepo);
// Only show when gitflow is setup
if (branchUtil !=null && branchUtil.hasGitflow()) {
e.getPresentation().setEnabledAndVisible(true);
} else {
e.getPresentation().setEnabledAndVisible(false);
}
}
@Override
protected String getSuccessMessage() {
return "Re-initialized gitflow in repo " + myRepo.getRoot().getPresentableName();
}
@Override
|
protected GitCommandResult executeCommand(GitflowInitOptions initOptions,
|
OpherV/gitflow4idea
|
src/main/java/gitflow/actions/StartBugfixAction.java
|
// Path: src/main/java/gitflow/ui/GitflowStartBugfixDialog.java
// public class GitflowStartBugfixDialog extends AbstractBranchStartDialog {
//
// public GitflowStartBugfixDialog(Project project, GitRepository repo) {
// super(project, repo);
// }
//
// @Override
// protected String getLabel() {
// return "bugfix";
// }
//
// @Override
// protected String getDefaultBranch() {
// return GitflowConfigUtil.getInstance(getProject(), myRepo).developBranch;
// }
// }
//
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
|
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import gitflow.ui.GitflowStartBugfixDialog;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
|
package gitflow.actions;
public class StartBugfixAction extends AbstractStartAction {
public StartBugfixAction() {
super("Start Bugfix");
}
public StartBugfixAction(GitRepository repo) {
super(repo, "Start Bugfix");
}
@Override
public void actionPerformed(AnActionEvent e) {
super.actionPerformed(e);
|
// Path: src/main/java/gitflow/ui/GitflowStartBugfixDialog.java
// public class GitflowStartBugfixDialog extends AbstractBranchStartDialog {
//
// public GitflowStartBugfixDialog(Project project, GitRepository repo) {
// super(project, repo);
// }
//
// @Override
// protected String getLabel() {
// return "bugfix";
// }
//
// @Override
// protected String getDefaultBranch() {
// return GitflowConfigUtil.getInstance(getProject(), myRepo).developBranch;
// }
// }
//
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
// Path: src/main/java/gitflow/actions/StartBugfixAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import gitflow.ui.GitflowStartBugfixDialog;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package gitflow.actions;
public class StartBugfixAction extends AbstractStartAction {
public StartBugfixAction() {
super("Start Bugfix");
}
public StartBugfixAction(GitRepository repo) {
super(repo, "Start Bugfix");
}
@Override
public void actionPerformed(AnActionEvent e) {
super.actionPerformed(e);
|
GitflowStartBugfixDialog dialog = new GitflowStartBugfixDialog(myProject, myRepo);
|
OpherV/gitflow4idea
|
src/main/java/gitflow/actions/StartBugfixAction.java
|
// Path: src/main/java/gitflow/ui/GitflowStartBugfixDialog.java
// public class GitflowStartBugfixDialog extends AbstractBranchStartDialog {
//
// public GitflowStartBugfixDialog(Project project, GitRepository repo) {
// super(project, repo);
// }
//
// @Override
// protected String getLabel() {
// return "bugfix";
// }
//
// @Override
// protected String getDefaultBranch() {
// return GitflowConfigUtil.getInstance(getProject(), myRepo).developBranch;
// }
// }
//
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
|
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import gitflow.ui.GitflowStartBugfixDialog;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
|
if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;
final String bugfixName = dialog.getNewBranchName();
final String baseBranchName = dialog.getBaseBranchName();
this.runAction(e.getProject(), baseBranchName, bugfixName, null);
}
@Override
public void runAction(final Project project, final String baseBranchName, final String bugfixName, @Nullable final Runnable callInAwtLater){
super.runAction(project, baseBranchName, bugfixName, callInAwtLater);
new Task.Backgroundable(myProject, "Starting bugfix " + bugfixName, false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
final GitCommandResult commandResult = createBugfixBranch(baseBranchName, bugfixName);
if (callInAwtLater != null && commandResult.success()) {
callInAwtLater.run();
}
}
}.queue();
}
private GitCommandResult createBugfixBranch(String baseBranchName, String bugfixName) {
GitflowErrorsListener errorListener = new GitflowErrorsListener(myProject);
GitCommandResult result = myGitflow.startBugfix(myRepo, bugfixName, baseBranchName, errorListener);
if (result.success()) {
String startedBugfixMessage = String.format("A new branch '%s%s' was created, based on '%s'", branchUtil.getPrefixBugfix(), bugfixName, baseBranchName);
|
// Path: src/main/java/gitflow/ui/GitflowStartBugfixDialog.java
// public class GitflowStartBugfixDialog extends AbstractBranchStartDialog {
//
// public GitflowStartBugfixDialog(Project project, GitRepository repo) {
// super(project, repo);
// }
//
// @Override
// protected String getLabel() {
// return "bugfix";
// }
//
// @Override
// protected String getDefaultBranch() {
// return GitflowConfigUtil.getInstance(getProject(), myRepo).developBranch;
// }
// }
//
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
// Path: src/main/java/gitflow/actions/StartBugfixAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import gitflow.ui.GitflowStartBugfixDialog;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;
final String bugfixName = dialog.getNewBranchName();
final String baseBranchName = dialog.getBaseBranchName();
this.runAction(e.getProject(), baseBranchName, bugfixName, null);
}
@Override
public void runAction(final Project project, final String baseBranchName, final String bugfixName, @Nullable final Runnable callInAwtLater){
super.runAction(project, baseBranchName, bugfixName, callInAwtLater);
new Task.Backgroundable(myProject, "Starting bugfix " + bugfixName, false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
final GitCommandResult commandResult = createBugfixBranch(baseBranchName, bugfixName);
if (callInAwtLater != null && commandResult.success()) {
callInAwtLater.run();
}
}
}.queue();
}
private GitCommandResult createBugfixBranch(String baseBranchName, String bugfixName) {
GitflowErrorsListener errorListener = new GitflowErrorsListener(myProject);
GitCommandResult result = myGitflow.startBugfix(myRepo, bugfixName, baseBranchName, errorListener);
if (result.success()) {
String startedBugfixMessage = String.format("A new branch '%s%s' was created, based on '%s'", branchUtil.getPrefixBugfix(), bugfixName, baseBranchName);
|
NotifyUtil.notifySuccess(myProject, bugfixName, startedBugfixMessage);
|
OpherV/gitflow4idea
|
src/main/java/gitflow/ui/GitflowWidget.java
|
// Path: src/main/java/gitflow/actions/GitflowPopupGroup.java
// public class GitflowPopupGroup {
//
// Project myProject;
// DefaultActionGroup actionGroup;
// GitRepositoryManager myRepositoryManager;
// List<GitRepository> gitRepositories;
//
// public GitflowPopupGroup(@NotNull Project project, boolean includeAdvanced) {
// myProject = project;
//
// //fetch all the git repositories from the project;
// myRepositoryManager = GitUtil.getRepositoryManager(project);
// gitRepositories = myRepositoryManager.getRepositories();
//
// createActionGroup(includeAdvanced);
// }
//
// /**
// * Generates the popup actions for the widget
// */
// private void createActionGroup(boolean includeAdvanced){
// actionGroup = new DefaultActionGroup(null, false);
//
//
// if (gitRepositories.size() == 1){
// ActionGroup repoActions =
// (new RepoActions(myProject, gitRepositories.get(0)))
// .getRepoActionGroup(includeAdvanced);
// actionGroup.addAll(repoActions);
// }
// else{
// Iterator gitRepositoriesIterator = gitRepositories.iterator();
// while(gitRepositoriesIterator.hasNext()){
// GitRepository repo = (GitRepository) gitRepositoriesIterator.next();
// RepoActions repoActions = new RepoActions(myProject, repo);
// actionGroup.add(repoActions);
// }
// }
// }
//
// public ActionGroup getActionGroup (){
//
// return actionGroup;
// }
// }
|
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.impl.SimpleDataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageDialogBuilder;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.StatusBarWidget;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.impl.status.EditorBasedWidget;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.popup.PopupFactoryImpl;
import com.intellij.util.Consumer;
import com.intellij.openapi.vcs.VcsRoot;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import git4idea.GitBranch;
import gitflow.*;
import gitflow.actions.GitflowPopupGroup;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import git4idea.GitUtil;
import git4idea.branch.GitBranchUtil;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryChangeListener;
import git4idea.ui.branch.GitBranchWidget;
import git4idea.GitVcs;
|
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* 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 gitflow.ui;
/**
* Status bar widget which displays actions for git flow
*
* @author Kirill Likhodedov, Opher Vishnia, Alexander von Bremen-Kühne
*/
public class GitflowWidget extends GitBranchWidget implements GitRepositoryChangeListener, StatusBarWidget.TextPresentation {
private volatile String myText = "";
private volatile String myTooltip = "";
|
// Path: src/main/java/gitflow/actions/GitflowPopupGroup.java
// public class GitflowPopupGroup {
//
// Project myProject;
// DefaultActionGroup actionGroup;
// GitRepositoryManager myRepositoryManager;
// List<GitRepository> gitRepositories;
//
// public GitflowPopupGroup(@NotNull Project project, boolean includeAdvanced) {
// myProject = project;
//
// //fetch all the git repositories from the project;
// myRepositoryManager = GitUtil.getRepositoryManager(project);
// gitRepositories = myRepositoryManager.getRepositories();
//
// createActionGroup(includeAdvanced);
// }
//
// /**
// * Generates the popup actions for the widget
// */
// private void createActionGroup(boolean includeAdvanced){
// actionGroup = new DefaultActionGroup(null, false);
//
//
// if (gitRepositories.size() == 1){
// ActionGroup repoActions =
// (new RepoActions(myProject, gitRepositories.get(0)))
// .getRepoActionGroup(includeAdvanced);
// actionGroup.addAll(repoActions);
// }
// else{
// Iterator gitRepositoriesIterator = gitRepositories.iterator();
// while(gitRepositoriesIterator.hasNext()){
// GitRepository repo = (GitRepository) gitRepositoriesIterator.next();
// RepoActions repoActions = new RepoActions(myProject, repo);
// actionGroup.add(repoActions);
// }
// }
// }
//
// public ActionGroup getActionGroup (){
//
// return actionGroup;
// }
// }
// Path: src/main/java/gitflow/ui/GitflowWidget.java
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.impl.SimpleDataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageDialogBuilder;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.StatusBarWidget;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.impl.status.EditorBasedWidget;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.popup.PopupFactoryImpl;
import com.intellij.util.Consumer;
import com.intellij.openapi.vcs.VcsRoot;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import git4idea.GitBranch;
import gitflow.*;
import gitflow.actions.GitflowPopupGroup;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import git4idea.GitUtil;
import git4idea.branch.GitBranchUtil;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryChangeListener;
import git4idea.ui.branch.GitBranchWidget;
import git4idea.GitVcs;
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* 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 gitflow.ui;
/**
* Status bar widget which displays actions for git flow
*
* @author Kirill Likhodedov, Opher Vishnia, Alexander von Bremen-Kühne
*/
public class GitflowWidget extends GitBranchWidget implements GitRepositoryChangeListener, StatusBarWidget.TextPresentation {
private volatile String myText = "";
private volatile String myTooltip = "";
|
private GitflowPopupGroup popupGroup;
|
OpherV/gitflow4idea
|
src/main/java/gitflow/GitflowConfigUtil.java
|
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
|
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import git4idea.config.GitConfigUtil;
import git4idea.repo.GitRepository;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
|
Disposer.register(project_, () -> gitflowConfigUtilMap.remove(project_));
}
return instance;
}
GitflowConfigUtil(Project project_, GitRepository repo_){
project = project_;
repo = repo_;
update();
}
public void update(){
VirtualFile root = repo.getRoot();
try{
Future<Void> f = (Future<Void>) ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
@Override
public void run() {
try{
masterBranch = GitConfigUtil.getValue(project, root, BRANCH_MASTER);
developBranch = GitConfigUtil.getValue(project, root, BRANCH_DEVELOP);
featurePrefix = GitConfigUtil.getValue(project,root,PREFIX_FEATURE);
releasePrefix = GitConfigUtil.getValue(project,root,PREFIX_RELEASE);
hotfixPrefix = GitConfigUtil.getValue(project,root,PREFIX_HOTFIX);
bugfixPrefix = GitConfigUtil.getValue(project,root,PREFIX_BUGFIX);
supportPrefix = GitConfigUtil.getValue(project,root,PREFIX_SUPPORT);
versiontagPrefix = GitConfigUtil.getValue(project,root,PREFIX_VERSIONTAG);
} catch (VcsException e) {
|
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
// Path: src/main/java/gitflow/GitflowConfigUtil.java
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import git4idea.config.GitConfigUtil;
import git4idea.repo.GitRepository;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
Disposer.register(project_, () -> gitflowConfigUtilMap.remove(project_));
}
return instance;
}
GitflowConfigUtil(Project project_, GitRepository repo_){
project = project_;
repo = repo_;
update();
}
public void update(){
VirtualFile root = repo.getRoot();
try{
Future<Void> f = (Future<Void>) ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
@Override
public void run() {
try{
masterBranch = GitConfigUtil.getValue(project, root, BRANCH_MASTER);
developBranch = GitConfigUtil.getValue(project, root, BRANCH_DEVELOP);
featurePrefix = GitConfigUtil.getValue(project,root,PREFIX_FEATURE);
releasePrefix = GitConfigUtil.getValue(project,root,PREFIX_RELEASE);
hotfixPrefix = GitConfigUtil.getValue(project,root,PREFIX_HOTFIX);
bugfixPrefix = GitConfigUtil.getValue(project,root,PREFIX_BUGFIX);
supportPrefix = GitConfigUtil.getValue(project,root,PREFIX_SUPPORT);
versiontagPrefix = GitConfigUtil.getValue(project,root,PREFIX_VERSIONTAG);
} catch (VcsException e) {
|
NotifyUtil.notifyError(project, "Config error", e);
|
OpherV/gitflow4idea
|
src/main/java/gitflow/actions/StartReleaseAction.java
|
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
|
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.ui.Messages;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import git4idea.validators.GitNewBranchNameValidator;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
|
package gitflow.actions;
public class StartReleaseAction extends AbstractStartAction {
StartReleaseAction() {
super("Start Release");
}
StartReleaseAction(GitRepository repo) {
super(repo,"Start Release");
}
@Override
public void actionPerformed(AnActionEvent e) {
super.actionPerformed(e);
final String releaseName = Messages.showInputDialog(myProject, "Enter the name of new release:", "New Release", Messages.getQuestionIcon(), "",
GitNewBranchNameValidator.newInstance(repos));
final GitflowErrorsListener errorLineHandler = new GitflowErrorsListener(myProject);
if (releaseName == null){
// user clicked cancel
}
else if (releaseName.isEmpty()){
Messages.showWarningDialog(myProject, "You must provide a name for the release", "Whoops");
}
else {
new Task.Backgroundable(myProject,"Starting release "+releaseName,false){
@Override
public void run(@NotNull ProgressIndicator indicator) {
GitCommandResult result= myGitflow.startRelease(myRepo, releaseName, errorLineHandler);
if (result.success()) {
String startedReleaseMessage = String.format("A new release '%s%s' was created, based on '%s'", branchUtil.getPrefixRelease(), releaseName, branchUtil.getBranchnameDevelop());
|
// Path: src/main/java/gitflow/ui/NotifyUtil.java
// public class NotifyUtil
// {
// private static final NotificationGroup TOOLWINDOW_NOTIFICATION = NotificationGroup.toolWindowGroup(
// "Gitflow Errors", ToolWindowId.VCS, true);
// private static final NotificationGroup STICKY_NOTIFICATION = new NotificationGroup(
// "Gitflow Errors", NotificationDisplayType.STICKY_BALLOON, true);
// private static final NotificationGroup BALLOON_NOTIFICATION = new NotificationGroup(
// "Gitflow Notifications", NotificationDisplayType.BALLOON, true);
//
// public static void notifySuccess(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, BALLOON_NOTIFICATION, project, title, message);
// }
//
// public static void notifyInfo(Project project, String title, String message) {
// notify(NotificationType.INFORMATION, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, String message) {
// notify(NotificationType.ERROR, TOOLWINDOW_NOTIFICATION, project, title, message);
// }
//
// public static void notifyError(Project project, String title, Exception exception) {
// notify(NotificationType.ERROR, STICKY_NOTIFICATION, project, title, exception.getMessage());
// }
//
// private static void notify(NotificationType type, NotificationGroup group, Project project, String title, String message) {
// group.createNotification(title, message, type, null).notify(project);
// }
// }
// Path: src/main/java/gitflow/actions/StartReleaseAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.ui.Messages;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import git4idea.validators.GitNewBranchNameValidator;
import gitflow.ui.NotifyUtil;
import org.jetbrains.annotations.NotNull;
package gitflow.actions;
public class StartReleaseAction extends AbstractStartAction {
StartReleaseAction() {
super("Start Release");
}
StartReleaseAction(GitRepository repo) {
super(repo,"Start Release");
}
@Override
public void actionPerformed(AnActionEvent e) {
super.actionPerformed(e);
final String releaseName = Messages.showInputDialog(myProject, "Enter the name of new release:", "New Release", Messages.getQuestionIcon(), "",
GitNewBranchNameValidator.newInstance(repos));
final GitflowErrorsListener errorLineHandler = new GitflowErrorsListener(myProject);
if (releaseName == null){
// user clicked cancel
}
else if (releaseName.isEmpty()){
Messages.showWarningDialog(myProject, "You must provide a name for the release", "Whoops");
}
else {
new Task.Backgroundable(myProject,"Starting release "+releaseName,false){
@Override
public void run(@NotNull ProgressIndicator indicator) {
GitCommandResult result= myGitflow.startRelease(myRepo, releaseName, errorLineHandler);
if (result.success()) {
String startedReleaseMessage = String.format("A new release '%s%s' was created, based on '%s'", branchUtil.getPrefixRelease(), releaseName, branchUtil.getBranchnameDevelop());
|
NotifyUtil.notifySuccess(myProject, releaseName, startedReleaseMessage);
|
OpherV/gitflow4idea
|
src/main/java/gitflow/ui/GitflowInitOptionsDialog.java
|
// Path: src/main/java/gitflow/GitflowInitOptions.java
// public class GitflowInitOptions {
// private boolean useDefaults;
// private String productionBranch;
// private String developmentBranch;
// private String featurePrefix;
// private String releasePrefix;
// private String hotfixPrefix;
// private String bugfixPrefix;
// private String supportPrefix;
// private String versionPrefix;
//
// public boolean isUseDefaults() {
// return useDefaults;
// }
//
// public void setUseDefaults(boolean useDefaults) {
// this.useDefaults = useDefaults;
// }
//
// public String getProductionBranch() {
// return productionBranch;
// }
//
// public void setProductionBranch(String productionBranch) {
// this.productionBranch = productionBranch;
// }
//
// public String getDevelopmentBranch() {
// return developmentBranch;
// }
//
// public void setDevelopmentBranch(String developmentBranch) {
// this.developmentBranch = developmentBranch;
// }
//
// public String getFeaturePrefix() {
// return featurePrefix;
// }
//
// public void setFeaturePrefix(String featurePrefix) {
// this.featurePrefix = featurePrefix;
// }
//
// public String getReleasePrefix() {
// return releasePrefix;
// }
//
// public void setReleasePrefix(String releasePrefix) {
// this.releasePrefix = releasePrefix;
// }
//
// public String getHotfixPrefix() {
// return hotfixPrefix;
// }
//
// public void setHotfixPrefix(String hotfixPrefix) {
// this.hotfixPrefix = hotfixPrefix;
// }
//
// public String getSupportPrefix() {
// return supportPrefix;
// }
//
// public void setSupportPrefix(String supportPrefix) {
// this.supportPrefix = supportPrefix;
// }
//
// public String getBugfixPrefix() {
// return bugfixPrefix;
// }
//
// public void setBugfixPrefix(String bugfixPrefix) {
// this.bugfixPrefix = bugfixPrefix;
// }
//
// public String getVersionPrefix() {
// return versionPrefix;
// }
//
// public void setVersionPrefix(String versionPrefix) {
// this.versionPrefix = versionPrefix;
// }
// }
|
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.CollectionComboBoxModel;
import gitflow.GitflowInitOptions;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Arrays;
import java.util.List;
|
}
private void setLocalBranchesComboBox(boolean isNonDefault){
if (isNonDefault){
developmentBranchComboBox.setModel(new CollectionComboBoxModel(localBranches));
productionBranchComboBox.setModel(new CollectionComboBoxModel(localBranches));
} else {
developmentBranchComboBox.setModel(new CollectionComboBoxModel(Arrays.asList("develop")));
productionBranchComboBox.setModel(new CollectionComboBoxModel(Arrays.asList("master")));
}
}
private void enableFields(boolean enable) {
setLocalBranchesComboBox(enable);
productionBranchComboBox.setEnabled(enable);
developmentBranchComboBox.setEnabled(enable);
featurePrefixTextField.setEnabled(enable);
releasePrefixTextField.setEnabled(enable);
hotfixPrefixTextField.setEnabled(enable);
supportPrefixTextField.setEnabled(enable);
bugfixPrefixTextField.setEnabled(enable);
versionPrefixTextField.setEnabled(enable);
}
public boolean useNonDefaultConfiguration()
{
return useNonDefaultConfigurationCheckBox.isSelected();
}
|
// Path: src/main/java/gitflow/GitflowInitOptions.java
// public class GitflowInitOptions {
// private boolean useDefaults;
// private String productionBranch;
// private String developmentBranch;
// private String featurePrefix;
// private String releasePrefix;
// private String hotfixPrefix;
// private String bugfixPrefix;
// private String supportPrefix;
// private String versionPrefix;
//
// public boolean isUseDefaults() {
// return useDefaults;
// }
//
// public void setUseDefaults(boolean useDefaults) {
// this.useDefaults = useDefaults;
// }
//
// public String getProductionBranch() {
// return productionBranch;
// }
//
// public void setProductionBranch(String productionBranch) {
// this.productionBranch = productionBranch;
// }
//
// public String getDevelopmentBranch() {
// return developmentBranch;
// }
//
// public void setDevelopmentBranch(String developmentBranch) {
// this.developmentBranch = developmentBranch;
// }
//
// public String getFeaturePrefix() {
// return featurePrefix;
// }
//
// public void setFeaturePrefix(String featurePrefix) {
// this.featurePrefix = featurePrefix;
// }
//
// public String getReleasePrefix() {
// return releasePrefix;
// }
//
// public void setReleasePrefix(String releasePrefix) {
// this.releasePrefix = releasePrefix;
// }
//
// public String getHotfixPrefix() {
// return hotfixPrefix;
// }
//
// public void setHotfixPrefix(String hotfixPrefix) {
// this.hotfixPrefix = hotfixPrefix;
// }
//
// public String getSupportPrefix() {
// return supportPrefix;
// }
//
// public void setSupportPrefix(String supportPrefix) {
// this.supportPrefix = supportPrefix;
// }
//
// public String getBugfixPrefix() {
// return bugfixPrefix;
// }
//
// public void setBugfixPrefix(String bugfixPrefix) {
// this.bugfixPrefix = bugfixPrefix;
// }
//
// public String getVersionPrefix() {
// return versionPrefix;
// }
//
// public void setVersionPrefix(String versionPrefix) {
// this.versionPrefix = versionPrefix;
// }
// }
// Path: src/main/java/gitflow/ui/GitflowInitOptionsDialog.java
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.CollectionComboBoxModel;
import gitflow.GitflowInitOptions;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Arrays;
import java.util.List;
}
private void setLocalBranchesComboBox(boolean isNonDefault){
if (isNonDefault){
developmentBranchComboBox.setModel(new CollectionComboBoxModel(localBranches));
productionBranchComboBox.setModel(new CollectionComboBoxModel(localBranches));
} else {
developmentBranchComboBox.setModel(new CollectionComboBoxModel(Arrays.asList("develop")));
productionBranchComboBox.setModel(new CollectionComboBoxModel(Arrays.asList("master")));
}
}
private void enableFields(boolean enable) {
setLocalBranchesComboBox(enable);
productionBranchComboBox.setEnabled(enable);
developmentBranchComboBox.setEnabled(enable);
featurePrefixTextField.setEnabled(enable);
releasePrefixTextField.setEnabled(enable);
hotfixPrefixTextField.setEnabled(enable);
supportPrefixTextField.setEnabled(enable);
bugfixPrefixTextField.setEnabled(enable);
versionPrefixTextField.setEnabled(enable);
}
public boolean useNonDefaultConfiguration()
{
return useNonDefaultConfigurationCheckBox.isSelected();
}
|
public GitflowInitOptions getOptions()
|
DSH105/SparkTrail
|
src/main/java/com/dsh105/sparktrail/trail/PacketEffect.java
|
// Path: src/main/java/com/dsh105/sparktrail/util/protocol/wrapper/WrapperPacketWorldParticles.java
// public class WrapperPacketWorldParticles extends Packet {
//
// public WrapperPacketWorldParticles() {
// super(PacketFactory.PacketType.WORLD_PARTICLES);
// }
//
// public void setParticleType(ParticleType value) {
// this.write("a", value.getName());
// this.setParticleSpeed(value.getDefaultSpeed());
// this.setParticleAmount(value.getDefaultAmount());
// }
//
// public ParticleType getParticleType() {
// return ParticleType.fromName(this.getParticle());
// }
//
// public void setParticle(String value) {
// this.write("a", value);
// }
//
// public String getParticle() {
// return (String) this.read("a");
// }
//
// public void setX(float value) {
// this.write("b", value);
// }
//
// public float getX() {
// return (Float) this.read("b");
// }
//
// public void setY(float value) {
// this.write("c", value);
// }
//
// public float getY() {
// return (Float) this.read("c");
// }
//
// public void setZ(float value) {
// this.write("d", value);
// }
//
// public float getZ() {
// return (Float) this.read("d");
// }
//
// public void setOffsetX(float value) {
// this.write("e", value);
// }
//
// public float getOffsetX() {
// return (Float) this.read("e");
// }
//
// public void setOffsetY(float value) {
// this.write("f", value);
// }
//
// public float getOffsetY() {
// return (Float) this.read("f");
// }
//
// public void setOffsetZ(float value) {
// this.write("g", value);
// }
//
// public float getOffsetZ() {
// return (Float) this.read("g");
// }
//
// public void setParticleSpeed(float speed) {
// this.write("h", speed);
// }
//
// public void setParticleAmount(int amount) {
// this.write("i", amount);
// }
//
// public enum ParticleType {
// SMOKE("largesmoke", 0.2f, 20),
// RED_SMOKE("reddust", 0f, 40),
// RAINBOW_SMOKE("reddust", 1f, 100),
// FIRE("flame", 0.05f, 100),
// FIREWORK_SPARK("fireworksSpark", 50F, 30),
// HEART("heart", 0f, 4),
// MAGIC_RUNES("enchantmenttable", 1f, 100),
// LAVA_SPARK("lava", 0f, 4),
// SPLASH("splash", 1f, 40),
// PORTAL("portal", 1f, 100),
//
// SMALL_EXPLOSION("largeexplode", 0.1f, 1),
// HUGE_EXPLOSION("hugeexplosion", 0.1f, 1),
// CLOUD("explode", 0.1f, 10),
// CRITICAL("crit", 0.1f, 100),
// MAGIC_CRITIAL("magicCrit", 0.1f, 100),
// ANGRY_VILLAGER("angryVillager", 0f, 20),
// SPARKLE("happyVillager", 0f, 20),
// WATER_DRIP("dripWater", 0f, 100),
// LAVA_DRIP("dripLava", 0f, 100),
// WITCH_MAGIC("witchMagic", 1f, 20),
// WITCH_MAGIC_SMALL("witchMagic", 0.1f, 5),
//
// SNOWBALL("snowballpoof", 1f, 20),
// SNOW_SHOVEL("snowshovel", 0.02f, 30),
// SLIME_SPLAT("slime", 1f, 30),
// BUBBLE("bubble", 0f, 50),
// SPELL("mobSpell", 1f, 100),
// SPELL_AMBIENT("mobSpellAmbient", 1f, 100),
// VOID("townaura", 1f, 100),
//
// BLOCK_BREAK("blockcrack", 0.1F, 100),
// BLOCK_DUST("blockdust", 0.1F, 100),;
//
// private String name;
// private float defaultSpeed;
// private int defaultAmount;
//
// ParticleType(String name, float defaultSpeed, int defaultAmount) {
// this.name = name;
// this.defaultSpeed = defaultSpeed;
// this.defaultAmount = defaultAmount;
// }
//
// public String getName() {
// return name;
// }
//
// public float getDefaultSpeed() {
// return defaultSpeed;
// }
//
// public int getDefaultAmount() {
// return defaultAmount;
// }
//
// public static ParticleType fromName(String name) {
// for (ParticleType type : ParticleType.values()) {
// if (type.getName().equalsIgnoreCase(name)) {
// return type;
// }
// }
// return null;
// }
// }
// }
|
import com.dsh105.dshutils.util.GeometryUtil;
import com.dsh105.sparktrail.util.protocol.wrapper.WrapperPacketWorldParticles;
import org.bukkit.Location;
import org.bukkit.entity.Player;
|
/*
* This file is part of SparkTrail 3.
*
* SparkTrail 3 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.
*
* SparkTrail 3 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 SparkTrail 3. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.sparktrail.trail;
public abstract class PacketEffect extends Effect {
public PacketEffect(EffectHolder effectHolder, ParticleType particleType) {
super(effectHolder, particleType);
}
|
// Path: src/main/java/com/dsh105/sparktrail/util/protocol/wrapper/WrapperPacketWorldParticles.java
// public class WrapperPacketWorldParticles extends Packet {
//
// public WrapperPacketWorldParticles() {
// super(PacketFactory.PacketType.WORLD_PARTICLES);
// }
//
// public void setParticleType(ParticleType value) {
// this.write("a", value.getName());
// this.setParticleSpeed(value.getDefaultSpeed());
// this.setParticleAmount(value.getDefaultAmount());
// }
//
// public ParticleType getParticleType() {
// return ParticleType.fromName(this.getParticle());
// }
//
// public void setParticle(String value) {
// this.write("a", value);
// }
//
// public String getParticle() {
// return (String) this.read("a");
// }
//
// public void setX(float value) {
// this.write("b", value);
// }
//
// public float getX() {
// return (Float) this.read("b");
// }
//
// public void setY(float value) {
// this.write("c", value);
// }
//
// public float getY() {
// return (Float) this.read("c");
// }
//
// public void setZ(float value) {
// this.write("d", value);
// }
//
// public float getZ() {
// return (Float) this.read("d");
// }
//
// public void setOffsetX(float value) {
// this.write("e", value);
// }
//
// public float getOffsetX() {
// return (Float) this.read("e");
// }
//
// public void setOffsetY(float value) {
// this.write("f", value);
// }
//
// public float getOffsetY() {
// return (Float) this.read("f");
// }
//
// public void setOffsetZ(float value) {
// this.write("g", value);
// }
//
// public float getOffsetZ() {
// return (Float) this.read("g");
// }
//
// public void setParticleSpeed(float speed) {
// this.write("h", speed);
// }
//
// public void setParticleAmount(int amount) {
// this.write("i", amount);
// }
//
// public enum ParticleType {
// SMOKE("largesmoke", 0.2f, 20),
// RED_SMOKE("reddust", 0f, 40),
// RAINBOW_SMOKE("reddust", 1f, 100),
// FIRE("flame", 0.05f, 100),
// FIREWORK_SPARK("fireworksSpark", 50F, 30),
// HEART("heart", 0f, 4),
// MAGIC_RUNES("enchantmenttable", 1f, 100),
// LAVA_SPARK("lava", 0f, 4),
// SPLASH("splash", 1f, 40),
// PORTAL("portal", 1f, 100),
//
// SMALL_EXPLOSION("largeexplode", 0.1f, 1),
// HUGE_EXPLOSION("hugeexplosion", 0.1f, 1),
// CLOUD("explode", 0.1f, 10),
// CRITICAL("crit", 0.1f, 100),
// MAGIC_CRITIAL("magicCrit", 0.1f, 100),
// ANGRY_VILLAGER("angryVillager", 0f, 20),
// SPARKLE("happyVillager", 0f, 20),
// WATER_DRIP("dripWater", 0f, 100),
// LAVA_DRIP("dripLava", 0f, 100),
// WITCH_MAGIC("witchMagic", 1f, 20),
// WITCH_MAGIC_SMALL("witchMagic", 0.1f, 5),
//
// SNOWBALL("snowballpoof", 1f, 20),
// SNOW_SHOVEL("snowshovel", 0.02f, 30),
// SLIME_SPLAT("slime", 1f, 30),
// BUBBLE("bubble", 0f, 50),
// SPELL("mobSpell", 1f, 100),
// SPELL_AMBIENT("mobSpellAmbient", 1f, 100),
// VOID("townaura", 1f, 100),
//
// BLOCK_BREAK("blockcrack", 0.1F, 100),
// BLOCK_DUST("blockdust", 0.1F, 100),;
//
// private String name;
// private float defaultSpeed;
// private int defaultAmount;
//
// ParticleType(String name, float defaultSpeed, int defaultAmount) {
// this.name = name;
// this.defaultSpeed = defaultSpeed;
// this.defaultAmount = defaultAmount;
// }
//
// public String getName() {
// return name;
// }
//
// public float getDefaultSpeed() {
// return defaultSpeed;
// }
//
// public int getDefaultAmount() {
// return defaultAmount;
// }
//
// public static ParticleType fromName(String name) {
// for (ParticleType type : ParticleType.values()) {
// if (type.getName().equalsIgnoreCase(name)) {
// return type;
// }
// }
// return null;
// }
// }
// }
// Path: src/main/java/com/dsh105/sparktrail/trail/PacketEffect.java
import com.dsh105.dshutils.util.GeometryUtil;
import com.dsh105.sparktrail.util.protocol.wrapper.WrapperPacketWorldParticles;
import org.bukkit.Location;
import org.bukkit.entity.Player;
/*
* This file is part of SparkTrail 3.
*
* SparkTrail 3 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.
*
* SparkTrail 3 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 SparkTrail 3. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.sparktrail.trail;
public abstract class PacketEffect extends Effect {
public PacketEffect(EffectHolder effectHolder, ParticleType particleType) {
super(effectHolder, particleType);
}
|
public WrapperPacketWorldParticles createPacket() {
|
DSH105/SparkTrail
|
src/main/java/com/dsh105/sparktrail/util/reflection/NMSClassTemplate.java
|
// Path: src/main/java/com/dsh105/sparktrail/util/ReflectionUtil.java
// public class ReflectionUtil {
//
// public static String NMS_PATH = getNMSPackageName();
// public static String CBC_PATH = getCBCPackageName();
//
// public static String getServerVersion() {
// return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
// }
//
// public static String getNMSPackageName() {
// return "net.minecraft.server." + getServerVersion();
// }
//
// public static String getCBCPackageName() {
// return "org.bukkit.craftbukkit." + getServerVersion();
// }
//
// /**
// * Class stuff
// */
//
// public static Class getClass(String name) {
// try {
// return Class.forName(name);
// } catch (ClassNotFoundException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not find class: " + name + "!");
// return null;
// }
// }
//
// public static Class getNMSClass(String className) {
// return getClass(NMS_PATH + "." + className);
// }
//
// public static Class getCBCClass(String classPath) {
// return getClass(CBC_PATH + "." + classPath);
// }
//
// /**
// * Field stuff
// */
//
// public static Field getField(Class<?> clazz, String fieldName) {
// try {
// Field field = clazz.getDeclaredField(fieldName);
//
// if (!field.isAccessible()) {
// field.setAccessible(true);
// }
//
// return field;
// } catch (NoSuchFieldException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such field: " + fieldName + "!");
// return null;
// }
// }
//
// public static <T> T getField(Class<?> clazz, String fieldName, Object instance) {
// try {
// return (T) getField(clazz, fieldName).get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access field: " + fieldName + "!");
// return null;
// }
// }
//
// public static void setField(Class<?> clazz, String fieldName, Object instance, Object value) {
// try {
// getField(clazz, fieldName).set(instance, value);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not set new field value for: " + fieldName);
// }
// }
//
// public static <T> T getField(Field field, Object instance) {
// try {
// return (T) field.get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to retrieve field: " + field.getName());
// return null;
// }
// }
//
// /**
// * Method stuff
// */
//
// public static Method getMethod(Class<?> clazz, String methodName, Class<?>... params) {
// try {
// return clazz.getDeclaredMethod(methodName, params);
// } catch (NoSuchMethodException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such method: " + methodName + "!");
// return null;
// }
// }
//
// public static <T> T invokeMethod(Method method, Object instance, Object... args) {
// try {
// return (T) method.invoke(instance, args);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access method: " + method.getName() + "!");
// return null;
// } catch (InvocationTargetException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to invoke method: " + method.getName() + "!");
// return null;
// }
// }
// }
|
import com.dsh105.dshutils.logger.ConsoleLogger;
import com.dsh105.dshutils.logger.Logger;
import com.dsh105.sparktrail.util.ReflectionUtil;
|
/*
* This file is part of SparkTrail 3.
*
* SparkTrail 3 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.
*
* SparkTrail 3 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 SparkTrail 3. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This file is part of EchoPet.
*
* EchoPet 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.
*
* EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.sparktrail.util.reflection;
public class NMSClassTemplate extends ClassTemplate {
protected NMSClassTemplate() {
setNMSClass(getClass().getSimpleName());
}
public NMSClassTemplate(String className) {
setNMSClass(className);
}
protected void setNMSClass(String name) {
|
// Path: src/main/java/com/dsh105/sparktrail/util/ReflectionUtil.java
// public class ReflectionUtil {
//
// public static String NMS_PATH = getNMSPackageName();
// public static String CBC_PATH = getCBCPackageName();
//
// public static String getServerVersion() {
// return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
// }
//
// public static String getNMSPackageName() {
// return "net.minecraft.server." + getServerVersion();
// }
//
// public static String getCBCPackageName() {
// return "org.bukkit.craftbukkit." + getServerVersion();
// }
//
// /**
// * Class stuff
// */
//
// public static Class getClass(String name) {
// try {
// return Class.forName(name);
// } catch (ClassNotFoundException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not find class: " + name + "!");
// return null;
// }
// }
//
// public static Class getNMSClass(String className) {
// return getClass(NMS_PATH + "." + className);
// }
//
// public static Class getCBCClass(String classPath) {
// return getClass(CBC_PATH + "." + classPath);
// }
//
// /**
// * Field stuff
// */
//
// public static Field getField(Class<?> clazz, String fieldName) {
// try {
// Field field = clazz.getDeclaredField(fieldName);
//
// if (!field.isAccessible()) {
// field.setAccessible(true);
// }
//
// return field;
// } catch (NoSuchFieldException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such field: " + fieldName + "!");
// return null;
// }
// }
//
// public static <T> T getField(Class<?> clazz, String fieldName, Object instance) {
// try {
// return (T) getField(clazz, fieldName).get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access field: " + fieldName + "!");
// return null;
// }
// }
//
// public static void setField(Class<?> clazz, String fieldName, Object instance, Object value) {
// try {
// getField(clazz, fieldName).set(instance, value);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not set new field value for: " + fieldName);
// }
// }
//
// public static <T> T getField(Field field, Object instance) {
// try {
// return (T) field.get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to retrieve field: " + field.getName());
// return null;
// }
// }
//
// /**
// * Method stuff
// */
//
// public static Method getMethod(Class<?> clazz, String methodName, Class<?>... params) {
// try {
// return clazz.getDeclaredMethod(methodName, params);
// } catch (NoSuchMethodException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such method: " + methodName + "!");
// return null;
// }
// }
//
// public static <T> T invokeMethod(Method method, Object instance, Object... args) {
// try {
// return (T) method.invoke(instance, args);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access method: " + method.getName() + "!");
// return null;
// } catch (InvocationTargetException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to invoke method: " + method.getName() + "!");
// return null;
// }
// }
// }
// Path: src/main/java/com/dsh105/sparktrail/util/reflection/NMSClassTemplate.java
import com.dsh105.dshutils.logger.ConsoleLogger;
import com.dsh105.dshutils.logger.Logger;
import com.dsh105.sparktrail.util.ReflectionUtil;
/*
* This file is part of SparkTrail 3.
*
* SparkTrail 3 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.
*
* SparkTrail 3 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 SparkTrail 3. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This file is part of EchoPet.
*
* EchoPet 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.
*
* EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.sparktrail.util.reflection;
public class NMSClassTemplate extends ClassTemplate {
protected NMSClassTemplate() {
setNMSClass(getClass().getSimpleName());
}
public NMSClassTemplate(String className) {
setNMSClass(className);
}
protected void setNMSClass(String name) {
|
Class clazz = ReflectionUtil.getNMSClass(name);
|
DSH105/SparkTrail
|
src/main/java/com/dsh105/sparktrail/util/protocol/Protocol.java
|
// Path: src/main/java/com/dsh105/sparktrail/util/ReflectionUtil.java
// public class ReflectionUtil {
//
// public static String NMS_PATH = getNMSPackageName();
// public static String CBC_PATH = getCBCPackageName();
//
// public static String getServerVersion() {
// return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
// }
//
// public static String getNMSPackageName() {
// return "net.minecraft.server." + getServerVersion();
// }
//
// public static String getCBCPackageName() {
// return "org.bukkit.craftbukkit." + getServerVersion();
// }
//
// /**
// * Class stuff
// */
//
// public static Class getClass(String name) {
// try {
// return Class.forName(name);
// } catch (ClassNotFoundException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not find class: " + name + "!");
// return null;
// }
// }
//
// public static Class getNMSClass(String className) {
// return getClass(NMS_PATH + "." + className);
// }
//
// public static Class getCBCClass(String classPath) {
// return getClass(CBC_PATH + "." + classPath);
// }
//
// /**
// * Field stuff
// */
//
// public static Field getField(Class<?> clazz, String fieldName) {
// try {
// Field field = clazz.getDeclaredField(fieldName);
//
// if (!field.isAccessible()) {
// field.setAccessible(true);
// }
//
// return field;
// } catch (NoSuchFieldException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such field: " + fieldName + "!");
// return null;
// }
// }
//
// public static <T> T getField(Class<?> clazz, String fieldName, Object instance) {
// try {
// return (T) getField(clazz, fieldName).get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access field: " + fieldName + "!");
// return null;
// }
// }
//
// public static void setField(Class<?> clazz, String fieldName, Object instance, Object value) {
// try {
// getField(clazz, fieldName).set(instance, value);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not set new field value for: " + fieldName);
// }
// }
//
// public static <T> T getField(Field field, Object instance) {
// try {
// return (T) field.get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to retrieve field: " + field.getName());
// return null;
// }
// }
//
// /**
// * Method stuff
// */
//
// public static Method getMethod(Class<?> clazz, String methodName, Class<?>... params) {
// try {
// return clazz.getDeclaredMethod(methodName, params);
// } catch (NoSuchMethodException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such method: " + methodName + "!");
// return null;
// }
// }
//
// public static <T> T invokeMethod(Method method, Object instance, Object... args) {
// try {
// return (T) method.invoke(instance, args);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access method: " + method.getName() + "!");
// return null;
// } catch (InvocationTargetException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to invoke method: " + method.getName() + "!");
// return null;
// }
// }
// }
|
import com.dsh105.sparktrail.util.ReflectionUtil;
|
/*
* This file is part of SparkTrail 3.
*
* SparkTrail 3 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.
*
* SparkTrail 3 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 SparkTrail 3. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This file is part of EchoPet.
*
* EchoPet 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.
*
* EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.sparktrail.util.protocol;
public enum Protocol {
HANDSHAKE,
PLAY,
STATUS,
LOGIN;
public static Protocol fromVanilla(Enum<?> enumValue) {
String name = enumValue.name();
if ("HANDSHAKING".equals(name))
return HANDSHAKE;
if ("PLAY".equals(name))
return PLAY;
if ("STATUS".equals(name))
return STATUS;
if ("LOGIN".equals(name))
return LOGIN;
return null;
}
public Object toVanilla() {
switch (this) {
case HANDSHAKE:
|
// Path: src/main/java/com/dsh105/sparktrail/util/ReflectionUtil.java
// public class ReflectionUtil {
//
// public static String NMS_PATH = getNMSPackageName();
// public static String CBC_PATH = getCBCPackageName();
//
// public static String getServerVersion() {
// return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
// }
//
// public static String getNMSPackageName() {
// return "net.minecraft.server." + getServerVersion();
// }
//
// public static String getCBCPackageName() {
// return "org.bukkit.craftbukkit." + getServerVersion();
// }
//
// /**
// * Class stuff
// */
//
// public static Class getClass(String name) {
// try {
// return Class.forName(name);
// } catch (ClassNotFoundException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not find class: " + name + "!");
// return null;
// }
// }
//
// public static Class getNMSClass(String className) {
// return getClass(NMS_PATH + "." + className);
// }
//
// public static Class getCBCClass(String classPath) {
// return getClass(CBC_PATH + "." + classPath);
// }
//
// /**
// * Field stuff
// */
//
// public static Field getField(Class<?> clazz, String fieldName) {
// try {
// Field field = clazz.getDeclaredField(fieldName);
//
// if (!field.isAccessible()) {
// field.setAccessible(true);
// }
//
// return field;
// } catch (NoSuchFieldException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such field: " + fieldName + "!");
// return null;
// }
// }
//
// public static <T> T getField(Class<?> clazz, String fieldName, Object instance) {
// try {
// return (T) getField(clazz, fieldName).get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access field: " + fieldName + "!");
// return null;
// }
// }
//
// public static void setField(Class<?> clazz, String fieldName, Object instance, Object value) {
// try {
// getField(clazz, fieldName).set(instance, value);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not set new field value for: " + fieldName);
// }
// }
//
// public static <T> T getField(Field field, Object instance) {
// try {
// return (T) field.get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to retrieve field: " + field.getName());
// return null;
// }
// }
//
// /**
// * Method stuff
// */
//
// public static Method getMethod(Class<?> clazz, String methodName, Class<?>... params) {
// try {
// return clazz.getDeclaredMethod(methodName, params);
// } catch (NoSuchMethodException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such method: " + methodName + "!");
// return null;
// }
// }
//
// public static <T> T invokeMethod(Method method, Object instance, Object... args) {
// try {
// return (T) method.invoke(instance, args);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access method: " + method.getName() + "!");
// return null;
// } catch (InvocationTargetException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to invoke method: " + method.getName() + "!");
// return null;
// }
// }
// }
// Path: src/main/java/com/dsh105/sparktrail/util/protocol/Protocol.java
import com.dsh105.sparktrail.util.ReflectionUtil;
/*
* This file is part of SparkTrail 3.
*
* SparkTrail 3 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.
*
* SparkTrail 3 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 SparkTrail 3. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This file is part of EchoPet.
*
* EchoPet 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.
*
* EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.sparktrail.util.protocol;
public enum Protocol {
HANDSHAKE,
PLAY,
STATUS,
LOGIN;
public static Protocol fromVanilla(Enum<?> enumValue) {
String name = enumValue.name();
if ("HANDSHAKING".equals(name))
return HANDSHAKE;
if ("PLAY".equals(name))
return PLAY;
if ("STATUS".equals(name))
return STATUS;
if ("LOGIN".equals(name))
return LOGIN;
return null;
}
public Object toVanilla() {
switch (this) {
case HANDSHAKE:
|
return Enum.valueOf(ReflectionUtil.getNMSClass("EnumProtocol"), "HANDSHAKING");
|
DSH105/SparkTrail
|
src/main/java/com/dsh105/sparktrail/util/protocol/wrapper/WrapperPacketWorldParticles.java
|
// Path: src/main/java/com/dsh105/sparktrail/util/protocol/Packet.java
// public class Packet {
//
// private Class packetClass;
// private Object packetHandle;
// private Protocol protocol;
// private Sender sender;
//
// public Packet(PacketFactory.PacketType packetType) {
// this(packetType.getProtocol(), packetType.getSender(), packetType.getId(), packetType.getLegacyId());
// }
//
// public Packet(Protocol protocol, Sender sender, int id, int legacyId) {
//
// if (SparkTrailPlugin.isUsingNetty) {
//
// this.packetClass = PacketUtil.getPacket(protocol, sender, id);
// try {
// this.packetHandle = this.packetClass.newInstance();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
// } else {
// FieldAccessor<Map> mapField = new SafeField<Map>(ReflectionUtil.getNMSClass("Packet"), "a");
// Map map = mapField.get(null);
// this.packetClass = (Class) MiscUtil.getKeyAtValue(map, legacyId);
// try {
// this.packetHandle = this.packetClass.newInstance();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
// }
// }
//
// public Object read(String fieldName) {
// return ReflectionUtil.getField(getPacketClass(), fieldName, this.getPacketHandle());
// }
//
// public void write(String fieldName, Object value) {
// ReflectionUtil.setField(getPacketClass(), fieldName, getPacketHandle(), value);
// }
//
// public void send(Player receiver) {
// PlayerUtil.sendPacket(receiver, getPacketHandle());
// }
//
// public Class getPacketClass() {
// return this.packetClass;
// }
//
// public Object getPacketHandle() {
// return this.packetHandle;
// }
//
// public Protocol getProtocol() {
// return this.protocol;
// }
//
// public Sender getSender() {
// return this.sender;
// }
// }
//
// Path: src/main/java/com/dsh105/sparktrail/util/protocol/PacketFactory.java
// public class PacketFactory {
//
// public enum PacketType {
// ENTITY_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0E, 0x17),
// ENTITY_LIVING_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0F, 0x18),
// ENTITY_DESTROY(Protocol.PLAY, Sender.SERVER, 0x13, 0x1D),
// ENTITY_TELEPORT(Protocol.PLAY, Sender.SERVER, 0x18, 0x22),
// ENTITY_ATTACH(Protocol.PLAY, Sender.SERVER, 0x1B, 0x27),
// ENTITY_METADATA(Protocol.PLAY, Sender.SERVER, 0x1C, 0x28),
// CHAT(Protocol.PLAY, Sender.SERVER, 0x02, 0x03),
// NAMED_ENTITY_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0C, 0x14),
// WORLD_PARTICLES(Protocol.PLAY, Sender.SERVER, 0x2A, 0x3F);
//
// private Protocol protocol;
// private Sender sender;
// private int id;
// private int legacyId;
//
// PacketType(Protocol protocol, Sender sender, int id, int legacyId) {
// this.protocol = protocol;
// this.sender = sender;
// this.id = id;
// this.legacyId = legacyId;
// }
//
// public Protocol getProtocol() {
// return protocol;
// }
//
// public Sender getSender() {
// return sender;
// }
//
// public int getId() {
// return id;
// }
//
// public int getLegacyId() {
// return this.legacyId;
// }
// }
//
// //TODO
//
// }
|
import com.dsh105.sparktrail.util.protocol.Packet;
import com.dsh105.sparktrail.util.protocol.PacketFactory;
|
/*
* This file is part of SparkTrail 3.
*
* SparkTrail 3 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.
*
* SparkTrail 3 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 SparkTrail 3. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This file is part of EchoPet.
*
* EchoPet 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.
*
* EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.sparktrail.util.protocol.wrapper;
public class WrapperPacketWorldParticles extends Packet {
public WrapperPacketWorldParticles() {
|
// Path: src/main/java/com/dsh105/sparktrail/util/protocol/Packet.java
// public class Packet {
//
// private Class packetClass;
// private Object packetHandle;
// private Protocol protocol;
// private Sender sender;
//
// public Packet(PacketFactory.PacketType packetType) {
// this(packetType.getProtocol(), packetType.getSender(), packetType.getId(), packetType.getLegacyId());
// }
//
// public Packet(Protocol protocol, Sender sender, int id, int legacyId) {
//
// if (SparkTrailPlugin.isUsingNetty) {
//
// this.packetClass = PacketUtil.getPacket(protocol, sender, id);
// try {
// this.packetHandle = this.packetClass.newInstance();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
// } else {
// FieldAccessor<Map> mapField = new SafeField<Map>(ReflectionUtil.getNMSClass("Packet"), "a");
// Map map = mapField.get(null);
// this.packetClass = (Class) MiscUtil.getKeyAtValue(map, legacyId);
// try {
// this.packetHandle = this.packetClass.newInstance();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
// }
// }
//
// public Object read(String fieldName) {
// return ReflectionUtil.getField(getPacketClass(), fieldName, this.getPacketHandle());
// }
//
// public void write(String fieldName, Object value) {
// ReflectionUtil.setField(getPacketClass(), fieldName, getPacketHandle(), value);
// }
//
// public void send(Player receiver) {
// PlayerUtil.sendPacket(receiver, getPacketHandle());
// }
//
// public Class getPacketClass() {
// return this.packetClass;
// }
//
// public Object getPacketHandle() {
// return this.packetHandle;
// }
//
// public Protocol getProtocol() {
// return this.protocol;
// }
//
// public Sender getSender() {
// return this.sender;
// }
// }
//
// Path: src/main/java/com/dsh105/sparktrail/util/protocol/PacketFactory.java
// public class PacketFactory {
//
// public enum PacketType {
// ENTITY_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0E, 0x17),
// ENTITY_LIVING_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0F, 0x18),
// ENTITY_DESTROY(Protocol.PLAY, Sender.SERVER, 0x13, 0x1D),
// ENTITY_TELEPORT(Protocol.PLAY, Sender.SERVER, 0x18, 0x22),
// ENTITY_ATTACH(Protocol.PLAY, Sender.SERVER, 0x1B, 0x27),
// ENTITY_METADATA(Protocol.PLAY, Sender.SERVER, 0x1C, 0x28),
// CHAT(Protocol.PLAY, Sender.SERVER, 0x02, 0x03),
// NAMED_ENTITY_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0C, 0x14),
// WORLD_PARTICLES(Protocol.PLAY, Sender.SERVER, 0x2A, 0x3F);
//
// private Protocol protocol;
// private Sender sender;
// private int id;
// private int legacyId;
//
// PacketType(Protocol protocol, Sender sender, int id, int legacyId) {
// this.protocol = protocol;
// this.sender = sender;
// this.id = id;
// this.legacyId = legacyId;
// }
//
// public Protocol getProtocol() {
// return protocol;
// }
//
// public Sender getSender() {
// return sender;
// }
//
// public int getId() {
// return id;
// }
//
// public int getLegacyId() {
// return this.legacyId;
// }
// }
//
// //TODO
//
// }
// Path: src/main/java/com/dsh105/sparktrail/util/protocol/wrapper/WrapperPacketWorldParticles.java
import com.dsh105.sparktrail.util.protocol.Packet;
import com.dsh105.sparktrail.util.protocol.PacketFactory;
/*
* This file is part of SparkTrail 3.
*
* SparkTrail 3 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.
*
* SparkTrail 3 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 SparkTrail 3. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This file is part of EchoPet.
*
* EchoPet 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.
*
* EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.sparktrail.util.protocol.wrapper;
public class WrapperPacketWorldParticles extends Packet {
public WrapperPacketWorldParticles() {
|
super(PacketFactory.PacketType.WORLD_PARTICLES);
|
DSH105/SparkTrail
|
src/main/java/com/dsh105/sparktrail/util/protocol/wrapper/WrapperPacketNamedEntitySpawn.java
|
// Path: src/main/java/com/dsh105/sparktrail/util/protocol/Packet.java
// public class Packet {
//
// private Class packetClass;
// private Object packetHandle;
// private Protocol protocol;
// private Sender sender;
//
// public Packet(PacketFactory.PacketType packetType) {
// this(packetType.getProtocol(), packetType.getSender(), packetType.getId(), packetType.getLegacyId());
// }
//
// public Packet(Protocol protocol, Sender sender, int id, int legacyId) {
//
// if (SparkTrailPlugin.isUsingNetty) {
//
// this.packetClass = PacketUtil.getPacket(protocol, sender, id);
// try {
// this.packetHandle = this.packetClass.newInstance();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
// } else {
// FieldAccessor<Map> mapField = new SafeField<Map>(ReflectionUtil.getNMSClass("Packet"), "a");
// Map map = mapField.get(null);
// this.packetClass = (Class) MiscUtil.getKeyAtValue(map, legacyId);
// try {
// this.packetHandle = this.packetClass.newInstance();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
// }
// }
//
// public Object read(String fieldName) {
// return ReflectionUtil.getField(getPacketClass(), fieldName, this.getPacketHandle());
// }
//
// public void write(String fieldName, Object value) {
// ReflectionUtil.setField(getPacketClass(), fieldName, getPacketHandle(), value);
// }
//
// public void send(Player receiver) {
// PlayerUtil.sendPacket(receiver, getPacketHandle());
// }
//
// public Class getPacketClass() {
// return this.packetClass;
// }
//
// public Object getPacketHandle() {
// return this.packetHandle;
// }
//
// public Protocol getProtocol() {
// return this.protocol;
// }
//
// public Sender getSender() {
// return this.sender;
// }
// }
//
// Path: src/main/java/com/dsh105/sparktrail/util/protocol/PacketFactory.java
// public class PacketFactory {
//
// public enum PacketType {
// ENTITY_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0E, 0x17),
// ENTITY_LIVING_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0F, 0x18),
// ENTITY_DESTROY(Protocol.PLAY, Sender.SERVER, 0x13, 0x1D),
// ENTITY_TELEPORT(Protocol.PLAY, Sender.SERVER, 0x18, 0x22),
// ENTITY_ATTACH(Protocol.PLAY, Sender.SERVER, 0x1B, 0x27),
// ENTITY_METADATA(Protocol.PLAY, Sender.SERVER, 0x1C, 0x28),
// CHAT(Protocol.PLAY, Sender.SERVER, 0x02, 0x03),
// NAMED_ENTITY_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0C, 0x14),
// WORLD_PARTICLES(Protocol.PLAY, Sender.SERVER, 0x2A, 0x3F);
//
// private Protocol protocol;
// private Sender sender;
// private int id;
// private int legacyId;
//
// PacketType(Protocol protocol, Sender sender, int id, int legacyId) {
// this.protocol = protocol;
// this.sender = sender;
// this.id = id;
// this.legacyId = legacyId;
// }
//
// public Protocol getProtocol() {
// return protocol;
// }
//
// public Sender getSender() {
// return sender;
// }
//
// public int getId() {
// return id;
// }
//
// public int getLegacyId() {
// return this.legacyId;
// }
// }
//
// //TODO
//
// }
|
import com.dsh105.sparktrail.util.protocol.Packet;
import com.dsh105.sparktrail.util.protocol.PacketFactory;
import net.minecraft.util.com.mojang.authlib.GameProfile;
|
/*
* This file is part of SparkTrail 3.
*
* SparkTrail 3 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.
*
* SparkTrail 3 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 SparkTrail 3. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This file is part of EchoPet.
*
* EchoPet 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.
*
* EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.sparktrail.util.protocol.wrapper;
public class WrapperPacketNamedEntitySpawn extends Packet {
public WrapperPacketNamedEntitySpawn() {
|
// Path: src/main/java/com/dsh105/sparktrail/util/protocol/Packet.java
// public class Packet {
//
// private Class packetClass;
// private Object packetHandle;
// private Protocol protocol;
// private Sender sender;
//
// public Packet(PacketFactory.PacketType packetType) {
// this(packetType.getProtocol(), packetType.getSender(), packetType.getId(), packetType.getLegacyId());
// }
//
// public Packet(Protocol protocol, Sender sender, int id, int legacyId) {
//
// if (SparkTrailPlugin.isUsingNetty) {
//
// this.packetClass = PacketUtil.getPacket(protocol, sender, id);
// try {
// this.packetHandle = this.packetClass.newInstance();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
// } else {
// FieldAccessor<Map> mapField = new SafeField<Map>(ReflectionUtil.getNMSClass("Packet"), "a");
// Map map = mapField.get(null);
// this.packetClass = (Class) MiscUtil.getKeyAtValue(map, legacyId);
// try {
// this.packetHandle = this.packetClass.newInstance();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
// }
// }
//
// public Object read(String fieldName) {
// return ReflectionUtil.getField(getPacketClass(), fieldName, this.getPacketHandle());
// }
//
// public void write(String fieldName, Object value) {
// ReflectionUtil.setField(getPacketClass(), fieldName, getPacketHandle(), value);
// }
//
// public void send(Player receiver) {
// PlayerUtil.sendPacket(receiver, getPacketHandle());
// }
//
// public Class getPacketClass() {
// return this.packetClass;
// }
//
// public Object getPacketHandle() {
// return this.packetHandle;
// }
//
// public Protocol getProtocol() {
// return this.protocol;
// }
//
// public Sender getSender() {
// return this.sender;
// }
// }
//
// Path: src/main/java/com/dsh105/sparktrail/util/protocol/PacketFactory.java
// public class PacketFactory {
//
// public enum PacketType {
// ENTITY_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0E, 0x17),
// ENTITY_LIVING_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0F, 0x18),
// ENTITY_DESTROY(Protocol.PLAY, Sender.SERVER, 0x13, 0x1D),
// ENTITY_TELEPORT(Protocol.PLAY, Sender.SERVER, 0x18, 0x22),
// ENTITY_ATTACH(Protocol.PLAY, Sender.SERVER, 0x1B, 0x27),
// ENTITY_METADATA(Protocol.PLAY, Sender.SERVER, 0x1C, 0x28),
// CHAT(Protocol.PLAY, Sender.SERVER, 0x02, 0x03),
// NAMED_ENTITY_SPAWN(Protocol.PLAY, Sender.SERVER, 0x0C, 0x14),
// WORLD_PARTICLES(Protocol.PLAY, Sender.SERVER, 0x2A, 0x3F);
//
// private Protocol protocol;
// private Sender sender;
// private int id;
// private int legacyId;
//
// PacketType(Protocol protocol, Sender sender, int id, int legacyId) {
// this.protocol = protocol;
// this.sender = sender;
// this.id = id;
// this.legacyId = legacyId;
// }
//
// public Protocol getProtocol() {
// return protocol;
// }
//
// public Sender getSender() {
// return sender;
// }
//
// public int getId() {
// return id;
// }
//
// public int getLegacyId() {
// return this.legacyId;
// }
// }
//
// //TODO
//
// }
// Path: src/main/java/com/dsh105/sparktrail/util/protocol/wrapper/WrapperPacketNamedEntitySpawn.java
import com.dsh105.sparktrail.util.protocol.Packet;
import com.dsh105.sparktrail.util.protocol.PacketFactory;
import net.minecraft.util.com.mojang.authlib.GameProfile;
/*
* This file is part of SparkTrail 3.
*
* SparkTrail 3 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.
*
* SparkTrail 3 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 SparkTrail 3. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This file is part of EchoPet.
*
* EchoPet 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.
*
* EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.sparktrail.util.protocol.wrapper;
public class WrapperPacketNamedEntitySpawn extends Packet {
public WrapperPacketNamedEntitySpawn() {
|
super(PacketFactory.PacketType.NAMED_ENTITY_SPAWN);
|
DSH105/SparkTrail
|
src/main/java/com/dsh105/sparktrail/util/reflection/ClassTemplate.java
|
// Path: src/main/java/com/dsh105/sparktrail/util/ReflectionUtil.java
// public class ReflectionUtil {
//
// public static String NMS_PATH = getNMSPackageName();
// public static String CBC_PATH = getCBCPackageName();
//
// public static String getServerVersion() {
// return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
// }
//
// public static String getNMSPackageName() {
// return "net.minecraft.server." + getServerVersion();
// }
//
// public static String getCBCPackageName() {
// return "org.bukkit.craftbukkit." + getServerVersion();
// }
//
// /**
// * Class stuff
// */
//
// public static Class getClass(String name) {
// try {
// return Class.forName(name);
// } catch (ClassNotFoundException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not find class: " + name + "!");
// return null;
// }
// }
//
// public static Class getNMSClass(String className) {
// return getClass(NMS_PATH + "." + className);
// }
//
// public static Class getCBCClass(String classPath) {
// return getClass(CBC_PATH + "." + classPath);
// }
//
// /**
// * Field stuff
// */
//
// public static Field getField(Class<?> clazz, String fieldName) {
// try {
// Field field = clazz.getDeclaredField(fieldName);
//
// if (!field.isAccessible()) {
// field.setAccessible(true);
// }
//
// return field;
// } catch (NoSuchFieldException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such field: " + fieldName + "!");
// return null;
// }
// }
//
// public static <T> T getField(Class<?> clazz, String fieldName, Object instance) {
// try {
// return (T) getField(clazz, fieldName).get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access field: " + fieldName + "!");
// return null;
// }
// }
//
// public static void setField(Class<?> clazz, String fieldName, Object instance, Object value) {
// try {
// getField(clazz, fieldName).set(instance, value);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not set new field value for: " + fieldName);
// }
// }
//
// public static <T> T getField(Field field, Object instance) {
// try {
// return (T) field.get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to retrieve field: " + field.getName());
// return null;
// }
// }
//
// /**
// * Method stuff
// */
//
// public static Method getMethod(Class<?> clazz, String methodName, Class<?>... params) {
// try {
// return clazz.getDeclaredMethod(methodName, params);
// } catch (NoSuchMethodException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such method: " + methodName + "!");
// return null;
// }
// }
//
// public static <T> T invokeMethod(Method method, Object instance, Object... args) {
// try {
// return (T) method.invoke(instance, args);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access method: " + method.getName() + "!");
// return null;
// } catch (InvocationTargetException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to invoke method: " + method.getName() + "!");
// return null;
// }
// }
// }
|
import com.dsh105.dshutils.logger.ConsoleLogger;
import com.dsh105.dshutils.logger.Logger;
import com.dsh105.sparktrail.util.ReflectionUtil;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
|
}
public T newInstance() {
if (this.type == null) {
throw new IllegalStateException("Class not set.");
}
try {
return getType().newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public Class<T> getType() {
return this.type;
}
public static ClassTemplate<?> create(Class<?> type) {
if (type == null) {
ConsoleLogger.log(Logger.LogLevel.WARNING, "Cannot create a ClassTemplate with a null type!");
return null;
}
return new ClassTemplate(type);
}
public static ClassTemplate<?> create(String className) {
|
// Path: src/main/java/com/dsh105/sparktrail/util/ReflectionUtil.java
// public class ReflectionUtil {
//
// public static String NMS_PATH = getNMSPackageName();
// public static String CBC_PATH = getCBCPackageName();
//
// public static String getServerVersion() {
// return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
// }
//
// public static String getNMSPackageName() {
// return "net.minecraft.server." + getServerVersion();
// }
//
// public static String getCBCPackageName() {
// return "org.bukkit.craftbukkit." + getServerVersion();
// }
//
// /**
// * Class stuff
// */
//
// public static Class getClass(String name) {
// try {
// return Class.forName(name);
// } catch (ClassNotFoundException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not find class: " + name + "!");
// return null;
// }
// }
//
// public static Class getNMSClass(String className) {
// return getClass(NMS_PATH + "." + className);
// }
//
// public static Class getCBCClass(String classPath) {
// return getClass(CBC_PATH + "." + classPath);
// }
//
// /**
// * Field stuff
// */
//
// public static Field getField(Class<?> clazz, String fieldName) {
// try {
// Field field = clazz.getDeclaredField(fieldName);
//
// if (!field.isAccessible()) {
// field.setAccessible(true);
// }
//
// return field;
// } catch (NoSuchFieldException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such field: " + fieldName + "!");
// return null;
// }
// }
//
// public static <T> T getField(Class<?> clazz, String fieldName, Object instance) {
// try {
// return (T) getField(clazz, fieldName).get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access field: " + fieldName + "!");
// return null;
// }
// }
//
// public static void setField(Class<?> clazz, String fieldName, Object instance, Object value) {
// try {
// getField(clazz, fieldName).set(instance, value);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not set new field value for: " + fieldName);
// }
// }
//
// public static <T> T getField(Field field, Object instance) {
// try {
// return (T) field.get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to retrieve field: " + field.getName());
// return null;
// }
// }
//
// /**
// * Method stuff
// */
//
// public static Method getMethod(Class<?> clazz, String methodName, Class<?>... params) {
// try {
// return clazz.getDeclaredMethod(methodName, params);
// } catch (NoSuchMethodException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such method: " + methodName + "!");
// return null;
// }
// }
//
// public static <T> T invokeMethod(Method method, Object instance, Object... args) {
// try {
// return (T) method.invoke(instance, args);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access method: " + method.getName() + "!");
// return null;
// } catch (InvocationTargetException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to invoke method: " + method.getName() + "!");
// return null;
// }
// }
// }
// Path: src/main/java/com/dsh105/sparktrail/util/reflection/ClassTemplate.java
import com.dsh105.dshutils.logger.ConsoleLogger;
import com.dsh105.dshutils.logger.Logger;
import com.dsh105.sparktrail.util.ReflectionUtil;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
}
public T newInstance() {
if (this.type == null) {
throw new IllegalStateException("Class not set.");
}
try {
return getType().newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public Class<T> getType() {
return this.type;
}
public static ClassTemplate<?> create(Class<?> type) {
if (type == null) {
ConsoleLogger.log(Logger.LogLevel.WARNING, "Cannot create a ClassTemplate with a null type!");
return null;
}
return new ClassTemplate(type);
}
public static ClassTemplate<?> create(String className) {
|
Class clazz = ReflectionUtil.getClass(className);
|
DSH105/SparkTrail
|
src/main/java/com/dsh105/sparktrail/util/reflection/CBClassTemplate.java
|
// Path: src/main/java/com/dsh105/sparktrail/util/ReflectionUtil.java
// public class ReflectionUtil {
//
// public static String NMS_PATH = getNMSPackageName();
// public static String CBC_PATH = getCBCPackageName();
//
// public static String getServerVersion() {
// return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
// }
//
// public static String getNMSPackageName() {
// return "net.minecraft.server." + getServerVersion();
// }
//
// public static String getCBCPackageName() {
// return "org.bukkit.craftbukkit." + getServerVersion();
// }
//
// /**
// * Class stuff
// */
//
// public static Class getClass(String name) {
// try {
// return Class.forName(name);
// } catch (ClassNotFoundException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not find class: " + name + "!");
// return null;
// }
// }
//
// public static Class getNMSClass(String className) {
// return getClass(NMS_PATH + "." + className);
// }
//
// public static Class getCBCClass(String classPath) {
// return getClass(CBC_PATH + "." + classPath);
// }
//
// /**
// * Field stuff
// */
//
// public static Field getField(Class<?> clazz, String fieldName) {
// try {
// Field field = clazz.getDeclaredField(fieldName);
//
// if (!field.isAccessible()) {
// field.setAccessible(true);
// }
//
// return field;
// } catch (NoSuchFieldException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such field: " + fieldName + "!");
// return null;
// }
// }
//
// public static <T> T getField(Class<?> clazz, String fieldName, Object instance) {
// try {
// return (T) getField(clazz, fieldName).get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access field: " + fieldName + "!");
// return null;
// }
// }
//
// public static void setField(Class<?> clazz, String fieldName, Object instance, Object value) {
// try {
// getField(clazz, fieldName).set(instance, value);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not set new field value for: " + fieldName);
// }
// }
//
// public static <T> T getField(Field field, Object instance) {
// try {
// return (T) field.get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to retrieve field: " + field.getName());
// return null;
// }
// }
//
// /**
// * Method stuff
// */
//
// public static Method getMethod(Class<?> clazz, String methodName, Class<?>... params) {
// try {
// return clazz.getDeclaredMethod(methodName, params);
// } catch (NoSuchMethodException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such method: " + methodName + "!");
// return null;
// }
// }
//
// public static <T> T invokeMethod(Method method, Object instance, Object... args) {
// try {
// return (T) method.invoke(instance, args);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access method: " + method.getName() + "!");
// return null;
// } catch (InvocationTargetException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to invoke method: " + method.getName() + "!");
// return null;
// }
// }
// }
|
import com.dsh105.dshutils.logger.ConsoleLogger;
import com.dsh105.dshutils.logger.Logger;
import com.dsh105.sparktrail.util.ReflectionUtil;
|
/*
* This file is part of SparkTrail 3.
*
* SparkTrail 3 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.
*
* SparkTrail 3 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 SparkTrail 3. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This file is part of EchoPet.
*
* EchoPet 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.
*
* EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.sparktrail.util.reflection;
public class CBClassTemplate extends ClassTemplate<Object> {
public CBClassTemplate() {
setCBClass(getClass().getSimpleName());
}
public CBClassTemplate(String className) {
setCBClass(className);
}
protected void setCBClass(String name) {
|
// Path: src/main/java/com/dsh105/sparktrail/util/ReflectionUtil.java
// public class ReflectionUtil {
//
// public static String NMS_PATH = getNMSPackageName();
// public static String CBC_PATH = getCBCPackageName();
//
// public static String getServerVersion() {
// return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
// }
//
// public static String getNMSPackageName() {
// return "net.minecraft.server." + getServerVersion();
// }
//
// public static String getCBCPackageName() {
// return "org.bukkit.craftbukkit." + getServerVersion();
// }
//
// /**
// * Class stuff
// */
//
// public static Class getClass(String name) {
// try {
// return Class.forName(name);
// } catch (ClassNotFoundException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not find class: " + name + "!");
// return null;
// }
// }
//
// public static Class getNMSClass(String className) {
// return getClass(NMS_PATH + "." + className);
// }
//
// public static Class getCBCClass(String classPath) {
// return getClass(CBC_PATH + "." + classPath);
// }
//
// /**
// * Field stuff
// */
//
// public static Field getField(Class<?> clazz, String fieldName) {
// try {
// Field field = clazz.getDeclaredField(fieldName);
//
// if (!field.isAccessible()) {
// field.setAccessible(true);
// }
//
// return field;
// } catch (NoSuchFieldException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such field: " + fieldName + "!");
// return null;
// }
// }
//
// public static <T> T getField(Class<?> clazz, String fieldName, Object instance) {
// try {
// return (T) getField(clazz, fieldName).get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access field: " + fieldName + "!");
// return null;
// }
// }
//
// public static void setField(Class<?> clazz, String fieldName, Object instance, Object value) {
// try {
// getField(clazz, fieldName).set(instance, value);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Could not set new field value for: " + fieldName);
// }
// }
//
// public static <T> T getField(Field field, Object instance) {
// try {
// return (T) field.get(instance);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to retrieve field: " + field.getName());
// return null;
// }
// }
//
// /**
// * Method stuff
// */
//
// public static Method getMethod(Class<?> clazz, String methodName, Class<?>... params) {
// try {
// return clazz.getDeclaredMethod(methodName, params);
// } catch (NoSuchMethodException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "No such method: " + methodName + "!");
// return null;
// }
// }
//
// public static <T> T invokeMethod(Method method, Object instance, Object... args) {
// try {
// return (T) method.invoke(instance, args);
// } catch (IllegalAccessException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to access method: " + method.getName() + "!");
// return null;
// } catch (InvocationTargetException e) {
// ConsoleLogger.log(Logger.LogLevel.WARNING, "Failed to invoke method: " + method.getName() + "!");
// return null;
// }
// }
// }
// Path: src/main/java/com/dsh105/sparktrail/util/reflection/CBClassTemplate.java
import com.dsh105.dshutils.logger.ConsoleLogger;
import com.dsh105.dshutils.logger.Logger;
import com.dsh105.sparktrail.util.ReflectionUtil;
/*
* This file is part of SparkTrail 3.
*
* SparkTrail 3 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.
*
* SparkTrail 3 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 SparkTrail 3. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This file is part of EchoPet.
*
* EchoPet 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.
*
* EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.sparktrail.util.reflection;
public class CBClassTemplate extends ClassTemplate<Object> {
public CBClassTemplate() {
setCBClass(getClass().getSimpleName());
}
public CBClassTemplate(String className) {
setCBClass(className);
}
protected void setCBClass(String name) {
|
Class clazz = ReflectionUtil.getCBCClass(name);
|
thecodinglive/hanbit-gradle-book-example
|
ch06/src/main/java/info/thecodinglive/service/TeamServiceImpl.java
|
// Path: ch06/src/main/java/info/thecodinglive/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch06/src/main/java/info/thecodinglive/repository/TeamDao.java
// public interface TeamDao {
//
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
|
import info.thecodinglive.model.Team;
import info.thecodinglive.repository.TeamDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
|
package info.thecodinglive.service;
@Service
@Transactional
public class TeamServiceImpl implements TeamService{
@Autowired
|
// Path: ch06/src/main/java/info/thecodinglive/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch06/src/main/java/info/thecodinglive/repository/TeamDao.java
// public interface TeamDao {
//
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
// Path: ch06/src/main/java/info/thecodinglive/service/TeamServiceImpl.java
import info.thecodinglive.model.Team;
import info.thecodinglive.repository.TeamDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
package info.thecodinglive.service;
@Service
@Transactional
public class TeamServiceImpl implements TeamService{
@Autowired
|
private TeamDao teamDao;
|
thecodinglive/hanbit-gradle-book-example
|
ch06/src/main/java/info/thecodinglive/service/TeamServiceImpl.java
|
// Path: ch06/src/main/java/info/thecodinglive/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch06/src/main/java/info/thecodinglive/repository/TeamDao.java
// public interface TeamDao {
//
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
|
import info.thecodinglive.model.Team;
import info.thecodinglive.repository.TeamDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
|
package info.thecodinglive.service;
@Service
@Transactional
public class TeamServiceImpl implements TeamService{
@Autowired
private TeamDao teamDao;
@Override
|
// Path: ch06/src/main/java/info/thecodinglive/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch06/src/main/java/info/thecodinglive/repository/TeamDao.java
// public interface TeamDao {
//
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
// Path: ch06/src/main/java/info/thecodinglive/service/TeamServiceImpl.java
import info.thecodinglive.model.Team;
import info.thecodinglive.repository.TeamDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
package info.thecodinglive.service;
@Service
@Transactional
public class TeamServiceImpl implements TeamService{
@Autowired
private TeamDao teamDao;
@Override
|
public void addTeam(Team team) {
|
thecodinglive/hanbit-gradle-book-example
|
ch06/src/main/java/info/thecodinglive/controller/TeamController.java
|
// Path: ch06/src/main/java/info/thecodinglive/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch06/src/main/java/info/thecodinglive/service/TeamService.java
// public interface TeamService {
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
|
import info.thecodinglive.model.Team;
import info.thecodinglive.service.TeamService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
|
package info.thecodinglive.controller;
@Controller
@RequestMapping(value = "/team")
public class TeamController {
@Autowired
|
// Path: ch06/src/main/java/info/thecodinglive/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch06/src/main/java/info/thecodinglive/service/TeamService.java
// public interface TeamService {
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
// Path: ch06/src/main/java/info/thecodinglive/controller/TeamController.java
import info.thecodinglive.model.Team;
import info.thecodinglive.service.TeamService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
package info.thecodinglive.controller;
@Controller
@RequestMapping(value = "/team")
public class TeamController {
@Autowired
|
private TeamService teamService;
|
thecodinglive/hanbit-gradle-book-example
|
ch06/src/main/java/info/thecodinglive/controller/TeamController.java
|
// Path: ch06/src/main/java/info/thecodinglive/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch06/src/main/java/info/thecodinglive/service/TeamService.java
// public interface TeamService {
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
|
import info.thecodinglive.model.Team;
import info.thecodinglive.service.TeamService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
|
package info.thecodinglive.controller;
@Controller
@RequestMapping(value = "/team")
public class TeamController {
@Autowired
private TeamService teamService;
@RequestMapping(value="/list")
public String listOfTeams(ModelMap model){
|
// Path: ch06/src/main/java/info/thecodinglive/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch06/src/main/java/info/thecodinglive/service/TeamService.java
// public interface TeamService {
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
// Path: ch06/src/main/java/info/thecodinglive/controller/TeamController.java
import info.thecodinglive.model.Team;
import info.thecodinglive.service.TeamService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
package info.thecodinglive.controller;
@Controller
@RequestMapping(value = "/team")
public class TeamController {
@Autowired
private TeamService teamService;
@RequestMapping(value="/list")
public String listOfTeams(ModelMap model){
|
model.addAttribute("teams", (List<Team>)teamService.getTeams());
|
thecodinglive/hanbit-gradle-book-example
|
ch07/springtobemulti/WebAppSub/src/main/java/info/thecodinglive/web/controller/TeamController.java
|
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/service/TeamService.java
// public interface TeamService {
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
|
import info.thecodinglive.hiber.model.Team;
import info.thecodinglive.hiber.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
|
package info.thecodinglive.web.controller;
@Controller
@RequestMapping(value = "/team")
public class TeamController {
@Autowired
|
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/service/TeamService.java
// public interface TeamService {
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
// Path: ch07/springtobemulti/WebAppSub/src/main/java/info/thecodinglive/web/controller/TeamController.java
import info.thecodinglive.hiber.model.Team;
import info.thecodinglive.hiber.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
package info.thecodinglive.web.controller;
@Controller
@RequestMapping(value = "/team")
public class TeamController {
@Autowired
|
private TeamService teamService;
|
thecodinglive/hanbit-gradle-book-example
|
ch07/springtobemulti/WebAppSub/src/main/java/info/thecodinglive/web/controller/TeamController.java
|
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/service/TeamService.java
// public interface TeamService {
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
|
import info.thecodinglive.hiber.model.Team;
import info.thecodinglive.hiber.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
|
package info.thecodinglive.web.controller;
@Controller
@RequestMapping(value = "/team")
public class TeamController {
@Autowired
private TeamService teamService;
@RequestMapping(value = "/list")
public String listOfTeams(ModelMap model) {
model.addAttribute("teams", teamService.getTeams());
return "teamlist";
}
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String addTeamPage(ModelMap model) {
|
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/service/TeamService.java
// public interface TeamService {
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
// Path: ch07/springtobemulti/WebAppSub/src/main/java/info/thecodinglive/web/controller/TeamController.java
import info.thecodinglive.hiber.model.Team;
import info.thecodinglive.hiber.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
package info.thecodinglive.web.controller;
@Controller
@RequestMapping(value = "/team")
public class TeamController {
@Autowired
private TeamService teamService;
@RequestMapping(value = "/list")
public String listOfTeams(ModelMap model) {
model.addAttribute("teams", teamService.getTeams());
return "teamlist";
}
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String addTeamPage(ModelMap model) {
|
model.addAttribute("team", new Team());
|
thecodinglive/hanbit-gradle-book-example
|
ch06/src/main/java/info/thecodinglive/repository/TeamDaoImpl.java
|
// Path: ch06/src/main/java/info/thecodinglive/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
|
import info.thecodinglive.model.Team;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
|
package info.thecodinglive.repository;
@Repository
public class TeamDaoImpl implements TeamDao{
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
|
// Path: ch06/src/main/java/info/thecodinglive/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
// Path: ch06/src/main/java/info/thecodinglive/repository/TeamDaoImpl.java
import info.thecodinglive.model.Team;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
package info.thecodinglive.repository;
@Repository
public class TeamDaoImpl implements TeamDao{
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
|
public void addTeam(Team team) {
|
thecodinglive/hanbit-gradle-book-example
|
ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/repository/TeamDaoImpl.java
|
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
|
import info.thecodinglive.hiber.model.Team;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
|
package info.thecodinglive.hiber.repository;
@Repository
public class TeamDaoImpl implements TeamDao{
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
|
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/repository/TeamDaoImpl.java
import info.thecodinglive.hiber.model.Team;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
package info.thecodinglive.hiber.repository;
@Repository
public class TeamDaoImpl implements TeamDao{
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
|
public void addTeam(Team team) {
|
thecodinglive/hanbit-gradle-book-example
|
ch06/src/main/java/info/thecodinglive/restController/TeamRestController.java
|
// Path: ch06/src/main/java/info/thecodinglive/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch06/src/main/java/info/thecodinglive/service/TeamService.java
// public interface TeamService {
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
|
import info.thecodinglive.model.Team;
import info.thecodinglive.service.TeamService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
|
package info.thecodinglive.restController;
@Controller
@RequestMapping(value="/api")
public class TeamRestController {
@Autowired
|
// Path: ch06/src/main/java/info/thecodinglive/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch06/src/main/java/info/thecodinglive/service/TeamService.java
// public interface TeamService {
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
// Path: ch06/src/main/java/info/thecodinglive/restController/TeamRestController.java
import info.thecodinglive.model.Team;
import info.thecodinglive.service.TeamService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
package info.thecodinglive.restController;
@Controller
@RequestMapping(value="/api")
public class TeamRestController {
@Autowired
|
TeamService teamService;
|
thecodinglive/hanbit-gradle-book-example
|
ch06/src/main/java/info/thecodinglive/restController/TeamRestController.java
|
// Path: ch06/src/main/java/info/thecodinglive/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch06/src/main/java/info/thecodinglive/service/TeamService.java
// public interface TeamService {
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
|
import info.thecodinglive.model.Team;
import info.thecodinglive.service.TeamService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
|
package info.thecodinglive.restController;
@Controller
@RequestMapping(value="/api")
public class TeamRestController {
@Autowired
TeamService teamService;
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
|
// Path: ch06/src/main/java/info/thecodinglive/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch06/src/main/java/info/thecodinglive/service/TeamService.java
// public interface TeamService {
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
// Path: ch06/src/main/java/info/thecodinglive/restController/TeamRestController.java
import info.thecodinglive.model.Team;
import info.thecodinglive.service.TeamService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
package info.thecodinglive.restController;
@Controller
@RequestMapping(value="/api")
public class TeamRestController {
@Autowired
TeamService teamService;
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
|
public List<Team> getTeams(){
|
thecodinglive/hanbit-gradle-book-example
|
ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/service/TeamServiceImpl.java
|
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/repository/TeamDao.java
// public interface TeamDao {
//
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
|
import info.thecodinglive.hiber.model.Team;
import info.thecodinglive.hiber.repository.TeamDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
|
package info.thecodinglive.hiber.service;
@Service
@Transactional
public class TeamServiceImpl implements TeamService{
@Autowired
|
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/repository/TeamDao.java
// public interface TeamDao {
//
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/service/TeamServiceImpl.java
import info.thecodinglive.hiber.model.Team;
import info.thecodinglive.hiber.repository.TeamDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
package info.thecodinglive.hiber.service;
@Service
@Transactional
public class TeamServiceImpl implements TeamService{
@Autowired
|
private TeamDao teamDao;
|
thecodinglive/hanbit-gradle-book-example
|
ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/service/TeamServiceImpl.java
|
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/repository/TeamDao.java
// public interface TeamDao {
//
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
|
import info.thecodinglive.hiber.model.Team;
import info.thecodinglive.hiber.repository.TeamDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
|
package info.thecodinglive.hiber.service;
@Service
@Transactional
public class TeamServiceImpl implements TeamService{
@Autowired
private TeamDao teamDao;
@Override
|
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/model/Team.java
// @Entity
// @Table(name="teams")
// public class Team {
// @Id
// @GeneratedValue
// private Integer id;
//
// private String teamName;
//
// private Integer rating;
//
// public String getTeamName() {
// return teamName;
// }
// public void setTeamName(String teamName) {
// this.teamName = teamName;
// }
//
//
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Integer getRating() {
// return rating;
// }
// public void setRating(Integer rating) {
// this.rating = rating;
// }
// }
//
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/repository/TeamDao.java
// public interface TeamDao {
//
// public void addTeam(Team team);
// public void updateTeam(Team team);
// public Team getTeam(int id);
// public void deleteTeam(int id);
// public List<Team> getTeams();
// }
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/service/TeamServiceImpl.java
import info.thecodinglive.hiber.model.Team;
import info.thecodinglive.hiber.repository.TeamDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
package info.thecodinglive.hiber.service;
@Service
@Transactional
public class TeamServiceImpl implements TeamService{
@Autowired
private TeamDao teamDao;
@Override
|
public void addTeam(Team team) {
|
thecodinglive/hanbit-gradle-book-example
|
ch07/springtobemulti/WebAppSub/src/main/java/info/thecodinglive/web/config/WebInitializer.java
|
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/config/DbConfig.java
// @Configuration
// @EnableTransactionManagement
// @ComponentScan(basePackages ={"info.thecodinglive.hiber"})
// @PropertySource("classpath:application.properties")
// public class DbConfig{
// private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
// private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
// private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
// private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
//
// private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
// private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
// private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
// private static final String PROPERTY_NAME_HIBERNATE_hbm2ddl = "hibernate.hbm2ddl.auto";
//
// private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
//
// @Resource
// private Environment env;
//
// @Bean
// public DataSource dataSource() {
// DriverManagerDataSource dataSource = new DriverManagerDataSource();
//
// dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
// dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
// dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
// dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
//
// return dataSource;
// }
//
//
// @Bean
// public LocalSessionFactoryBean sessionFactory() {
// LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
// sessionFactoryBean.setDataSource(dataSource());
// sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
// sessionFactoryBean.setHibernateProperties(hibProperties());
//
//
// return sessionFactoryBean;
// }
//
// private Properties hibProperties() {
// Properties properties = new Properties();
// properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
// properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
// properties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
// properties.put(PROPERTY_NAME_HIBERNATE_hbm2ddl, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_hbm2ddl));
//
// return properties;
// }
//
// @Bean
// public HibernateTransactionManager transactionManager() {
// HibernateTransactionManager transactionManager = new HibernateTransactionManager();
// transactionManager.setSessionFactory(sessionFactory().getObject());
// return transactionManager;
// }
// }
|
import info.thecodinglive.hiber.config.DbConfig;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
|
package info.thecodinglive.web.config;
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
@Override
protected Class<?>[] getRootConfigClasses() {
|
// Path: ch07/springtobemulti/HibernateSub/src/main/java/info/thecodinglive/hiber/config/DbConfig.java
// @Configuration
// @EnableTransactionManagement
// @ComponentScan(basePackages ={"info.thecodinglive.hiber"})
// @PropertySource("classpath:application.properties")
// public class DbConfig{
// private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
// private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
// private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
// private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
//
// private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
// private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
// private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
// private static final String PROPERTY_NAME_HIBERNATE_hbm2ddl = "hibernate.hbm2ddl.auto";
//
// private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
//
// @Resource
// private Environment env;
//
// @Bean
// public DataSource dataSource() {
// DriverManagerDataSource dataSource = new DriverManagerDataSource();
//
// dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
// dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
// dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
// dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
//
// return dataSource;
// }
//
//
// @Bean
// public LocalSessionFactoryBean sessionFactory() {
// LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
// sessionFactoryBean.setDataSource(dataSource());
// sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
// sessionFactoryBean.setHibernateProperties(hibProperties());
//
//
// return sessionFactoryBean;
// }
//
// private Properties hibProperties() {
// Properties properties = new Properties();
// properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
// properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
// properties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
// properties.put(PROPERTY_NAME_HIBERNATE_hbm2ddl, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_hbm2ddl));
//
// return properties;
// }
//
// @Bean
// public HibernateTransactionManager transactionManager() {
// HibernateTransactionManager transactionManager = new HibernateTransactionManager();
// transactionManager.setSessionFactory(sessionFactory().getObject());
// return transactionManager;
// }
// }
// Path: ch07/springtobemulti/WebAppSub/src/main/java/info/thecodinglive/web/config/WebInitializer.java
import info.thecodinglive.hiber.config.DbConfig;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
package info.thecodinglive.web.config;
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
@Override
protected Class<?>[] getRootConfigClasses() {
|
return new Class[]{DbConfig.class};
|
RandoApp/Rando-android
|
src/main/java/com/github/randoapp/upload/UploadJobScheduler.java
|
// Path: src/main/java/com/github/randoapp/log/Log.java
// public class Log {
//
// public static void i(Class clazz, String... msgs) {
// android.util.Log.i(clazz.getName(), concatenate(msgs));
// }
//
// public static void d(Class clazz, String... msgs) {
// android.util.Log.d(clazz.getName(), concatenate(msgs));
// }
//
// public static void w(Class clazz, String... msgs) {
// android.util.Log.w(clazz.getName(), concatenate(msgs));
// }
//
// public static void e(Class clazz, String... msgs) {
// android.util.Log.e(clazz.getName(), concatenate(msgs));
// }
//
// public static void e(Class clazz, String comment, Throwable throwable) {
// android.util.Log.e(clazz.getName(), comment + " error:", throwable);
// }
//
// public static void v(Class clazz, String... msgs) {
// android.util.Log.v(clazz.getName(), concatenate(msgs));
// }
//
// private static String concatenate(String[] msgs) {
// if (msgs == null) {
// return "";
// }
//
// StringBuilder sb = new StringBuilder();
// for (String msg : msgs) {
// sb.append(msg).append(" ");
// }
// return sb.toString();
// }
//
// }
|
import java.util.concurrent.TimeUnit;
import android.content.Context;
import com.evernote.android.job.JobRequest;
import com.github.randoapp.log.Log;
|
package com.github.randoapp.upload;
public class UploadJobScheduler {
public static void scheduleUpload(Context context) {
|
// Path: src/main/java/com/github/randoapp/log/Log.java
// public class Log {
//
// public static void i(Class clazz, String... msgs) {
// android.util.Log.i(clazz.getName(), concatenate(msgs));
// }
//
// public static void d(Class clazz, String... msgs) {
// android.util.Log.d(clazz.getName(), concatenate(msgs));
// }
//
// public static void w(Class clazz, String... msgs) {
// android.util.Log.w(clazz.getName(), concatenate(msgs));
// }
//
// public static void e(Class clazz, String... msgs) {
// android.util.Log.e(clazz.getName(), concatenate(msgs));
// }
//
// public static void e(Class clazz, String comment, Throwable throwable) {
// android.util.Log.e(clazz.getName(), comment + " error:", throwable);
// }
//
// public static void v(Class clazz, String... msgs) {
// android.util.Log.v(clazz.getName(), concatenate(msgs));
// }
//
// private static String concatenate(String[] msgs) {
// if (msgs == null) {
// return "";
// }
//
// StringBuilder sb = new StringBuilder();
// for (String msg : msgs) {
// sb.append(msg).append(" ");
// }
// return sb.toString();
// }
//
// }
// Path: src/main/java/com/github/randoapp/upload/UploadJobScheduler.java
import java.util.concurrent.TimeUnit;
import android.content.Context;
import com.evernote.android.job.JobRequest;
import com.github.randoapp.log.Log;
package com.github.randoapp.upload;
public class UploadJobScheduler {
public static void scheduleUpload(Context context) {
|
Log.d(UploadJobScheduler.class, "Schedule Job to upload");
|
RandoApp/Rando-android
|
src/main/java/com/github/randoapp/util/GooglePlayServicesUtil.java
|
// Path: src/main/java/com/github/randoapp/log/Log.java
// public class Log {
//
// public static void i(Class clazz, String... msgs) {
// android.util.Log.i(clazz.getName(), concatenate(msgs));
// }
//
// public static void d(Class clazz, String... msgs) {
// android.util.Log.d(clazz.getName(), concatenate(msgs));
// }
//
// public static void w(Class clazz, String... msgs) {
// android.util.Log.w(clazz.getName(), concatenate(msgs));
// }
//
// public static void e(Class clazz, String... msgs) {
// android.util.Log.e(clazz.getName(), concatenate(msgs));
// }
//
// public static void e(Class clazz, String comment, Throwable throwable) {
// android.util.Log.e(clazz.getName(), comment + " error:", throwable);
// }
//
// public static void v(Class clazz, String... msgs) {
// android.util.Log.v(clazz.getName(), concatenate(msgs));
// }
//
// private static String concatenate(String[] msgs) {
// if (msgs == null) {
// return "";
// }
//
// StringBuilder sb = new StringBuilder();
// for (String msg : msgs) {
// sb.append(msg).append(" ");
// }
// return sb.toString();
// }
//
// }
|
import android.content.pm.PackageManager;
import com.github.randoapp.log.Log;
import com.google.android.gms.common.GoogleApiAvailability;
|
package com.github.randoapp.util;
public class GooglePlayServicesUtil {
private static int MIN_GPS_VERISON = 5000000;
public static boolean isGPSVersionLowerThanRequired(PackageManager packageManager){
int versionCode = 0;
try {
versionCode = packageManager.getPackageInfo(GoogleApiAvailability.GOOGLE_PLAY_SERVICES_PACKAGE, 0 ).versionCode;
} catch (PackageManager.NameNotFoundException e) {
|
// Path: src/main/java/com/github/randoapp/log/Log.java
// public class Log {
//
// public static void i(Class clazz, String... msgs) {
// android.util.Log.i(clazz.getName(), concatenate(msgs));
// }
//
// public static void d(Class clazz, String... msgs) {
// android.util.Log.d(clazz.getName(), concatenate(msgs));
// }
//
// public static void w(Class clazz, String... msgs) {
// android.util.Log.w(clazz.getName(), concatenate(msgs));
// }
//
// public static void e(Class clazz, String... msgs) {
// android.util.Log.e(clazz.getName(), concatenate(msgs));
// }
//
// public static void e(Class clazz, String comment, Throwable throwable) {
// android.util.Log.e(clazz.getName(), comment + " error:", throwable);
// }
//
// public static void v(Class clazz, String... msgs) {
// android.util.Log.v(clazz.getName(), concatenate(msgs));
// }
//
// private static String concatenate(String[] msgs) {
// if (msgs == null) {
// return "";
// }
//
// StringBuilder sb = new StringBuilder();
// for (String msg : msgs) {
// sb.append(msg).append(" ");
// }
// return sb.toString();
// }
//
// }
// Path: src/main/java/com/github/randoapp/util/GooglePlayServicesUtil.java
import android.content.pm.PackageManager;
import com.github.randoapp.log.Log;
import com.google.android.gms.common.GoogleApiAvailability;
package com.github.randoapp.util;
public class GooglePlayServicesUtil {
private static int MIN_GPS_VERISON = 5000000;
public static boolean isGPSVersionLowerThanRequired(PackageManager packageManager){
int versionCode = 0;
try {
versionCode = packageManager.getPackageInfo(GoogleApiAvailability.GOOGLE_PLAY_SERVICES_PACKAGE, 0 ).versionCode;
} catch (PackageManager.NameNotFoundException e) {
|
Log.d(GooglePlayServicesUtil.class, "Google Play Services not installed at all");
|
RandoApp/Rando-android
|
src/main/java/com/github/randoapp/cache/LruMemCache.java
|
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final int NUMBER_OF_IMAGES_FOR_CACHING = NUMBER_OF_IMAGES_IN_ONE_SET * 2; //2 visible image sets per screen
|
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader;
import static com.github.randoapp.Constants.NUMBER_OF_IMAGES_FOR_CACHING;
|
package com.github.randoapp.cache;
public class LruMemCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
|
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final int NUMBER_OF_IMAGES_FOR_CACHING = NUMBER_OF_IMAGES_IN_ONE_SET * 2; //2 visible image sets per screen
// Path: src/main/java/com/github/randoapp/cache/LruMemCache.java
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader;
import static com.github.randoapp.Constants.NUMBER_OF_IMAGES_FOR_CACHING;
package com.github.randoapp.cache;
public class LruMemCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
|
final int cacheSize = maxMemory / NUMBER_OF_IMAGES_FOR_CACHING;
|
RandoApp/Rando-android
|
src/main/java/com/github/randoapp/preferences/Preferences.java
|
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java
// public class Statistics implements Serializable {
// private int likes;
// private int dislikes;
//
// public static Statistics of(int likes, int dislikes) {
// Statistics statistics = new Statistics();
// statistics.likes = likes;
// statistics.dislikes = dislikes;
// return statistics;
// }
//
// public static Statistics from(JSONObject obj) {
// Statistics statistics = new Statistics();
// try {
// statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0;
// statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return statistics;
// }
//
// public int getLikes() {
// return likes;
// }
//
// public void setLikes(int likes) {
// this.likes = likes;
// }
//
// public int getDislikes() {
// return dislikes;
// }
//
// public void setDislikes(int dislikes) {
// this.dislikes = dislikes;
// }
// }
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String ACCOUNT = "account";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String AUTH_TOKEN = "auth.token";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String BAN_RESET_AT = "main.ban.reset.at";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FACING_STRING = "camera.facing.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FLASH_MODE = "camera.flash.mode";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_GRID_STRING = "camera.grid.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LATITUDE_PARAM = "latitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LOCATION = "location";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LONGITUDE_PARAM = "longitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String PREFERENCES_FILE_NAME = "rando.prefs";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_DISLIKES = "dislikes";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_LIKES = "likes";
|
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import com.github.randoapp.db.model.Statistics;
import com.otaliastudios.cameraview.Facing;
import com.otaliastudios.cameraview.Flash;
import com.otaliastudios.cameraview.Grid;
import static com.github.randoapp.Constants.ACCOUNT;
import static com.github.randoapp.Constants.AUTH_TOKEN;
import static com.github.randoapp.Constants.BAN_RESET_AT;
import static com.github.randoapp.Constants.CAMERA_FACING_STRING;
import static com.github.randoapp.Constants.CAMERA_FLASH_MODE;
import static com.github.randoapp.Constants.CAMERA_GRID_STRING;
import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID;
import static com.github.randoapp.Constants.LATITUDE_PARAM;
import static com.github.randoapp.Constants.LOCATION;
import static com.github.randoapp.Constants.LONGITUDE_PARAM;
import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME;
import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN;
import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES;
import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
|
package com.github.randoapp.preferences;
public class Preferences {
public static final String AUTH_TOKEN_DEFAULT_VALUE = "";
public static final String FIREBASE_INSTANCE_ID_DEFAULT_VALUE = "";
public static final String ACCOUNT_DEFAULT_VALUE = "";
public static final int STATISTICS_DEFAULT_VALUE = 0;
private static Object monitor = new Object();
public static String getAuthToken(Context context) {
synchronized (monitor) {
|
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java
// public class Statistics implements Serializable {
// private int likes;
// private int dislikes;
//
// public static Statistics of(int likes, int dislikes) {
// Statistics statistics = new Statistics();
// statistics.likes = likes;
// statistics.dislikes = dislikes;
// return statistics;
// }
//
// public static Statistics from(JSONObject obj) {
// Statistics statistics = new Statistics();
// try {
// statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0;
// statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return statistics;
// }
//
// public int getLikes() {
// return likes;
// }
//
// public void setLikes(int likes) {
// this.likes = likes;
// }
//
// public int getDislikes() {
// return dislikes;
// }
//
// public void setDislikes(int dislikes) {
// this.dislikes = dislikes;
// }
// }
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String ACCOUNT = "account";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String AUTH_TOKEN = "auth.token";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String BAN_RESET_AT = "main.ban.reset.at";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FACING_STRING = "camera.facing.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FLASH_MODE = "camera.flash.mode";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_GRID_STRING = "camera.grid.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LATITUDE_PARAM = "latitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LOCATION = "location";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LONGITUDE_PARAM = "longitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String PREFERENCES_FILE_NAME = "rando.prefs";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_DISLIKES = "dislikes";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_LIKES = "likes";
// Path: src/main/java/com/github/randoapp/preferences/Preferences.java
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import com.github.randoapp.db.model.Statistics;
import com.otaliastudios.cameraview.Facing;
import com.otaliastudios.cameraview.Flash;
import com.otaliastudios.cameraview.Grid;
import static com.github.randoapp.Constants.ACCOUNT;
import static com.github.randoapp.Constants.AUTH_TOKEN;
import static com.github.randoapp.Constants.BAN_RESET_AT;
import static com.github.randoapp.Constants.CAMERA_FACING_STRING;
import static com.github.randoapp.Constants.CAMERA_FLASH_MODE;
import static com.github.randoapp.Constants.CAMERA_GRID_STRING;
import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID;
import static com.github.randoapp.Constants.LATITUDE_PARAM;
import static com.github.randoapp.Constants.LOCATION;
import static com.github.randoapp.Constants.LONGITUDE_PARAM;
import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME;
import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN;
import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES;
import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
package com.github.randoapp.preferences;
public class Preferences {
public static final String AUTH_TOKEN_DEFAULT_VALUE = "";
public static final String FIREBASE_INSTANCE_ID_DEFAULT_VALUE = "";
public static final String ACCOUNT_DEFAULT_VALUE = "";
public static final int STATISTICS_DEFAULT_VALUE = 0;
private static Object monitor = new Object();
public static String getAuthToken(Context context) {
synchronized (monitor) {
|
return getSharedPreferences(context).getString(AUTH_TOKEN, AUTH_TOKEN_DEFAULT_VALUE);
|
RandoApp/Rando-android
|
src/main/java/com/github/randoapp/preferences/Preferences.java
|
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java
// public class Statistics implements Serializable {
// private int likes;
// private int dislikes;
//
// public static Statistics of(int likes, int dislikes) {
// Statistics statistics = new Statistics();
// statistics.likes = likes;
// statistics.dislikes = dislikes;
// return statistics;
// }
//
// public static Statistics from(JSONObject obj) {
// Statistics statistics = new Statistics();
// try {
// statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0;
// statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return statistics;
// }
//
// public int getLikes() {
// return likes;
// }
//
// public void setLikes(int likes) {
// this.likes = likes;
// }
//
// public int getDislikes() {
// return dislikes;
// }
//
// public void setDislikes(int dislikes) {
// this.dislikes = dislikes;
// }
// }
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String ACCOUNT = "account";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String AUTH_TOKEN = "auth.token";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String BAN_RESET_AT = "main.ban.reset.at";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FACING_STRING = "camera.facing.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FLASH_MODE = "camera.flash.mode";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_GRID_STRING = "camera.grid.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LATITUDE_PARAM = "latitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LOCATION = "location";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LONGITUDE_PARAM = "longitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String PREFERENCES_FILE_NAME = "rando.prefs";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_DISLIKES = "dislikes";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_LIKES = "likes";
|
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import com.github.randoapp.db.model.Statistics;
import com.otaliastudios.cameraview.Facing;
import com.otaliastudios.cameraview.Flash;
import com.otaliastudios.cameraview.Grid;
import static com.github.randoapp.Constants.ACCOUNT;
import static com.github.randoapp.Constants.AUTH_TOKEN;
import static com.github.randoapp.Constants.BAN_RESET_AT;
import static com.github.randoapp.Constants.CAMERA_FACING_STRING;
import static com.github.randoapp.Constants.CAMERA_FLASH_MODE;
import static com.github.randoapp.Constants.CAMERA_GRID_STRING;
import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID;
import static com.github.randoapp.Constants.LATITUDE_PARAM;
import static com.github.randoapp.Constants.LOCATION;
import static com.github.randoapp.Constants.LONGITUDE_PARAM;
import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME;
import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN;
import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES;
import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
|
package com.github.randoapp.preferences;
public class Preferences {
public static final String AUTH_TOKEN_DEFAULT_VALUE = "";
public static final String FIREBASE_INSTANCE_ID_DEFAULT_VALUE = "";
public static final String ACCOUNT_DEFAULT_VALUE = "";
public static final int STATISTICS_DEFAULT_VALUE = 0;
private static Object monitor = new Object();
public static String getAuthToken(Context context) {
synchronized (monitor) {
return getSharedPreferences(context).getString(AUTH_TOKEN, AUTH_TOKEN_DEFAULT_VALUE);
}
}
public static void setAuthToken(Context context, String token) {
if (token != null) {
synchronized (monitor) {
getSharedPreferences(context).edit().putString(AUTH_TOKEN, token).apply();
}
}
}
public static void removeAuthToken(Context context) {
synchronized (monitor) {
getSharedPreferences(context).edit().remove(AUTH_TOKEN).apply();
}
}
public static String getAccount(Context context) {
synchronized (monitor) {
|
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java
// public class Statistics implements Serializable {
// private int likes;
// private int dislikes;
//
// public static Statistics of(int likes, int dislikes) {
// Statistics statistics = new Statistics();
// statistics.likes = likes;
// statistics.dislikes = dislikes;
// return statistics;
// }
//
// public static Statistics from(JSONObject obj) {
// Statistics statistics = new Statistics();
// try {
// statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0;
// statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return statistics;
// }
//
// public int getLikes() {
// return likes;
// }
//
// public void setLikes(int likes) {
// this.likes = likes;
// }
//
// public int getDislikes() {
// return dislikes;
// }
//
// public void setDislikes(int dislikes) {
// this.dislikes = dislikes;
// }
// }
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String ACCOUNT = "account";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String AUTH_TOKEN = "auth.token";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String BAN_RESET_AT = "main.ban.reset.at";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FACING_STRING = "camera.facing.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FLASH_MODE = "camera.flash.mode";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_GRID_STRING = "camera.grid.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LATITUDE_PARAM = "latitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LOCATION = "location";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LONGITUDE_PARAM = "longitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String PREFERENCES_FILE_NAME = "rando.prefs";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_DISLIKES = "dislikes";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_LIKES = "likes";
// Path: src/main/java/com/github/randoapp/preferences/Preferences.java
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import com.github.randoapp.db.model.Statistics;
import com.otaliastudios.cameraview.Facing;
import com.otaliastudios.cameraview.Flash;
import com.otaliastudios.cameraview.Grid;
import static com.github.randoapp.Constants.ACCOUNT;
import static com.github.randoapp.Constants.AUTH_TOKEN;
import static com.github.randoapp.Constants.BAN_RESET_AT;
import static com.github.randoapp.Constants.CAMERA_FACING_STRING;
import static com.github.randoapp.Constants.CAMERA_FLASH_MODE;
import static com.github.randoapp.Constants.CAMERA_GRID_STRING;
import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID;
import static com.github.randoapp.Constants.LATITUDE_PARAM;
import static com.github.randoapp.Constants.LOCATION;
import static com.github.randoapp.Constants.LONGITUDE_PARAM;
import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME;
import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN;
import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES;
import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
package com.github.randoapp.preferences;
public class Preferences {
public static final String AUTH_TOKEN_DEFAULT_VALUE = "";
public static final String FIREBASE_INSTANCE_ID_DEFAULT_VALUE = "";
public static final String ACCOUNT_DEFAULT_VALUE = "";
public static final int STATISTICS_DEFAULT_VALUE = 0;
private static Object monitor = new Object();
public static String getAuthToken(Context context) {
synchronized (monitor) {
return getSharedPreferences(context).getString(AUTH_TOKEN, AUTH_TOKEN_DEFAULT_VALUE);
}
}
public static void setAuthToken(Context context, String token) {
if (token != null) {
synchronized (monitor) {
getSharedPreferences(context).edit().putString(AUTH_TOKEN, token).apply();
}
}
}
public static void removeAuthToken(Context context) {
synchronized (monitor) {
getSharedPreferences(context).edit().remove(AUTH_TOKEN).apply();
}
}
public static String getAccount(Context context) {
synchronized (monitor) {
|
return getSharedPreferences(context).getString(ACCOUNT, ACCOUNT_DEFAULT_VALUE);
|
RandoApp/Rando-android
|
src/main/java/com/github/randoapp/preferences/Preferences.java
|
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java
// public class Statistics implements Serializable {
// private int likes;
// private int dislikes;
//
// public static Statistics of(int likes, int dislikes) {
// Statistics statistics = new Statistics();
// statistics.likes = likes;
// statistics.dislikes = dislikes;
// return statistics;
// }
//
// public static Statistics from(JSONObject obj) {
// Statistics statistics = new Statistics();
// try {
// statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0;
// statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return statistics;
// }
//
// public int getLikes() {
// return likes;
// }
//
// public void setLikes(int likes) {
// this.likes = likes;
// }
//
// public int getDislikes() {
// return dislikes;
// }
//
// public void setDislikes(int dislikes) {
// this.dislikes = dislikes;
// }
// }
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String ACCOUNT = "account";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String AUTH_TOKEN = "auth.token";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String BAN_RESET_AT = "main.ban.reset.at";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FACING_STRING = "camera.facing.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FLASH_MODE = "camera.flash.mode";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_GRID_STRING = "camera.grid.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LATITUDE_PARAM = "latitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LOCATION = "location";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LONGITUDE_PARAM = "longitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String PREFERENCES_FILE_NAME = "rando.prefs";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_DISLIKES = "dislikes";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_LIKES = "likes";
|
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import com.github.randoapp.db.model.Statistics;
import com.otaliastudios.cameraview.Facing;
import com.otaliastudios.cameraview.Flash;
import com.otaliastudios.cameraview.Grid;
import static com.github.randoapp.Constants.ACCOUNT;
import static com.github.randoapp.Constants.AUTH_TOKEN;
import static com.github.randoapp.Constants.BAN_RESET_AT;
import static com.github.randoapp.Constants.CAMERA_FACING_STRING;
import static com.github.randoapp.Constants.CAMERA_FLASH_MODE;
import static com.github.randoapp.Constants.CAMERA_GRID_STRING;
import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID;
import static com.github.randoapp.Constants.LATITUDE_PARAM;
import static com.github.randoapp.Constants.LOCATION;
import static com.github.randoapp.Constants.LONGITUDE_PARAM;
import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME;
import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN;
import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES;
import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
|
}
public static void removeAuthToken(Context context) {
synchronized (monitor) {
getSharedPreferences(context).edit().remove(AUTH_TOKEN).apply();
}
}
public static String getAccount(Context context) {
synchronized (monitor) {
return getSharedPreferences(context).getString(ACCOUNT, ACCOUNT_DEFAULT_VALUE);
}
}
public static void setAccount(Context context, String token) {
if (token != null) {
synchronized (monitor) {
getSharedPreferences(context).edit().putString(ACCOUNT, token).apply();
}
}
}
public static void removeAccount(Context context) {
synchronized (monitor) {
getSharedPreferences(context).edit().remove(ACCOUNT).apply();
}
}
public static Location getLocation(Context context) {
|
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java
// public class Statistics implements Serializable {
// private int likes;
// private int dislikes;
//
// public static Statistics of(int likes, int dislikes) {
// Statistics statistics = new Statistics();
// statistics.likes = likes;
// statistics.dislikes = dislikes;
// return statistics;
// }
//
// public static Statistics from(JSONObject obj) {
// Statistics statistics = new Statistics();
// try {
// statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0;
// statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return statistics;
// }
//
// public int getLikes() {
// return likes;
// }
//
// public void setLikes(int likes) {
// this.likes = likes;
// }
//
// public int getDislikes() {
// return dislikes;
// }
//
// public void setDislikes(int dislikes) {
// this.dislikes = dislikes;
// }
// }
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String ACCOUNT = "account";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String AUTH_TOKEN = "auth.token";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String BAN_RESET_AT = "main.ban.reset.at";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FACING_STRING = "camera.facing.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FLASH_MODE = "camera.flash.mode";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_GRID_STRING = "camera.grid.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LATITUDE_PARAM = "latitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LOCATION = "location";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LONGITUDE_PARAM = "longitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String PREFERENCES_FILE_NAME = "rando.prefs";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_DISLIKES = "dislikes";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_LIKES = "likes";
// Path: src/main/java/com/github/randoapp/preferences/Preferences.java
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import com.github.randoapp.db.model.Statistics;
import com.otaliastudios.cameraview.Facing;
import com.otaliastudios.cameraview.Flash;
import com.otaliastudios.cameraview.Grid;
import static com.github.randoapp.Constants.ACCOUNT;
import static com.github.randoapp.Constants.AUTH_TOKEN;
import static com.github.randoapp.Constants.BAN_RESET_AT;
import static com.github.randoapp.Constants.CAMERA_FACING_STRING;
import static com.github.randoapp.Constants.CAMERA_FLASH_MODE;
import static com.github.randoapp.Constants.CAMERA_GRID_STRING;
import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID;
import static com.github.randoapp.Constants.LATITUDE_PARAM;
import static com.github.randoapp.Constants.LOCATION;
import static com.github.randoapp.Constants.LONGITUDE_PARAM;
import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME;
import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN;
import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES;
import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
}
public static void removeAuthToken(Context context) {
synchronized (monitor) {
getSharedPreferences(context).edit().remove(AUTH_TOKEN).apply();
}
}
public static String getAccount(Context context) {
synchronized (monitor) {
return getSharedPreferences(context).getString(ACCOUNT, ACCOUNT_DEFAULT_VALUE);
}
}
public static void setAccount(Context context, String token) {
if (token != null) {
synchronized (monitor) {
getSharedPreferences(context).edit().putString(ACCOUNT, token).apply();
}
}
}
public static void removeAccount(Context context) {
synchronized (monitor) {
getSharedPreferences(context).edit().remove(ACCOUNT).apply();
}
}
public static Location getLocation(Context context) {
|
Location location = new Location(LOCATION);
|
RandoApp/Rando-android
|
src/main/java/com/github/randoapp/preferences/Preferences.java
|
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java
// public class Statistics implements Serializable {
// private int likes;
// private int dislikes;
//
// public static Statistics of(int likes, int dislikes) {
// Statistics statistics = new Statistics();
// statistics.likes = likes;
// statistics.dislikes = dislikes;
// return statistics;
// }
//
// public static Statistics from(JSONObject obj) {
// Statistics statistics = new Statistics();
// try {
// statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0;
// statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return statistics;
// }
//
// public int getLikes() {
// return likes;
// }
//
// public void setLikes(int likes) {
// this.likes = likes;
// }
//
// public int getDislikes() {
// return dislikes;
// }
//
// public void setDislikes(int dislikes) {
// this.dislikes = dislikes;
// }
// }
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String ACCOUNT = "account";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String AUTH_TOKEN = "auth.token";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String BAN_RESET_AT = "main.ban.reset.at";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FACING_STRING = "camera.facing.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FLASH_MODE = "camera.flash.mode";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_GRID_STRING = "camera.grid.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LATITUDE_PARAM = "latitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LOCATION = "location";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LONGITUDE_PARAM = "longitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String PREFERENCES_FILE_NAME = "rando.prefs";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_DISLIKES = "dislikes";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_LIKES = "likes";
|
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import com.github.randoapp.db.model.Statistics;
import com.otaliastudios.cameraview.Facing;
import com.otaliastudios.cameraview.Flash;
import com.otaliastudios.cameraview.Grid;
import static com.github.randoapp.Constants.ACCOUNT;
import static com.github.randoapp.Constants.AUTH_TOKEN;
import static com.github.randoapp.Constants.BAN_RESET_AT;
import static com.github.randoapp.Constants.CAMERA_FACING_STRING;
import static com.github.randoapp.Constants.CAMERA_FLASH_MODE;
import static com.github.randoapp.Constants.CAMERA_GRID_STRING;
import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID;
import static com.github.randoapp.Constants.LATITUDE_PARAM;
import static com.github.randoapp.Constants.LOCATION;
import static com.github.randoapp.Constants.LONGITUDE_PARAM;
import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME;
import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN;
import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES;
import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
|
public static void removeAuthToken(Context context) {
synchronized (monitor) {
getSharedPreferences(context).edit().remove(AUTH_TOKEN).apply();
}
}
public static String getAccount(Context context) {
synchronized (monitor) {
return getSharedPreferences(context).getString(ACCOUNT, ACCOUNT_DEFAULT_VALUE);
}
}
public static void setAccount(Context context, String token) {
if (token != null) {
synchronized (monitor) {
getSharedPreferences(context).edit().putString(ACCOUNT, token).apply();
}
}
}
public static void removeAccount(Context context) {
synchronized (monitor) {
getSharedPreferences(context).edit().remove(ACCOUNT).apply();
}
}
public static Location getLocation(Context context) {
Location location = new Location(LOCATION);
synchronized (monitor) {
|
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java
// public class Statistics implements Serializable {
// private int likes;
// private int dislikes;
//
// public static Statistics of(int likes, int dislikes) {
// Statistics statistics = new Statistics();
// statistics.likes = likes;
// statistics.dislikes = dislikes;
// return statistics;
// }
//
// public static Statistics from(JSONObject obj) {
// Statistics statistics = new Statistics();
// try {
// statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0;
// statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return statistics;
// }
//
// public int getLikes() {
// return likes;
// }
//
// public void setLikes(int likes) {
// this.likes = likes;
// }
//
// public int getDislikes() {
// return dislikes;
// }
//
// public void setDislikes(int dislikes) {
// this.dislikes = dislikes;
// }
// }
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String ACCOUNT = "account";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String AUTH_TOKEN = "auth.token";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String BAN_RESET_AT = "main.ban.reset.at";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FACING_STRING = "camera.facing.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FLASH_MODE = "camera.flash.mode";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_GRID_STRING = "camera.grid.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LATITUDE_PARAM = "latitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LOCATION = "location";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LONGITUDE_PARAM = "longitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String PREFERENCES_FILE_NAME = "rando.prefs";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_DISLIKES = "dislikes";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_LIKES = "likes";
// Path: src/main/java/com/github/randoapp/preferences/Preferences.java
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import com.github.randoapp.db.model.Statistics;
import com.otaliastudios.cameraview.Facing;
import com.otaliastudios.cameraview.Flash;
import com.otaliastudios.cameraview.Grid;
import static com.github.randoapp.Constants.ACCOUNT;
import static com.github.randoapp.Constants.AUTH_TOKEN;
import static com.github.randoapp.Constants.BAN_RESET_AT;
import static com.github.randoapp.Constants.CAMERA_FACING_STRING;
import static com.github.randoapp.Constants.CAMERA_FLASH_MODE;
import static com.github.randoapp.Constants.CAMERA_GRID_STRING;
import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID;
import static com.github.randoapp.Constants.LATITUDE_PARAM;
import static com.github.randoapp.Constants.LOCATION;
import static com.github.randoapp.Constants.LONGITUDE_PARAM;
import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME;
import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN;
import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES;
import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
public static void removeAuthToken(Context context) {
synchronized (monitor) {
getSharedPreferences(context).edit().remove(AUTH_TOKEN).apply();
}
}
public static String getAccount(Context context) {
synchronized (monitor) {
return getSharedPreferences(context).getString(ACCOUNT, ACCOUNT_DEFAULT_VALUE);
}
}
public static void setAccount(Context context, String token) {
if (token != null) {
synchronized (monitor) {
getSharedPreferences(context).edit().putString(ACCOUNT, token).apply();
}
}
}
public static void removeAccount(Context context) {
synchronized (monitor) {
getSharedPreferences(context).edit().remove(ACCOUNT).apply();
}
}
public static Location getLocation(Context context) {
Location location = new Location(LOCATION);
synchronized (monitor) {
|
double lat = Double.valueOf(getSharedPreferences(context).getString(LATITUDE_PARAM, "0"));
|
RandoApp/Rando-android
|
src/main/java/com/github/randoapp/preferences/Preferences.java
|
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java
// public class Statistics implements Serializable {
// private int likes;
// private int dislikes;
//
// public static Statistics of(int likes, int dislikes) {
// Statistics statistics = new Statistics();
// statistics.likes = likes;
// statistics.dislikes = dislikes;
// return statistics;
// }
//
// public static Statistics from(JSONObject obj) {
// Statistics statistics = new Statistics();
// try {
// statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0;
// statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return statistics;
// }
//
// public int getLikes() {
// return likes;
// }
//
// public void setLikes(int likes) {
// this.likes = likes;
// }
//
// public int getDislikes() {
// return dislikes;
// }
//
// public void setDislikes(int dislikes) {
// this.dislikes = dislikes;
// }
// }
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String ACCOUNT = "account";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String AUTH_TOKEN = "auth.token";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String BAN_RESET_AT = "main.ban.reset.at";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FACING_STRING = "camera.facing.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FLASH_MODE = "camera.flash.mode";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_GRID_STRING = "camera.grid.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LATITUDE_PARAM = "latitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LOCATION = "location";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LONGITUDE_PARAM = "longitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String PREFERENCES_FILE_NAME = "rando.prefs";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_DISLIKES = "dislikes";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_LIKES = "likes";
|
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import com.github.randoapp.db.model.Statistics;
import com.otaliastudios.cameraview.Facing;
import com.otaliastudios.cameraview.Flash;
import com.otaliastudios.cameraview.Grid;
import static com.github.randoapp.Constants.ACCOUNT;
import static com.github.randoapp.Constants.AUTH_TOKEN;
import static com.github.randoapp.Constants.BAN_RESET_AT;
import static com.github.randoapp.Constants.CAMERA_FACING_STRING;
import static com.github.randoapp.Constants.CAMERA_FLASH_MODE;
import static com.github.randoapp.Constants.CAMERA_GRID_STRING;
import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID;
import static com.github.randoapp.Constants.LATITUDE_PARAM;
import static com.github.randoapp.Constants.LOCATION;
import static com.github.randoapp.Constants.LONGITUDE_PARAM;
import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME;
import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN;
import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES;
import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
|
synchronized (monitor) {
getSharedPreferences(context).edit().remove(AUTH_TOKEN).apply();
}
}
public static String getAccount(Context context) {
synchronized (monitor) {
return getSharedPreferences(context).getString(ACCOUNT, ACCOUNT_DEFAULT_VALUE);
}
}
public static void setAccount(Context context, String token) {
if (token != null) {
synchronized (monitor) {
getSharedPreferences(context).edit().putString(ACCOUNT, token).apply();
}
}
}
public static void removeAccount(Context context) {
synchronized (monitor) {
getSharedPreferences(context).edit().remove(ACCOUNT).apply();
}
}
public static Location getLocation(Context context) {
Location location = new Location(LOCATION);
synchronized (monitor) {
double lat = Double.valueOf(getSharedPreferences(context).getString(LATITUDE_PARAM, "0"));
|
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java
// public class Statistics implements Serializable {
// private int likes;
// private int dislikes;
//
// public static Statistics of(int likes, int dislikes) {
// Statistics statistics = new Statistics();
// statistics.likes = likes;
// statistics.dislikes = dislikes;
// return statistics;
// }
//
// public static Statistics from(JSONObject obj) {
// Statistics statistics = new Statistics();
// try {
// statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0;
// statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return statistics;
// }
//
// public int getLikes() {
// return likes;
// }
//
// public void setLikes(int likes) {
// this.likes = likes;
// }
//
// public int getDislikes() {
// return dislikes;
// }
//
// public void setDislikes(int dislikes) {
// this.dislikes = dislikes;
// }
// }
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String ACCOUNT = "account";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String AUTH_TOKEN = "auth.token";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String BAN_RESET_AT = "main.ban.reset.at";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FACING_STRING = "camera.facing.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FLASH_MODE = "camera.flash.mode";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_GRID_STRING = "camera.grid.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LATITUDE_PARAM = "latitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LOCATION = "location";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LONGITUDE_PARAM = "longitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String PREFERENCES_FILE_NAME = "rando.prefs";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_DISLIKES = "dislikes";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_LIKES = "likes";
// Path: src/main/java/com/github/randoapp/preferences/Preferences.java
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import com.github.randoapp.db.model.Statistics;
import com.otaliastudios.cameraview.Facing;
import com.otaliastudios.cameraview.Flash;
import com.otaliastudios.cameraview.Grid;
import static com.github.randoapp.Constants.ACCOUNT;
import static com.github.randoapp.Constants.AUTH_TOKEN;
import static com.github.randoapp.Constants.BAN_RESET_AT;
import static com.github.randoapp.Constants.CAMERA_FACING_STRING;
import static com.github.randoapp.Constants.CAMERA_FLASH_MODE;
import static com.github.randoapp.Constants.CAMERA_GRID_STRING;
import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID;
import static com.github.randoapp.Constants.LATITUDE_PARAM;
import static com.github.randoapp.Constants.LOCATION;
import static com.github.randoapp.Constants.LONGITUDE_PARAM;
import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME;
import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN;
import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES;
import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
synchronized (monitor) {
getSharedPreferences(context).edit().remove(AUTH_TOKEN).apply();
}
}
public static String getAccount(Context context) {
synchronized (monitor) {
return getSharedPreferences(context).getString(ACCOUNT, ACCOUNT_DEFAULT_VALUE);
}
}
public static void setAccount(Context context, String token) {
if (token != null) {
synchronized (monitor) {
getSharedPreferences(context).edit().putString(ACCOUNT, token).apply();
}
}
}
public static void removeAccount(Context context) {
synchronized (monitor) {
getSharedPreferences(context).edit().remove(ACCOUNT).apply();
}
}
public static Location getLocation(Context context) {
Location location = new Location(LOCATION);
synchronized (monitor) {
double lat = Double.valueOf(getSharedPreferences(context).getString(LATITUDE_PARAM, "0"));
|
double lon = Double.valueOf(getSharedPreferences(context).getString(LONGITUDE_PARAM, "0"));
|
RandoApp/Rando-android
|
src/main/java/com/github/randoapp/preferences/Preferences.java
|
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java
// public class Statistics implements Serializable {
// private int likes;
// private int dislikes;
//
// public static Statistics of(int likes, int dislikes) {
// Statistics statistics = new Statistics();
// statistics.likes = likes;
// statistics.dislikes = dislikes;
// return statistics;
// }
//
// public static Statistics from(JSONObject obj) {
// Statistics statistics = new Statistics();
// try {
// statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0;
// statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return statistics;
// }
//
// public int getLikes() {
// return likes;
// }
//
// public void setLikes(int likes) {
// this.likes = likes;
// }
//
// public int getDislikes() {
// return dislikes;
// }
//
// public void setDislikes(int dislikes) {
// this.dislikes = dislikes;
// }
// }
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String ACCOUNT = "account";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String AUTH_TOKEN = "auth.token";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String BAN_RESET_AT = "main.ban.reset.at";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FACING_STRING = "camera.facing.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FLASH_MODE = "camera.flash.mode";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_GRID_STRING = "camera.grid.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LATITUDE_PARAM = "latitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LOCATION = "location";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LONGITUDE_PARAM = "longitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String PREFERENCES_FILE_NAME = "rando.prefs";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_DISLIKES = "dislikes";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_LIKES = "likes";
|
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import com.github.randoapp.db.model.Statistics;
import com.otaliastudios.cameraview.Facing;
import com.otaliastudios.cameraview.Flash;
import com.otaliastudios.cameraview.Grid;
import static com.github.randoapp.Constants.ACCOUNT;
import static com.github.randoapp.Constants.AUTH_TOKEN;
import static com.github.randoapp.Constants.BAN_RESET_AT;
import static com.github.randoapp.Constants.CAMERA_FACING_STRING;
import static com.github.randoapp.Constants.CAMERA_FLASH_MODE;
import static com.github.randoapp.Constants.CAMERA_GRID_STRING;
import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID;
import static com.github.randoapp.Constants.LATITUDE_PARAM;
import static com.github.randoapp.Constants.LOCATION;
import static com.github.randoapp.Constants.LONGITUDE_PARAM;
import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME;
import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN;
import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES;
import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
|
location.setLatitude(lat);
location.setLongitude(lon);
}
return location;
}
public static void setLocation(Context context, Location location) {
if (location != null) {
synchronized (monitor) {
getSharedPreferences(context).edit().putString(LONGITUDE_PARAM, String.valueOf(location.getLongitude())).apply();
getSharedPreferences(context).edit().putString(LATITUDE_PARAM, String.valueOf(location.getLatitude())).apply();
}
}
}
public static void removeLocation(Context context) {
synchronized (monitor) {
getSharedPreferences(context).edit().remove(LONGITUDE_PARAM).apply();
getSharedPreferences(context).edit().remove(LATITUDE_PARAM).apply();
}
}
public static boolean isTrainingFragmentShown() {
//TODO: change to return real value when Training will be Implemented.
return true;
//return 1 == getSharedPreferences().getInt(Constants.TRAINING_FRAGMENT_SHOWN, 0);
}
public static void setTrainingFragmentShown(Context context, int i) {
synchronized (monitor) {
|
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java
// public class Statistics implements Serializable {
// private int likes;
// private int dislikes;
//
// public static Statistics of(int likes, int dislikes) {
// Statistics statistics = new Statistics();
// statistics.likes = likes;
// statistics.dislikes = dislikes;
// return statistics;
// }
//
// public static Statistics from(JSONObject obj) {
// Statistics statistics = new Statistics();
// try {
// statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0;
// statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return statistics;
// }
//
// public int getLikes() {
// return likes;
// }
//
// public void setLikes(int likes) {
// this.likes = likes;
// }
//
// public int getDislikes() {
// return dislikes;
// }
//
// public void setDislikes(int dislikes) {
// this.dislikes = dislikes;
// }
// }
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String ACCOUNT = "account";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String AUTH_TOKEN = "auth.token";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String BAN_RESET_AT = "main.ban.reset.at";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FACING_STRING = "camera.facing.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_FLASH_MODE = "camera.flash.mode";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String CAMERA_GRID_STRING = "camera.grid.string";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LATITUDE_PARAM = "latitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LOCATION = "location";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String LONGITUDE_PARAM = "longitude";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String PREFERENCES_FILE_NAME = "rando.prefs";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_DISLIKES = "dislikes";
//
// Path: src/main/java/com/github/randoapp/Constants.java
// public static final String USER_STATISTICS_LIKES = "likes";
// Path: src/main/java/com/github/randoapp/preferences/Preferences.java
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import com.github.randoapp.db.model.Statistics;
import com.otaliastudios.cameraview.Facing;
import com.otaliastudios.cameraview.Flash;
import com.otaliastudios.cameraview.Grid;
import static com.github.randoapp.Constants.ACCOUNT;
import static com.github.randoapp.Constants.AUTH_TOKEN;
import static com.github.randoapp.Constants.BAN_RESET_AT;
import static com.github.randoapp.Constants.CAMERA_FACING_STRING;
import static com.github.randoapp.Constants.CAMERA_FLASH_MODE;
import static com.github.randoapp.Constants.CAMERA_GRID_STRING;
import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID;
import static com.github.randoapp.Constants.LATITUDE_PARAM;
import static com.github.randoapp.Constants.LOCATION;
import static com.github.randoapp.Constants.LONGITUDE_PARAM;
import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME;
import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN;
import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES;
import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
location.setLatitude(lat);
location.setLongitude(lon);
}
return location;
}
public static void setLocation(Context context, Location location) {
if (location != null) {
synchronized (monitor) {
getSharedPreferences(context).edit().putString(LONGITUDE_PARAM, String.valueOf(location.getLongitude())).apply();
getSharedPreferences(context).edit().putString(LATITUDE_PARAM, String.valueOf(location.getLatitude())).apply();
}
}
}
public static void removeLocation(Context context) {
synchronized (monitor) {
getSharedPreferences(context).edit().remove(LONGITUDE_PARAM).apply();
getSharedPreferences(context).edit().remove(LATITUDE_PARAM).apply();
}
}
public static boolean isTrainingFragmentShown() {
//TODO: change to return real value when Training will be Implemented.
return true;
//return 1 == getSharedPreferences().getInt(Constants.TRAINING_FRAGMENT_SHOWN, 0);
}
public static void setTrainingFragmentShown(Context context, int i) {
synchronized (monitor) {
|
getSharedPreferences(context).edit().putInt(TRAINING_FRAGMENT_SHOWN, i).apply();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.