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 |
|---|---|---|---|---|---|---|
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/service/AgentStringReaderProvider.java | // Path: src/main/java/nl/uva/larissa/json/ParseException.java
// public class ParseException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -786854572139522845L;
//
// public ParseException(String message) {
// super(message);
// }
// public ParseException(Exception e) {
// super(e);
// }
//
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementParser.java
// @Contract
// public interface StatementParser {
// public Statement parseStatement(String json) throws ParseException;
//
// public StatementDocument parseStatementDocument(String doc)
// throws ParseException;
//
// public <T> T parse(Class<T> type, String json) throws ParseException;
//
// public List<Statement> parseStatementList(String json)
// throws ParseException;;
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementPrinter.java
// public interface StatementPrinter {
// public String printStatement(Statement statement) throws IOException;
//
// public String print(StatementResult result) throws IOException;
//
// String printCompact(Object object) throws IOException;
//
// /**
// * print Statement as defined in xAPI spec 7.2.3 for parameter 'format' with
// * value 'ids'; Only print minimum info in Agent, Activity and Group Objects
// * necessary to identify them
// **/
// String printIds(Statement statement) throws IOException;
//
// public String printIds(StatementResult result) throws IOException;
// }
//
// Path: src/main/java/nl/uva/larissa/json/model/Agent.java
// @JsonInclude(Include.NON_NULL)
// public class Agent implements Actor, Authority, Instructor, StatementObject {
//
// private String objectType;
// private String name;
// @JsonUnwrapped
// @Valid
// @NotNull
// private IFI identifier;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public IFI getIdentifier() {
// return identifier;
// }
//
// public void setIdentifier(IFI identifier) {
// this.identifier = identifier;
// }
//
// public String getObjectType() {
// return objectType;
// }
//
// public void setObjectType(String objectType) {
// this.objectType = objectType;
// }
// }
| import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.inject.Inject;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import nl.uva.larissa.json.ParseException;
import nl.uva.larissa.json.StatementParser;
import nl.uva.larissa.json.StatementPrinter;
import nl.uva.larissa.json.model.Agent; | package nl.uva.larissa.service;
@Provider
public class AgentStringReaderProvider implements ParamConverterProvider {
@Inject | // Path: src/main/java/nl/uva/larissa/json/ParseException.java
// public class ParseException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -786854572139522845L;
//
// public ParseException(String message) {
// super(message);
// }
// public ParseException(Exception e) {
// super(e);
// }
//
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementParser.java
// @Contract
// public interface StatementParser {
// public Statement parseStatement(String json) throws ParseException;
//
// public StatementDocument parseStatementDocument(String doc)
// throws ParseException;
//
// public <T> T parse(Class<T> type, String json) throws ParseException;
//
// public List<Statement> parseStatementList(String json)
// throws ParseException;;
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementPrinter.java
// public interface StatementPrinter {
// public String printStatement(Statement statement) throws IOException;
//
// public String print(StatementResult result) throws IOException;
//
// String printCompact(Object object) throws IOException;
//
// /**
// * print Statement as defined in xAPI spec 7.2.3 for parameter 'format' with
// * value 'ids'; Only print minimum info in Agent, Activity and Group Objects
// * necessary to identify them
// **/
// String printIds(Statement statement) throws IOException;
//
// public String printIds(StatementResult result) throws IOException;
// }
//
// Path: src/main/java/nl/uva/larissa/json/model/Agent.java
// @JsonInclude(Include.NON_NULL)
// public class Agent implements Actor, Authority, Instructor, StatementObject {
//
// private String objectType;
// private String name;
// @JsonUnwrapped
// @Valid
// @NotNull
// private IFI identifier;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public IFI getIdentifier() {
// return identifier;
// }
//
// public void setIdentifier(IFI identifier) {
// this.identifier = identifier;
// }
//
// public String getObjectType() {
// return objectType;
// }
//
// public void setObjectType(String objectType) {
// this.objectType = objectType;
// }
// }
// Path: src/main/java/nl/uva/larissa/service/AgentStringReaderProvider.java
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.inject.Inject;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import nl.uva.larissa.json.ParseException;
import nl.uva.larissa.json.StatementParser;
import nl.uva.larissa.json.StatementPrinter;
import nl.uva.larissa.json.model.Agent;
package nl.uva.larissa.service;
@Provider
public class AgentStringReaderProvider implements ParamConverterProvider {
@Inject | StatementParser parser; |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/service/AgentStringReaderProvider.java | // Path: src/main/java/nl/uva/larissa/json/ParseException.java
// public class ParseException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -786854572139522845L;
//
// public ParseException(String message) {
// super(message);
// }
// public ParseException(Exception e) {
// super(e);
// }
//
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementParser.java
// @Contract
// public interface StatementParser {
// public Statement parseStatement(String json) throws ParseException;
//
// public StatementDocument parseStatementDocument(String doc)
// throws ParseException;
//
// public <T> T parse(Class<T> type, String json) throws ParseException;
//
// public List<Statement> parseStatementList(String json)
// throws ParseException;;
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementPrinter.java
// public interface StatementPrinter {
// public String printStatement(Statement statement) throws IOException;
//
// public String print(StatementResult result) throws IOException;
//
// String printCompact(Object object) throws IOException;
//
// /**
// * print Statement as defined in xAPI spec 7.2.3 for parameter 'format' with
// * value 'ids'; Only print minimum info in Agent, Activity and Group Objects
// * necessary to identify them
// **/
// String printIds(Statement statement) throws IOException;
//
// public String printIds(StatementResult result) throws IOException;
// }
//
// Path: src/main/java/nl/uva/larissa/json/model/Agent.java
// @JsonInclude(Include.NON_NULL)
// public class Agent implements Actor, Authority, Instructor, StatementObject {
//
// private String objectType;
// private String name;
// @JsonUnwrapped
// @Valid
// @NotNull
// private IFI identifier;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public IFI getIdentifier() {
// return identifier;
// }
//
// public void setIdentifier(IFI identifier) {
// this.identifier = identifier;
// }
//
// public String getObjectType() {
// return objectType;
// }
//
// public void setObjectType(String objectType) {
// this.objectType = objectType;
// }
// }
| import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.inject.Inject;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import nl.uva.larissa.json.ParseException;
import nl.uva.larissa.json.StatementParser;
import nl.uva.larissa.json.StatementPrinter;
import nl.uva.larissa.json.model.Agent; | package nl.uva.larissa.service;
@Provider
public class AgentStringReaderProvider implements ParamConverterProvider {
@Inject
StatementParser parser;
@Inject | // Path: src/main/java/nl/uva/larissa/json/ParseException.java
// public class ParseException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -786854572139522845L;
//
// public ParseException(String message) {
// super(message);
// }
// public ParseException(Exception e) {
// super(e);
// }
//
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementParser.java
// @Contract
// public interface StatementParser {
// public Statement parseStatement(String json) throws ParseException;
//
// public StatementDocument parseStatementDocument(String doc)
// throws ParseException;
//
// public <T> T parse(Class<T> type, String json) throws ParseException;
//
// public List<Statement> parseStatementList(String json)
// throws ParseException;;
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementPrinter.java
// public interface StatementPrinter {
// public String printStatement(Statement statement) throws IOException;
//
// public String print(StatementResult result) throws IOException;
//
// String printCompact(Object object) throws IOException;
//
// /**
// * print Statement as defined in xAPI spec 7.2.3 for parameter 'format' with
// * value 'ids'; Only print minimum info in Agent, Activity and Group Objects
// * necessary to identify them
// **/
// String printIds(Statement statement) throws IOException;
//
// public String printIds(StatementResult result) throws IOException;
// }
//
// Path: src/main/java/nl/uva/larissa/json/model/Agent.java
// @JsonInclude(Include.NON_NULL)
// public class Agent implements Actor, Authority, Instructor, StatementObject {
//
// private String objectType;
// private String name;
// @JsonUnwrapped
// @Valid
// @NotNull
// private IFI identifier;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public IFI getIdentifier() {
// return identifier;
// }
//
// public void setIdentifier(IFI identifier) {
// this.identifier = identifier;
// }
//
// public String getObjectType() {
// return objectType;
// }
//
// public void setObjectType(String objectType) {
// this.objectType = objectType;
// }
// }
// Path: src/main/java/nl/uva/larissa/service/AgentStringReaderProvider.java
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.inject.Inject;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import nl.uva.larissa.json.ParseException;
import nl.uva.larissa.json.StatementParser;
import nl.uva.larissa.json.StatementPrinter;
import nl.uva.larissa.json.model.Agent;
package nl.uva.larissa.service;
@Provider
public class AgentStringReaderProvider implements ParamConverterProvider {
@Inject
StatementParser parser;
@Inject | StatementPrinter printer; |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/service/AgentStringReaderProvider.java | // Path: src/main/java/nl/uva/larissa/json/ParseException.java
// public class ParseException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -786854572139522845L;
//
// public ParseException(String message) {
// super(message);
// }
// public ParseException(Exception e) {
// super(e);
// }
//
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementParser.java
// @Contract
// public interface StatementParser {
// public Statement parseStatement(String json) throws ParseException;
//
// public StatementDocument parseStatementDocument(String doc)
// throws ParseException;
//
// public <T> T parse(Class<T> type, String json) throws ParseException;
//
// public List<Statement> parseStatementList(String json)
// throws ParseException;;
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementPrinter.java
// public interface StatementPrinter {
// public String printStatement(Statement statement) throws IOException;
//
// public String print(StatementResult result) throws IOException;
//
// String printCompact(Object object) throws IOException;
//
// /**
// * print Statement as defined in xAPI spec 7.2.3 for parameter 'format' with
// * value 'ids'; Only print minimum info in Agent, Activity and Group Objects
// * necessary to identify them
// **/
// String printIds(Statement statement) throws IOException;
//
// public String printIds(StatementResult result) throws IOException;
// }
//
// Path: src/main/java/nl/uva/larissa/json/model/Agent.java
// @JsonInclude(Include.NON_NULL)
// public class Agent implements Actor, Authority, Instructor, StatementObject {
//
// private String objectType;
// private String name;
// @JsonUnwrapped
// @Valid
// @NotNull
// private IFI identifier;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public IFI getIdentifier() {
// return identifier;
// }
//
// public void setIdentifier(IFI identifier) {
// this.identifier = identifier;
// }
//
// public String getObjectType() {
// return objectType;
// }
//
// public void setObjectType(String objectType) {
// this.objectType = objectType;
// }
// }
| import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.inject.Inject;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import nl.uva.larissa.json.ParseException;
import nl.uva.larissa.json.StatementParser;
import nl.uva.larissa.json.StatementPrinter;
import nl.uva.larissa.json.model.Agent; | package nl.uva.larissa.service;
@Provider
public class AgentStringReaderProvider implements ParamConverterProvider {
@Inject
StatementParser parser;
@Inject
StatementPrinter printer;
@SuppressWarnings("unchecked")
@Override
public <T> ParamConverter<T> getConverter(Class<T> arg0, Type arg1,
Annotation[] arg2) { | // Path: src/main/java/nl/uva/larissa/json/ParseException.java
// public class ParseException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -786854572139522845L;
//
// public ParseException(String message) {
// super(message);
// }
// public ParseException(Exception e) {
// super(e);
// }
//
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementParser.java
// @Contract
// public interface StatementParser {
// public Statement parseStatement(String json) throws ParseException;
//
// public StatementDocument parseStatementDocument(String doc)
// throws ParseException;
//
// public <T> T parse(Class<T> type, String json) throws ParseException;
//
// public List<Statement> parseStatementList(String json)
// throws ParseException;;
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementPrinter.java
// public interface StatementPrinter {
// public String printStatement(Statement statement) throws IOException;
//
// public String print(StatementResult result) throws IOException;
//
// String printCompact(Object object) throws IOException;
//
// /**
// * print Statement as defined in xAPI spec 7.2.3 for parameter 'format' with
// * value 'ids'; Only print minimum info in Agent, Activity and Group Objects
// * necessary to identify them
// **/
// String printIds(Statement statement) throws IOException;
//
// public String printIds(StatementResult result) throws IOException;
// }
//
// Path: src/main/java/nl/uva/larissa/json/model/Agent.java
// @JsonInclude(Include.NON_NULL)
// public class Agent implements Actor, Authority, Instructor, StatementObject {
//
// private String objectType;
// private String name;
// @JsonUnwrapped
// @Valid
// @NotNull
// private IFI identifier;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public IFI getIdentifier() {
// return identifier;
// }
//
// public void setIdentifier(IFI identifier) {
// this.identifier = identifier;
// }
//
// public String getObjectType() {
// return objectType;
// }
//
// public void setObjectType(String objectType) {
// this.objectType = objectType;
// }
// }
// Path: src/main/java/nl/uva/larissa/service/AgentStringReaderProvider.java
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.inject.Inject;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import nl.uva.larissa.json.ParseException;
import nl.uva.larissa.json.StatementParser;
import nl.uva.larissa.json.StatementPrinter;
import nl.uva.larissa.json.model.Agent;
package nl.uva.larissa.service;
@Provider
public class AgentStringReaderProvider implements ParamConverterProvider {
@Inject
StatementParser parser;
@Inject
StatementPrinter printer;
@SuppressWarnings("unchecked")
@Override
public <T> ParamConverter<T> getConverter(Class<T> arg0, Type arg1,
Annotation[] arg2) { | if (arg1.equals(Agent.class)) { |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/service/AgentStringReaderProvider.java | // Path: src/main/java/nl/uva/larissa/json/ParseException.java
// public class ParseException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -786854572139522845L;
//
// public ParseException(String message) {
// super(message);
// }
// public ParseException(Exception e) {
// super(e);
// }
//
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementParser.java
// @Contract
// public interface StatementParser {
// public Statement parseStatement(String json) throws ParseException;
//
// public StatementDocument parseStatementDocument(String doc)
// throws ParseException;
//
// public <T> T parse(Class<T> type, String json) throws ParseException;
//
// public List<Statement> parseStatementList(String json)
// throws ParseException;;
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementPrinter.java
// public interface StatementPrinter {
// public String printStatement(Statement statement) throws IOException;
//
// public String print(StatementResult result) throws IOException;
//
// String printCompact(Object object) throws IOException;
//
// /**
// * print Statement as defined in xAPI spec 7.2.3 for parameter 'format' with
// * value 'ids'; Only print minimum info in Agent, Activity and Group Objects
// * necessary to identify them
// **/
// String printIds(Statement statement) throws IOException;
//
// public String printIds(StatementResult result) throws IOException;
// }
//
// Path: src/main/java/nl/uva/larissa/json/model/Agent.java
// @JsonInclude(Include.NON_NULL)
// public class Agent implements Actor, Authority, Instructor, StatementObject {
//
// private String objectType;
// private String name;
// @JsonUnwrapped
// @Valid
// @NotNull
// private IFI identifier;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public IFI getIdentifier() {
// return identifier;
// }
//
// public void setIdentifier(IFI identifier) {
// this.identifier = identifier;
// }
//
// public String getObjectType() {
// return objectType;
// }
//
// public void setObjectType(String objectType) {
// this.objectType = objectType;
// }
// }
| import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.inject.Inject;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import nl.uva.larissa.json.ParseException;
import nl.uva.larissa.json.StatementParser;
import nl.uva.larissa.json.StatementPrinter;
import nl.uva.larissa.json.model.Agent; | package nl.uva.larissa.service;
@Provider
public class AgentStringReaderProvider implements ParamConverterProvider {
@Inject
StatementParser parser;
@Inject
StatementPrinter printer;
@SuppressWarnings("unchecked")
@Override
public <T> ParamConverter<T> getConverter(Class<T> arg0, Type arg1,
Annotation[] arg2) {
if (arg1.equals(Agent.class)) {
return (ParamConverter<T>) new AgentParamConverter();
}
return null;
}
// TODO static class (but keep injection working?)
class AgentParamConverter implements ParamConverter<Agent> {
@Override
public Agent fromString(String arg0) {
try {
return parser.parse(Agent.class, arg0); | // Path: src/main/java/nl/uva/larissa/json/ParseException.java
// public class ParseException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -786854572139522845L;
//
// public ParseException(String message) {
// super(message);
// }
// public ParseException(Exception e) {
// super(e);
// }
//
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementParser.java
// @Contract
// public interface StatementParser {
// public Statement parseStatement(String json) throws ParseException;
//
// public StatementDocument parseStatementDocument(String doc)
// throws ParseException;
//
// public <T> T parse(Class<T> type, String json) throws ParseException;
//
// public List<Statement> parseStatementList(String json)
// throws ParseException;;
// }
//
// Path: src/main/java/nl/uva/larissa/json/StatementPrinter.java
// public interface StatementPrinter {
// public String printStatement(Statement statement) throws IOException;
//
// public String print(StatementResult result) throws IOException;
//
// String printCompact(Object object) throws IOException;
//
// /**
// * print Statement as defined in xAPI spec 7.2.3 for parameter 'format' with
// * value 'ids'; Only print minimum info in Agent, Activity and Group Objects
// * necessary to identify them
// **/
// String printIds(Statement statement) throws IOException;
//
// public String printIds(StatementResult result) throws IOException;
// }
//
// Path: src/main/java/nl/uva/larissa/json/model/Agent.java
// @JsonInclude(Include.NON_NULL)
// public class Agent implements Actor, Authority, Instructor, StatementObject {
//
// private String objectType;
// private String name;
// @JsonUnwrapped
// @Valid
// @NotNull
// private IFI identifier;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public IFI getIdentifier() {
// return identifier;
// }
//
// public void setIdentifier(IFI identifier) {
// this.identifier = identifier;
// }
//
// public String getObjectType() {
// return objectType;
// }
//
// public void setObjectType(String objectType) {
// this.objectType = objectType;
// }
// }
// Path: src/main/java/nl/uva/larissa/service/AgentStringReaderProvider.java
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.inject.Inject;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import nl.uva.larissa.json.ParseException;
import nl.uva.larissa.json.StatementParser;
import nl.uva.larissa.json.StatementPrinter;
import nl.uva.larissa.json.model.Agent;
package nl.uva.larissa.service;
@Provider
public class AgentStringReaderProvider implements ParamConverterProvider {
@Inject
StatementParser parser;
@Inject
StatementPrinter printer;
@SuppressWarnings("unchecked")
@Override
public <T> ParamConverter<T> getConverter(Class<T> arg0, Type arg1,
Annotation[] arg2) {
if (arg1.equals(Agent.class)) {
return (ParamConverter<T>) new AgentParamConverter();
}
return null;
}
// TODO static class (but keep injection working?)
class AgentParamConverter implements ParamConverter<Agent> {
@Override
public Agent fromString(String arg0) {
try {
return parser.parse(Agent.class, arg0); | } catch (ParseException e) { |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/json/model/validate/IsUUIDValidator.java | // Path: src/main/java/nl/uva/larissa/UUIDUtil.java
// public class UUIDUtil {
// public static boolean isUUID(String string) {
// try {
// return UUID.fromString(string).toString().equals(string);
// } catch (IllegalArgumentException e) {
// return false;
// }
// }
// }
| import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import nl.uva.larissa.UUIDUtil; | package nl.uva.larissa.json.model.validate;
public class IsUUIDValidator implements ConstraintValidator<IsUUID, String> {
@Override
public void initialize(IsUUID constraintAnnotation) {
}
@Override
public boolean isValid(String string, ConstraintValidatorContext context) {
if (string == null) {
return true;
} | // Path: src/main/java/nl/uva/larissa/UUIDUtil.java
// public class UUIDUtil {
// public static boolean isUUID(String string) {
// try {
// return UUID.fromString(string).toString().equals(string);
// } catch (IllegalArgumentException e) {
// return false;
// }
// }
// }
// Path: src/main/java/nl/uva/larissa/json/model/validate/IsUUIDValidator.java
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import nl.uva.larissa.UUIDUtil;
package nl.uva.larissa.json.model.validate;
public class IsUUIDValidator implements ConstraintValidator<IsUUID, String> {
@Override
public void initialize(IsUUID constraintAnnotation) {
}
@Override
public boolean isValid(String string, ConstraintValidatorContext context) {
if (string == null) {
return true;
} | return UUIDUtil.isUUID(string); |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/repository/StatementRepository.java | // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/model/StatementResult.java
// public class StatementResult {
//
// private List<Statement> statements;
// // xAPI 1.0.1 4.2 Empty string if there are no more results to fetch
// private String more = "";
//
// @JsonIgnore
// private Date consistentThrough;
//
// public StatementResult(List<Statement> statements, Date consistentThrough) {
// this.statements = statements;
// this.consistentThrough = consistentThrough;
// }
//
// public Date getConsistentThrough() {
// return consistentThrough;
// }
//
// public void setConsistentThrough(Date consistentThrough) {
// this.consistentThrough = consistentThrough;
// }
//
// public List<Statement> getStatements() {
// return statements;
// }
//
// public void setStatements(List<Statement> statements) {
// this.statements = statements;
// }
//
// public String getMore() {
// return more;
// }
//
// public void setMore(String more) {
// this.more = more;
// }
// }
| import java.util.List;
import nl.uva.larissa.json.model.Statement;
import nl.uva.larissa.json.model.StatementResult; | package nl.uva.larissa.repository;
/**
* The interface for the Repository for storing and retrieving Statement objects
*
* @FIXME ugly side-effects on store-methods
*
*/
public interface StatementRepository {
/**
* Stores a Statement
*
* @param statement
* A valid Statement according to the xAPI 1.0.1 specification.
* Statement.id may be null to instruct the repository to
* generate an id instead.
* @return The id which may be used to reference the stored Statement.
* Should be the id of the original Statement if it was not null.
*
* @throws DuplicateIdException
* If statement.id has a value that is already in use.
*
* @throws VoidingTargetException
* If statement is voiding but refers to an invalid target for
* voiding
*
* @throws UnknownStatementException
* If statement.object.objectType=='StatementRef' and targets an
* unknown statement-id <br>
* <br>
* <b>side-effect</b> if Statement.id was null, Statement.id may
* be set to the return-value.
*
*
*/
public String storeStatement(Statement statement)
throws DuplicateIdException, VoidingTargetException,
UnknownStatementException;
/**
* Retrieves a Statement
*
* @param id
* UUID of the Statement to get.
* @return A StatementResult with 1 Statement, or with an empty list if no
* Statement with the given id exists or if the Statement is voided.
*/ | // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/model/StatementResult.java
// public class StatementResult {
//
// private List<Statement> statements;
// // xAPI 1.0.1 4.2 Empty string if there are no more results to fetch
// private String more = "";
//
// @JsonIgnore
// private Date consistentThrough;
//
// public StatementResult(List<Statement> statements, Date consistentThrough) {
// this.statements = statements;
// this.consistentThrough = consistentThrough;
// }
//
// public Date getConsistentThrough() {
// return consistentThrough;
// }
//
// public void setConsistentThrough(Date consistentThrough) {
// this.consistentThrough = consistentThrough;
// }
//
// public List<Statement> getStatements() {
// return statements;
// }
//
// public void setStatements(List<Statement> statements) {
// this.statements = statements;
// }
//
// public String getMore() {
// return more;
// }
//
// public void setMore(String more) {
// this.more = more;
// }
// }
// Path: src/main/java/nl/uva/larissa/repository/StatementRepository.java
import java.util.List;
import nl.uva.larissa.json.model.Statement;
import nl.uva.larissa.json.model.StatementResult;
package nl.uva.larissa.repository;
/**
* The interface for the Repository for storing and retrieving Statement objects
*
* @FIXME ugly side-effects on store-methods
*
*/
public interface StatementRepository {
/**
* Stores a Statement
*
* @param statement
* A valid Statement according to the xAPI 1.0.1 specification.
* Statement.id may be null to instruct the repository to
* generate an id instead.
* @return The id which may be used to reference the stored Statement.
* Should be the id of the original Statement if it was not null.
*
* @throws DuplicateIdException
* If statement.id has a value that is already in use.
*
* @throws VoidingTargetException
* If statement is voiding but refers to an invalid target for
* voiding
*
* @throws UnknownStatementException
* If statement.object.objectType=='StatementRef' and targets an
* unknown statement-id <br>
* <br>
* <b>side-effect</b> if Statement.id was null, Statement.id may
* be set to the return-value.
*
*
*/
public String storeStatement(Statement statement)
throws DuplicateIdException, VoidingTargetException,
UnknownStatementException;
/**
* Retrieves a Statement
*
* @param id
* UUID of the Statement to get.
* @return A StatementResult with 1 Statement, or with an empty list if no
* Statement with the given id exists or if the Statement is voided.
*/ | public StatementResult getStatement(String id); |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/CouchDbConnectorFactory.java | // Path: src/main/java/nl/uva/larissa/json/IRIDeserializer.java
// public final class IRIDeserializer extends JsonDeserializer<IRI> {
// @Override
// public IRI deserialize(JsonParser jsonparser,
// DeserializationContext deserializationcontext)
// throws IOException, JsonProcessingException {
// String value = jsonparser.readValueAs(String.class);
// return new IRI(value);
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/IRISerializer.java
// public final class IRISerializer extends JsonSerializer<IRI> {
// @Override
// public void serialize(IRI iri, JsonGenerator generator,
// SerializerProvider serializerProvider) throws IOException,
// JsonProcessingException {
// generator.writeString(iri.toString());
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/ISO8601VerboseDateFormat.java
// public class ISO8601VerboseDateFormat extends ISO8601DateFormat {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public StringBuffer format(Date date, StringBuffer stringbuffer,
// FieldPosition fieldposition) {
// String s = ISO8601Utils.format(date, true);
// stringbuffer.append(s);
// return stringbuffer;
// }
// }
| import java.net.MalformedURLException;
import nl.uva.larissa.json.IRIDeserializer;
import nl.uva.larissa.json.IRISerializer;
import nl.uva.larissa.json.ISO8601VerboseDateFormat;
import org.apache.abdera.i18n.iri.IRI;
import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;
import org.ektorp.impl.StreamingJsonSerializer;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule; | package nl.uva.larissa;
public class CouchDbConnectorFactory {
private static void applyMapperConfiguration(ObjectMapper mapper) {
// working around broken NON_NULL stuff in Ektorp/Jackson
// TODO report and/or check for update
mapper.setSerializationInclusion(Include.NON_NULL);
| // Path: src/main/java/nl/uva/larissa/json/IRIDeserializer.java
// public final class IRIDeserializer extends JsonDeserializer<IRI> {
// @Override
// public IRI deserialize(JsonParser jsonparser,
// DeserializationContext deserializationcontext)
// throws IOException, JsonProcessingException {
// String value = jsonparser.readValueAs(String.class);
// return new IRI(value);
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/IRISerializer.java
// public final class IRISerializer extends JsonSerializer<IRI> {
// @Override
// public void serialize(IRI iri, JsonGenerator generator,
// SerializerProvider serializerProvider) throws IOException,
// JsonProcessingException {
// generator.writeString(iri.toString());
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/ISO8601VerboseDateFormat.java
// public class ISO8601VerboseDateFormat extends ISO8601DateFormat {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public StringBuffer format(Date date, StringBuffer stringbuffer,
// FieldPosition fieldposition) {
// String s = ISO8601Utils.format(date, true);
// stringbuffer.append(s);
// return stringbuffer;
// }
// }
// Path: src/main/java/nl/uva/larissa/CouchDbConnectorFactory.java
import java.net.MalformedURLException;
import nl.uva.larissa.json.IRIDeserializer;
import nl.uva.larissa.json.IRISerializer;
import nl.uva.larissa.json.ISO8601VerboseDateFormat;
import org.apache.abdera.i18n.iri.IRI;
import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;
import org.ektorp.impl.StreamingJsonSerializer;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
package nl.uva.larissa;
public class CouchDbConnectorFactory {
private static void applyMapperConfiguration(ObjectMapper mapper) {
// working around broken NON_NULL stuff in Ektorp/Jackson
// TODO report and/or check for update
mapper.setSerializationInclusion(Include.NON_NULL);
| mapper.setDateFormat(new ISO8601VerboseDateFormat()); |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/CouchDbConnectorFactory.java | // Path: src/main/java/nl/uva/larissa/json/IRIDeserializer.java
// public final class IRIDeserializer extends JsonDeserializer<IRI> {
// @Override
// public IRI deserialize(JsonParser jsonparser,
// DeserializationContext deserializationcontext)
// throws IOException, JsonProcessingException {
// String value = jsonparser.readValueAs(String.class);
// return new IRI(value);
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/IRISerializer.java
// public final class IRISerializer extends JsonSerializer<IRI> {
// @Override
// public void serialize(IRI iri, JsonGenerator generator,
// SerializerProvider serializerProvider) throws IOException,
// JsonProcessingException {
// generator.writeString(iri.toString());
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/ISO8601VerboseDateFormat.java
// public class ISO8601VerboseDateFormat extends ISO8601DateFormat {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public StringBuffer format(Date date, StringBuffer stringbuffer,
// FieldPosition fieldposition) {
// String s = ISO8601Utils.format(date, true);
// stringbuffer.append(s);
// return stringbuffer;
// }
// }
| import java.net.MalformedURLException;
import nl.uva.larissa.json.IRIDeserializer;
import nl.uva.larissa.json.IRISerializer;
import nl.uva.larissa.json.ISO8601VerboseDateFormat;
import org.apache.abdera.i18n.iri.IRI;
import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;
import org.ektorp.impl.StreamingJsonSerializer;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule; | package nl.uva.larissa;
public class CouchDbConnectorFactory {
private static void applyMapperConfiguration(ObjectMapper mapper) {
// working around broken NON_NULL stuff in Ektorp/Jackson
// TODO report and/or check for update
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.setDateFormat(new ISO8601VerboseDateFormat());
SimpleModule module = new SimpleModule(); | // Path: src/main/java/nl/uva/larissa/json/IRIDeserializer.java
// public final class IRIDeserializer extends JsonDeserializer<IRI> {
// @Override
// public IRI deserialize(JsonParser jsonparser,
// DeserializationContext deserializationcontext)
// throws IOException, JsonProcessingException {
// String value = jsonparser.readValueAs(String.class);
// return new IRI(value);
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/IRISerializer.java
// public final class IRISerializer extends JsonSerializer<IRI> {
// @Override
// public void serialize(IRI iri, JsonGenerator generator,
// SerializerProvider serializerProvider) throws IOException,
// JsonProcessingException {
// generator.writeString(iri.toString());
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/ISO8601VerboseDateFormat.java
// public class ISO8601VerboseDateFormat extends ISO8601DateFormat {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public StringBuffer format(Date date, StringBuffer stringbuffer,
// FieldPosition fieldposition) {
// String s = ISO8601Utils.format(date, true);
// stringbuffer.append(s);
// return stringbuffer;
// }
// }
// Path: src/main/java/nl/uva/larissa/CouchDbConnectorFactory.java
import java.net.MalformedURLException;
import nl.uva.larissa.json.IRIDeserializer;
import nl.uva.larissa.json.IRISerializer;
import nl.uva.larissa.json.ISO8601VerboseDateFormat;
import org.apache.abdera.i18n.iri.IRI;
import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;
import org.ektorp.impl.StreamingJsonSerializer;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
package nl.uva.larissa;
public class CouchDbConnectorFactory {
private static void applyMapperConfiguration(ObjectMapper mapper) {
// working around broken NON_NULL stuff in Ektorp/Jackson
// TODO report and/or check for update
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.setDateFormat(new ISO8601VerboseDateFormat());
SimpleModule module = new SimpleModule(); | module.addSerializer(IRI.class, new IRISerializer()); |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/CouchDbConnectorFactory.java | // Path: src/main/java/nl/uva/larissa/json/IRIDeserializer.java
// public final class IRIDeserializer extends JsonDeserializer<IRI> {
// @Override
// public IRI deserialize(JsonParser jsonparser,
// DeserializationContext deserializationcontext)
// throws IOException, JsonProcessingException {
// String value = jsonparser.readValueAs(String.class);
// return new IRI(value);
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/IRISerializer.java
// public final class IRISerializer extends JsonSerializer<IRI> {
// @Override
// public void serialize(IRI iri, JsonGenerator generator,
// SerializerProvider serializerProvider) throws IOException,
// JsonProcessingException {
// generator.writeString(iri.toString());
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/ISO8601VerboseDateFormat.java
// public class ISO8601VerboseDateFormat extends ISO8601DateFormat {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public StringBuffer format(Date date, StringBuffer stringbuffer,
// FieldPosition fieldposition) {
// String s = ISO8601Utils.format(date, true);
// stringbuffer.append(s);
// return stringbuffer;
// }
// }
| import java.net.MalformedURLException;
import nl.uva.larissa.json.IRIDeserializer;
import nl.uva.larissa.json.IRISerializer;
import nl.uva.larissa.json.ISO8601VerboseDateFormat;
import org.apache.abdera.i18n.iri.IRI;
import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;
import org.ektorp.impl.StreamingJsonSerializer;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule; | package nl.uva.larissa;
public class CouchDbConnectorFactory {
private static void applyMapperConfiguration(ObjectMapper mapper) {
// working around broken NON_NULL stuff in Ektorp/Jackson
// TODO report and/or check for update
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.setDateFormat(new ISO8601VerboseDateFormat());
SimpleModule module = new SimpleModule();
module.addSerializer(IRI.class, new IRISerializer()); | // Path: src/main/java/nl/uva/larissa/json/IRIDeserializer.java
// public final class IRIDeserializer extends JsonDeserializer<IRI> {
// @Override
// public IRI deserialize(JsonParser jsonparser,
// DeserializationContext deserializationcontext)
// throws IOException, JsonProcessingException {
// String value = jsonparser.readValueAs(String.class);
// return new IRI(value);
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/IRISerializer.java
// public final class IRISerializer extends JsonSerializer<IRI> {
// @Override
// public void serialize(IRI iri, JsonGenerator generator,
// SerializerProvider serializerProvider) throws IOException,
// JsonProcessingException {
// generator.writeString(iri.toString());
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/ISO8601VerboseDateFormat.java
// public class ISO8601VerboseDateFormat extends ISO8601DateFormat {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public StringBuffer format(Date date, StringBuffer stringbuffer,
// FieldPosition fieldposition) {
// String s = ISO8601Utils.format(date, true);
// stringbuffer.append(s);
// return stringbuffer;
// }
// }
// Path: src/main/java/nl/uva/larissa/CouchDbConnectorFactory.java
import java.net.MalformedURLException;
import nl.uva.larissa.json.IRIDeserializer;
import nl.uva.larissa.json.IRISerializer;
import nl.uva.larissa.json.ISO8601VerboseDateFormat;
import org.apache.abdera.i18n.iri.IRI;
import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;
import org.ektorp.impl.StreamingJsonSerializer;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
package nl.uva.larissa;
public class CouchDbConnectorFactory {
private static void applyMapperConfiguration(ObjectMapper mapper) {
// working around broken NON_NULL stuff in Ektorp/Jackson
// TODO report and/or check for update
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.setDateFormat(new ISO8601VerboseDateFormat());
SimpleModule module = new SimpleModule();
module.addSerializer(IRI.class, new IRISerializer()); | module.addDeserializer(IRI.class, new IRIDeserializer()); |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/json/StatementParser.java | // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/main/java/nl/uva/larissa/repository/couchdb/StatementDocument.java
// public class StatementDocument extends CouchDbDocument {
//
// public static enum Type {
// PLAIN, VOIDED
// }
//
// /**
// *
// */
// private static final long serialVersionUID = 1533055980737805979L;
//
// @JsonUnwrapped
// private Statement statement;
//
// private Type type = Type.PLAIN;
//
// private List<StatementDocument> referrers = new ArrayList<>();
//
// public List<StatementDocument> getReferrers() {
// return referrers;
// }
//
// public void setReferrers(List<StatementDocument> referrers) {
// this.referrers = referrers;
// }
//
// public Statement getStatement() {
// return statement;
// }
//
// public void setStatement(Statement statement) {
// this.statement = statement;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// }
| import java.util.List;
import org.jvnet.hk2.annotations.Contract;
import nl.uva.larissa.json.model.Statement;
import nl.uva.larissa.repository.couchdb.StatementDocument; | package nl.uva.larissa.json;
@Contract
public interface StatementParser { | // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/main/java/nl/uva/larissa/repository/couchdb/StatementDocument.java
// public class StatementDocument extends CouchDbDocument {
//
// public static enum Type {
// PLAIN, VOIDED
// }
//
// /**
// *
// */
// private static final long serialVersionUID = 1533055980737805979L;
//
// @JsonUnwrapped
// private Statement statement;
//
// private Type type = Type.PLAIN;
//
// private List<StatementDocument> referrers = new ArrayList<>();
//
// public List<StatementDocument> getReferrers() {
// return referrers;
// }
//
// public void setReferrers(List<StatementDocument> referrers) {
// this.referrers = referrers;
// }
//
// public Statement getStatement() {
// return statement;
// }
//
// public void setStatement(Statement statement) {
// this.statement = statement;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// }
// Path: src/main/java/nl/uva/larissa/json/StatementParser.java
import java.util.List;
import org.jvnet.hk2.annotations.Contract;
import nl.uva.larissa.json.model.Statement;
import nl.uva.larissa.repository.couchdb.StatementDocument;
package nl.uva.larissa.json;
@Contract
public interface StatementParser { | public Statement parseStatement(String json) throws ParseException; |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/json/StatementParser.java | // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/main/java/nl/uva/larissa/repository/couchdb/StatementDocument.java
// public class StatementDocument extends CouchDbDocument {
//
// public static enum Type {
// PLAIN, VOIDED
// }
//
// /**
// *
// */
// private static final long serialVersionUID = 1533055980737805979L;
//
// @JsonUnwrapped
// private Statement statement;
//
// private Type type = Type.PLAIN;
//
// private List<StatementDocument> referrers = new ArrayList<>();
//
// public List<StatementDocument> getReferrers() {
// return referrers;
// }
//
// public void setReferrers(List<StatementDocument> referrers) {
// this.referrers = referrers;
// }
//
// public Statement getStatement() {
// return statement;
// }
//
// public void setStatement(Statement statement) {
// this.statement = statement;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// }
| import java.util.List;
import org.jvnet.hk2.annotations.Contract;
import nl.uva.larissa.json.model.Statement;
import nl.uva.larissa.repository.couchdb.StatementDocument; | package nl.uva.larissa.json;
@Contract
public interface StatementParser {
public Statement parseStatement(String json) throws ParseException;
| // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/main/java/nl/uva/larissa/repository/couchdb/StatementDocument.java
// public class StatementDocument extends CouchDbDocument {
//
// public static enum Type {
// PLAIN, VOIDED
// }
//
// /**
// *
// */
// private static final long serialVersionUID = 1533055980737805979L;
//
// @JsonUnwrapped
// private Statement statement;
//
// private Type type = Type.PLAIN;
//
// private List<StatementDocument> referrers = new ArrayList<>();
//
// public List<StatementDocument> getReferrers() {
// return referrers;
// }
//
// public void setReferrers(List<StatementDocument> referrers) {
// this.referrers = referrers;
// }
//
// public Statement getStatement() {
// return statement;
// }
//
// public void setStatement(Statement statement) {
// this.statement = statement;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// }
// Path: src/main/java/nl/uva/larissa/json/StatementParser.java
import java.util.List;
import org.jvnet.hk2.annotations.Contract;
import nl.uva.larissa.json.model.Statement;
import nl.uva.larissa.repository.couchdb.StatementDocument;
package nl.uva.larissa.json;
@Contract
public interface StatementParser {
public Statement parseStatement(String json) throws ParseException;
| public StatementDocument parseStatementDocument(String doc) |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/repository/couchdb/StatementDocument.java | // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import nl.uva.larissa.json.model.Statement;
import org.ektorp.support.CouchDbDocument;
import com.fasterxml.jackson.annotation.JsonUnwrapped; | package nl.uva.larissa.repository.couchdb;
public class StatementDocument extends CouchDbDocument {
public static enum Type {
PLAIN, VOIDED
}
/**
*
*/
private static final long serialVersionUID = 1533055980737805979L;
@JsonUnwrapped | // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
// Path: src/main/java/nl/uva/larissa/repository/couchdb/StatementDocument.java
import java.util.ArrayList;
import java.util.List;
import nl.uva.larissa.json.model.Statement;
import org.ektorp.support.CouchDbDocument;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
package nl.uva.larissa.repository.couchdb;
public class StatementDocument extends CouchDbDocument {
public static enum Type {
PLAIN, VOIDED
}
/**
*
*/
private static final long serialVersionUID = 1533055980737805979L;
@JsonUnwrapped | private Statement statement; |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/json/StatementParserImpl.java | // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/main/java/nl/uva/larissa/repository/couchdb/StatementDocument.java
// public class StatementDocument extends CouchDbDocument {
//
// public static enum Type {
// PLAIN, VOIDED
// }
//
// /**
// *
// */
// private static final long serialVersionUID = 1533055980737805979L;
//
// @JsonUnwrapped
// private Statement statement;
//
// private Type type = Type.PLAIN;
//
// private List<StatementDocument> referrers = new ArrayList<>();
//
// public List<StatementDocument> getReferrers() {
// return referrers;
// }
//
// public void setReferrers(List<StatementDocument> referrers) {
// this.referrers = referrers;
// }
//
// public Statement getStatement() {
// return statement;
// }
//
// public void setStatement(Statement statement) {
// this.statement = statement;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// }
| import java.io.IOException;
import java.util.List;
import org.apache.abdera.i18n.iri.IRI;
import nl.uva.larissa.json.model.Statement;
import nl.uva.larissa.repository.couchdb.StatementDocument;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule; | package nl.uva.larissa.json;
public class StatementParserImpl implements StatementParser {
final private ObjectMapper mapper;
public StatementParserImpl() {
this.mapper = new ObjectMapper();
// FIXME Jackson doesn't seem to give an error on a missing property on
// the level of an ActivityDefinition. This is potentially risky as a
// statement will
// be accepted yet stored incomplete. bug in Jackson?
// TODO make this configure less general? (meant for only
// ContextActivities)
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
true);
SimpleModule module = new SimpleModule();
module.addDeserializer(IRI.class, new IRIDeserializer());
mapper.registerModule(module);
}
@Override | // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/main/java/nl/uva/larissa/repository/couchdb/StatementDocument.java
// public class StatementDocument extends CouchDbDocument {
//
// public static enum Type {
// PLAIN, VOIDED
// }
//
// /**
// *
// */
// private static final long serialVersionUID = 1533055980737805979L;
//
// @JsonUnwrapped
// private Statement statement;
//
// private Type type = Type.PLAIN;
//
// private List<StatementDocument> referrers = new ArrayList<>();
//
// public List<StatementDocument> getReferrers() {
// return referrers;
// }
//
// public void setReferrers(List<StatementDocument> referrers) {
// this.referrers = referrers;
// }
//
// public Statement getStatement() {
// return statement;
// }
//
// public void setStatement(Statement statement) {
// this.statement = statement;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// }
// Path: src/main/java/nl/uva/larissa/json/StatementParserImpl.java
import java.io.IOException;
import java.util.List;
import org.apache.abdera.i18n.iri.IRI;
import nl.uva.larissa.json.model.Statement;
import nl.uva.larissa.repository.couchdb.StatementDocument;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
package nl.uva.larissa.json;
public class StatementParserImpl implements StatementParser {
final private ObjectMapper mapper;
public StatementParserImpl() {
this.mapper = new ObjectMapper();
// FIXME Jackson doesn't seem to give an error on a missing property on
// the level of an ActivityDefinition. This is potentially risky as a
// statement will
// be accepted yet stored incomplete. bug in Jackson?
// TODO make this configure less general? (meant for only
// ContextActivities)
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
true);
SimpleModule module = new SimpleModule();
module.addDeserializer(IRI.class, new IRIDeserializer());
mapper.registerModule(module);
}
@Override | public Statement parseStatement(String json) throws ParseException { |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/json/StatementParserImpl.java | // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/main/java/nl/uva/larissa/repository/couchdb/StatementDocument.java
// public class StatementDocument extends CouchDbDocument {
//
// public static enum Type {
// PLAIN, VOIDED
// }
//
// /**
// *
// */
// private static final long serialVersionUID = 1533055980737805979L;
//
// @JsonUnwrapped
// private Statement statement;
//
// private Type type = Type.PLAIN;
//
// private List<StatementDocument> referrers = new ArrayList<>();
//
// public List<StatementDocument> getReferrers() {
// return referrers;
// }
//
// public void setReferrers(List<StatementDocument> referrers) {
// this.referrers = referrers;
// }
//
// public Statement getStatement() {
// return statement;
// }
//
// public void setStatement(Statement statement) {
// this.statement = statement;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// }
| import java.io.IOException;
import java.util.List;
import org.apache.abdera.i18n.iri.IRI;
import nl.uva.larissa.json.model.Statement;
import nl.uva.larissa.repository.couchdb.StatementDocument;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule; | package nl.uva.larissa.json;
public class StatementParserImpl implements StatementParser {
final private ObjectMapper mapper;
public StatementParserImpl() {
this.mapper = new ObjectMapper();
// FIXME Jackson doesn't seem to give an error on a missing property on
// the level of an ActivityDefinition. This is potentially risky as a
// statement will
// be accepted yet stored incomplete. bug in Jackson?
// TODO make this configure less general? (meant for only
// ContextActivities)
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
true);
SimpleModule module = new SimpleModule();
module.addDeserializer(IRI.class, new IRIDeserializer());
mapper.registerModule(module);
}
@Override
public Statement parseStatement(String json) throws ParseException {
try {
Statement result = mapper.readValue(json, Statement.class);
if (result == null) {
throw new ParseException("no data");
}
return result;
} catch (IOException e) {
throw new ParseException(e);
}
}
@Override | // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/main/java/nl/uva/larissa/repository/couchdb/StatementDocument.java
// public class StatementDocument extends CouchDbDocument {
//
// public static enum Type {
// PLAIN, VOIDED
// }
//
// /**
// *
// */
// private static final long serialVersionUID = 1533055980737805979L;
//
// @JsonUnwrapped
// private Statement statement;
//
// private Type type = Type.PLAIN;
//
// private List<StatementDocument> referrers = new ArrayList<>();
//
// public List<StatementDocument> getReferrers() {
// return referrers;
// }
//
// public void setReferrers(List<StatementDocument> referrers) {
// this.referrers = referrers;
// }
//
// public Statement getStatement() {
// return statement;
// }
//
// public void setStatement(Statement statement) {
// this.statement = statement;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// }
// Path: src/main/java/nl/uva/larissa/json/StatementParserImpl.java
import java.io.IOException;
import java.util.List;
import org.apache.abdera.i18n.iri.IRI;
import nl.uva.larissa.json.model.Statement;
import nl.uva.larissa.repository.couchdb.StatementDocument;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
package nl.uva.larissa.json;
public class StatementParserImpl implements StatementParser {
final private ObjectMapper mapper;
public StatementParserImpl() {
this.mapper = new ObjectMapper();
// FIXME Jackson doesn't seem to give an error on a missing property on
// the level of an ActivityDefinition. This is potentially risky as a
// statement will
// be accepted yet stored incomplete. bug in Jackson?
// TODO make this configure less general? (meant for only
// ContextActivities)
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
true);
SimpleModule module = new SimpleModule();
module.addDeserializer(IRI.class, new IRIDeserializer());
mapper.registerModule(module);
}
@Override
public Statement parseStatement(String json) throws ParseException {
try {
Statement result = mapper.readValue(json, Statement.class);
if (result == null) {
throw new ParseException("no data");
}
return result;
} catch (IOException e) {
throw new ParseException(e);
}
}
@Override | public StatementDocument parseStatementDocument(String json) |
Apereo-Learning-Analytics-Initiative/Larissa | src/test/java/nl/uva/larissa/json/TestStatementParser.java | // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/test/java/nl/uva/test/Util.java
// public class Util {
// public static String readJsonFile(File textFile) throws IOException {
// try (BufferedReader reader = new BufferedReader(
// new FileReader(textFile))) {
// final StringBuilder result = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// line = line.replaceAll(" ", "");
// result.append(line);
// }
// return result.toString();
// }
// }
// }
| import static org.junit.Assert.*;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import nl.uva.larissa.json.model.Statement;
import nl.uva.test.Util;
import org.junit.BeforeClass;
import org.junit.Test; | package nl.uva.larissa.json;
public class TestStatementParser {
private static StatementParser parser;
private static StatementPrinter printer;
private static File testFileDir = new File("src/test/resources/");
private static File expectedOutputDir = new File(
"src/test/resources/expected/");
private static Validator validator;
@BeforeClass
public static void beforeClass() {
parser = new StatementParserImpl();
printer = new StatementPrinterImpl();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void testParser() throws IOException {
File[] testFiles = testFileDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith("json");
}
});
for (File testFile : testFiles) {
String jsonInput;
| // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/test/java/nl/uva/test/Util.java
// public class Util {
// public static String readJsonFile(File textFile) throws IOException {
// try (BufferedReader reader = new BufferedReader(
// new FileReader(textFile))) {
// final StringBuilder result = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// line = line.replaceAll(" ", "");
// result.append(line);
// }
// return result.toString();
// }
// }
// }
// Path: src/test/java/nl/uva/larissa/json/TestStatementParser.java
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import nl.uva.larissa.json.model.Statement;
import nl.uva.test.Util;
import org.junit.BeforeClass;
import org.junit.Test;
package nl.uva.larissa.json;
public class TestStatementParser {
private static StatementParser parser;
private static StatementPrinter printer;
private static File testFileDir = new File("src/test/resources/");
private static File expectedOutputDir = new File(
"src/test/resources/expected/");
private static Validator validator;
@BeforeClass
public static void beforeClass() {
parser = new StatementParserImpl();
printer = new StatementPrinterImpl();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void testParser() throws IOException {
File[] testFiles = testFileDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith("json");
}
});
for (File testFile : testFiles) {
String jsonInput;
| jsonInput = Util.readJsonFile(testFile); |
Apereo-Learning-Analytics-Initiative/Larissa | src/test/java/nl/uva/larissa/json/TestStatementParser.java | // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/test/java/nl/uva/test/Util.java
// public class Util {
// public static String readJsonFile(File textFile) throws IOException {
// try (BufferedReader reader = new BufferedReader(
// new FileReader(textFile))) {
// final StringBuilder result = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// line = line.replaceAll(" ", "");
// result.append(line);
// }
// return result.toString();
// }
// }
// }
| import static org.junit.Assert.*;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import nl.uva.larissa.json.model.Statement;
import nl.uva.test.Util;
import org.junit.BeforeClass;
import org.junit.Test; | package nl.uva.larissa.json;
public class TestStatementParser {
private static StatementParser parser;
private static StatementPrinter printer;
private static File testFileDir = new File("src/test/resources/");
private static File expectedOutputDir = new File(
"src/test/resources/expected/");
private static Validator validator;
@BeforeClass
public static void beforeClass() {
parser = new StatementParserImpl();
printer = new StatementPrinterImpl();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void testParser() throws IOException {
File[] testFiles = testFileDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith("json");
}
});
for (File testFile : testFiles) {
String jsonInput;
jsonInput = Util.readJsonFile(testFile);
| // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/test/java/nl/uva/test/Util.java
// public class Util {
// public static String readJsonFile(File textFile) throws IOException {
// try (BufferedReader reader = new BufferedReader(
// new FileReader(textFile))) {
// final StringBuilder result = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// line = line.replaceAll(" ", "");
// result.append(line);
// }
// return result.toString();
// }
// }
// }
// Path: src/test/java/nl/uva/larissa/json/TestStatementParser.java
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import nl.uva.larissa.json.model.Statement;
import nl.uva.test.Util;
import org.junit.BeforeClass;
import org.junit.Test;
package nl.uva.larissa.json;
public class TestStatementParser {
private static StatementParser parser;
private static StatementPrinter printer;
private static File testFileDir = new File("src/test/resources/");
private static File expectedOutputDir = new File(
"src/test/resources/expected/");
private static Validator validator;
@BeforeClass
public static void beforeClass() {
parser = new StatementParserImpl();
printer = new StatementPrinterImpl();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void testParser() throws IOException {
File[] testFiles = testFileDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith("json");
}
});
for (File testFile : testFiles) {
String jsonInput;
jsonInput = Util.readJsonFile(testFile);
| Statement statement; |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/service/DateParamConverterProvider.java | // Path: src/main/java/nl/uva/larissa/json/ISO8601VerboseDateFormat.java
// public class ISO8601VerboseDateFormat extends ISO8601DateFormat {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public StringBuffer format(Date date, StringBuffer stringbuffer,
// FieldPosition fieldposition) {
// String s = ISO8601Utils.format(date, true);
// stringbuffer.append(s);
// return stringbuffer;
// }
// }
| import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import nl.uva.larissa.json.ISO8601VerboseDateFormat; | package nl.uva.larissa.service;
@Provider
public class DateParamConverterProvider implements ParamConverterProvider {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public ParamConverter getConverter(Class arg0, Type arg1, Annotation[] arg2) {
if (arg1.equals(Date.class)) {
return new DateParamConverter();
} else {
return null;
}
}
private static class DateParamConverter implements ParamConverter<Date> {
// TODO is this threadsafe? | // Path: src/main/java/nl/uva/larissa/json/ISO8601VerboseDateFormat.java
// public class ISO8601VerboseDateFormat extends ISO8601DateFormat {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public StringBuffer format(Date date, StringBuffer stringbuffer,
// FieldPosition fieldposition) {
// String s = ISO8601Utils.format(date, true);
// stringbuffer.append(s);
// return stringbuffer;
// }
// }
// Path: src/main/java/nl/uva/larissa/service/DateParamConverterProvider.java
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import nl.uva.larissa.json.ISO8601VerboseDateFormat;
package nl.uva.larissa.service;
@Provider
public class DateParamConverterProvider implements ParamConverterProvider {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public ParamConverter getConverter(Class arg0, Type arg1, Annotation[] arg2) {
if (arg1.equals(Date.class)) {
return new DateParamConverter();
} else {
return null;
}
}
private static class DateParamConverter implements ParamConverter<Date> {
// TODO is this threadsafe? | final DateFormat format = new ISO8601VerboseDateFormat(); |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/repository/couchdb/QueryResolver.java | // Path: src/main/java/nl/uva/larissa/repository/StatementFilter.java
// public class StatementFilter {
//
// private String statementId;
// private String voidedStatementId;
// // TODO or Identified Group!
// private Agent agent;
// private IRI verb;
// private IRI activity;
// // UUID
// private String registration;
// private Boolean relatedActivities;
// private Boolean relatedAgents;
// private Date since;
// private Date until;
// private Integer limit;
// // TODO enum?
// private String format;
// private Boolean ascending;
//
// // for more-URL
// @QueryParam("startId")
// private String startId;
//
// public StatementFilter() {
// }
//
// public StatementFilter(StatementFilter filter) {
// statementId = filter.getStatementId();
// voidedStatementId = filter.getVoidedStatementid();
// agent = filter.getAgent();
// verb = filter.getVerb();
// activity = filter.getActivity();
// registration = filter.getRegistration();
// relatedActivities = filter.getRelatedActivities();
// relatedAgents = filter.getRelatedAgents();
// since = filter.getSince();
// until = filter.getUntil();
// limit = filter.getLimit();
// format = filter.getFormat();
// ascending= filter.getAscending();
// startId = filter.getStartId();
// }
//
// public String getStatementId() {
// return statementId;
// }
//
// public void setStatementId(String statementId) {
// this.statementId = statementId;
// }
//
// public String getVoidedStatementid() {
// return voidedStatementId;
// }
//
// public void setVoidedStatementid(String voidedStatementId) {
// this.voidedStatementId = voidedStatementId;
// }
//
// public Agent getAgent() {
// return agent;
// }
//
// public void setAgent(Agent agent) {
// this.agent = agent;
// }
//
// public IRI getVerb() {
// return verb;
// }
//
// public void setVerb(IRI verb) {
// this.verb = verb;
// }
//
// public IRI getActivity() {
// return activity;
// }
//
// public void setActivity(IRI activity) {
// this.activity = activity;
// }
//
// public String getRegistration() {
// return registration;
// }
//
// public void setRegistration(String registration) {
// this.registration = registration;
// }
//
// public Boolean getRelatedActivities() {
// return relatedActivities;
// }
//
// public void setRelatedActivities(Boolean relatedActivities) {
// this.relatedActivities = relatedActivities;
// }
//
// public Boolean getRelatedAgents() {
// return relatedAgents;
// }
//
// public void setRelatedAgents(Boolean relatedAgents) {
// this.relatedAgents = relatedAgents;
// }
//
// public String getVoidedStatementId() {
// return voidedStatementId;
// }
//
// @Override
// public String toString() {
// return "StatementFilter [statementId=" + statementId
// + ", voidedStatementId=" + voidedStatementId + ", agent="
// + agent + ", verb=" + verb + ", activity=" + activity
// + ", registration=" + registration + ", relatedActivities="
// + relatedActivities + ", relatedAgents=" + relatedAgents
// + ", since=" + since + ", until=" + until + ", limit=" + limit
// + ", format=" + format + ", ascending=" + ascending
// + ", startId=" + startId + "]";
// }
//
// public void setVoidedStatementId(String voidedStatementId) {
// this.voidedStatementId = voidedStatementId;
// }
//
// public Date getSince() {
// return since;
// }
//
// public void setSince(Date since) {
// this.since = since;
// }
//
// public Date getUntil() {
// return until;
// }
//
// public void setUntil(Date until) {
// this.until = until;
// }
//
// public Integer getLimit() {
// return limit;
// }
//
// public void setLimit(Integer limit) {
// this.limit = limit;
// }
//
// public String getFormat() {
// return format;
// }
//
// public void setFormat(String format) {
// this.format = format;
// }
//
// public String getStartId() {
// return startId;
// }
//
// public void setStartId(String startId) {
// this.startId = startId;
// }
//
// public Boolean getAscending() {
// return ascending;
// }
//
// public void setAscending(Boolean ascending) {
// this.ascending = ascending;
// }
//
// }
| import nl.uva.larissa.repository.StatementFilter; | package nl.uva.larissa.repository.couchdb;
public class QueryResolver implements IQueryResolver {
static String DESIGN_ID = "_design/statements";
@Override | // Path: src/main/java/nl/uva/larissa/repository/StatementFilter.java
// public class StatementFilter {
//
// private String statementId;
// private String voidedStatementId;
// // TODO or Identified Group!
// private Agent agent;
// private IRI verb;
// private IRI activity;
// // UUID
// private String registration;
// private Boolean relatedActivities;
// private Boolean relatedAgents;
// private Date since;
// private Date until;
// private Integer limit;
// // TODO enum?
// private String format;
// private Boolean ascending;
//
// // for more-URL
// @QueryParam("startId")
// private String startId;
//
// public StatementFilter() {
// }
//
// public StatementFilter(StatementFilter filter) {
// statementId = filter.getStatementId();
// voidedStatementId = filter.getVoidedStatementid();
// agent = filter.getAgent();
// verb = filter.getVerb();
// activity = filter.getActivity();
// registration = filter.getRegistration();
// relatedActivities = filter.getRelatedActivities();
// relatedAgents = filter.getRelatedAgents();
// since = filter.getSince();
// until = filter.getUntil();
// limit = filter.getLimit();
// format = filter.getFormat();
// ascending= filter.getAscending();
// startId = filter.getStartId();
// }
//
// public String getStatementId() {
// return statementId;
// }
//
// public void setStatementId(String statementId) {
// this.statementId = statementId;
// }
//
// public String getVoidedStatementid() {
// return voidedStatementId;
// }
//
// public void setVoidedStatementid(String voidedStatementId) {
// this.voidedStatementId = voidedStatementId;
// }
//
// public Agent getAgent() {
// return agent;
// }
//
// public void setAgent(Agent agent) {
// this.agent = agent;
// }
//
// public IRI getVerb() {
// return verb;
// }
//
// public void setVerb(IRI verb) {
// this.verb = verb;
// }
//
// public IRI getActivity() {
// return activity;
// }
//
// public void setActivity(IRI activity) {
// this.activity = activity;
// }
//
// public String getRegistration() {
// return registration;
// }
//
// public void setRegistration(String registration) {
// this.registration = registration;
// }
//
// public Boolean getRelatedActivities() {
// return relatedActivities;
// }
//
// public void setRelatedActivities(Boolean relatedActivities) {
// this.relatedActivities = relatedActivities;
// }
//
// public Boolean getRelatedAgents() {
// return relatedAgents;
// }
//
// public void setRelatedAgents(Boolean relatedAgents) {
// this.relatedAgents = relatedAgents;
// }
//
// public String getVoidedStatementId() {
// return voidedStatementId;
// }
//
// @Override
// public String toString() {
// return "StatementFilter [statementId=" + statementId
// + ", voidedStatementId=" + voidedStatementId + ", agent="
// + agent + ", verb=" + verb + ", activity=" + activity
// + ", registration=" + registration + ", relatedActivities="
// + relatedActivities + ", relatedAgents=" + relatedAgents
// + ", since=" + since + ", until=" + until + ", limit=" + limit
// + ", format=" + format + ", ascending=" + ascending
// + ", startId=" + startId + "]";
// }
//
// public void setVoidedStatementId(String voidedStatementId) {
// this.voidedStatementId = voidedStatementId;
// }
//
// public Date getSince() {
// return since;
// }
//
// public void setSince(Date since) {
// this.since = since;
// }
//
// public Date getUntil() {
// return until;
// }
//
// public void setUntil(Date until) {
// this.until = until;
// }
//
// public Integer getLimit() {
// return limit;
// }
//
// public void setLimit(Integer limit) {
// this.limit = limit;
// }
//
// public String getFormat() {
// return format;
// }
//
// public void setFormat(String format) {
// this.format = format;
// }
//
// public String getStartId() {
// return startId;
// }
//
// public void setStartId(String startId) {
// this.startId = startId;
// }
//
// public Boolean getAscending() {
// return ascending;
// }
//
// public void setAscending(Boolean ascending) {
// this.ascending = ascending;
// }
//
// }
// Path: src/main/java/nl/uva/larissa/repository/couchdb/QueryResolver.java
import nl.uva.larissa.repository.StatementFilter;
package nl.uva.larissa.repository.couchdb;
public class QueryResolver implements IQueryResolver {
static String DESIGN_ID = "_design/statements";
@Override | public StatementResultQuery resolve(StatementFilter filter) { |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/json/model/validate/ValidGroupValidator.java | // Path: src/main/java/nl/uva/larissa/json/model/Agent.java
// @JsonInclude(Include.NON_NULL)
// public class Agent implements Actor, Authority, Instructor, StatementObject {
//
// private String objectType;
// private String name;
// @JsonUnwrapped
// @Valid
// @NotNull
// private IFI identifier;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public IFI getIdentifier() {
// return identifier;
// }
//
// public void setIdentifier(IFI identifier) {
// this.identifier = identifier;
// }
//
// public String getObjectType() {
// return objectType;
// }
//
// public void setObjectType(String objectType) {
// this.objectType = objectType;
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/model/Group.java
// @ValidGroup
// public class Group implements Actor {
//
// private String objectType;
// private String name;
// @Valid
// private List<Agent> member;
//
// @JsonUnwrapped
// @Valid
// private IFI identifier;
//
// public String getObjectType() {
// return objectType;
// }
//
// public void setObjectType(String objectType) {
// this.objectType = objectType;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<Agent> getMember() {
// return member;
// }
//
// public void setMember(List<Agent> member) {
// this.member = member;
// }
//
// public IFI getIdentifier() {
// return identifier;
// }
//
// public void setIdentifier(IFI identifier) {
// this.identifier = identifier;
// }
//
// }
| import java.util.List;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import nl.uva.larissa.json.model.Agent;
import nl.uva.larissa.json.model.Group; | package nl.uva.larissa.json.model.validate;
public class ValidGroupValidator implements
ConstraintValidator<ValidGroup, Group> {
@Override
public void initialize(ValidGroup constraintAnnotation) {
}
@Override
public boolean isValid(Group group, ConstraintValidatorContext context) {
if (group.getIdentifier() == null) { | // Path: src/main/java/nl/uva/larissa/json/model/Agent.java
// @JsonInclude(Include.NON_NULL)
// public class Agent implements Actor, Authority, Instructor, StatementObject {
//
// private String objectType;
// private String name;
// @JsonUnwrapped
// @Valid
// @NotNull
// private IFI identifier;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public IFI getIdentifier() {
// return identifier;
// }
//
// public void setIdentifier(IFI identifier) {
// this.identifier = identifier;
// }
//
// public String getObjectType() {
// return objectType;
// }
//
// public void setObjectType(String objectType) {
// this.objectType = objectType;
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/model/Group.java
// @ValidGroup
// public class Group implements Actor {
//
// private String objectType;
// private String name;
// @Valid
// private List<Agent> member;
//
// @JsonUnwrapped
// @Valid
// private IFI identifier;
//
// public String getObjectType() {
// return objectType;
// }
//
// public void setObjectType(String objectType) {
// this.objectType = objectType;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<Agent> getMember() {
// return member;
// }
//
// public void setMember(List<Agent> member) {
// this.member = member;
// }
//
// public IFI getIdentifier() {
// return identifier;
// }
//
// public void setIdentifier(IFI identifier) {
// this.identifier = identifier;
// }
//
// }
// Path: src/main/java/nl/uva/larissa/json/model/validate/ValidGroupValidator.java
import java.util.List;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import nl.uva.larissa.json.model.Agent;
import nl.uva.larissa.json.model.Group;
package nl.uva.larissa.json.model.validate;
public class ValidGroupValidator implements
ConstraintValidator<ValidGroup, Group> {
@Override
public void initialize(ValidGroup constraintAnnotation) {
}
@Override
public boolean isValid(Group group, ConstraintValidatorContext context) {
if (group.getIdentifier() == null) { | List<Agent> members = group.getMember(); |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/json/StatementPrinter.java | // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/model/StatementResult.java
// public class StatementResult {
//
// private List<Statement> statements;
// // xAPI 1.0.1 4.2 Empty string if there are no more results to fetch
// private String more = "";
//
// @JsonIgnore
// private Date consistentThrough;
//
// public StatementResult(List<Statement> statements, Date consistentThrough) {
// this.statements = statements;
// this.consistentThrough = consistentThrough;
// }
//
// public Date getConsistentThrough() {
// return consistentThrough;
// }
//
// public void setConsistentThrough(Date consistentThrough) {
// this.consistentThrough = consistentThrough;
// }
//
// public List<Statement> getStatements() {
// return statements;
// }
//
// public void setStatements(List<Statement> statements) {
// this.statements = statements;
// }
//
// public String getMore() {
// return more;
// }
//
// public void setMore(String more) {
// this.more = more;
// }
// }
| import java.io.IOException;
import nl.uva.larissa.json.model.Statement;
import nl.uva.larissa.json.model.StatementResult; | package nl.uva.larissa.json;
public interface StatementPrinter {
public String printStatement(Statement statement) throws IOException;
| // Path: src/main/java/nl/uva/larissa/json/model/Statement.java
// @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context",
// "timestamp", "stored", "authority", "version" })
// @ValidRevisionUsage
// @ValidPlatformUsage
// public class Statement {
// @JsonProperty(required = false)
// @IsUUID
// private String id;
// @NotNull
// @Valid
// private Actor actor;
// @NotNull
// @Valid
// private Verb verb;
// @NotNull
// @Valid
// @JsonProperty("object")
// private StatementObject statementObject;
// private Result result;
// @Valid
// private Context context;
// // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it
// // is outside of a Sub-Statement.
// @Past
// private Date timestamp;
//
// // should be set by the LRS, not the client
// @Null
// private Date stored;
// private Authority authority;
// private String version;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Actor getActor() {
// return actor;
// }
//
// public void setActor(Actor actor) {
// this.actor = actor;
// }
//
// public Verb getVerb() {
// return verb;
// }
//
// public void setVerb(Verb verb) {
// this.verb = verb;
// }
//
// public StatementObject getStatementObject() {
// return statementObject;
// }
//
// public void setStatementObject(StatementObject statementObject) {
// this.statementObject = statementObject;
// }
//
// public Result getResult() {
// return result;
// }
//
// public void setResult(Result result) {
// this.result = result;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
//
// public Date getStored() {
// return stored;
// }
//
// public void setStored(Date stored) {
// this.stored = stored;
// }
//
// public Authority getAuthority() {
// return authority;
// }
//
// public void setAuthority(Authority authority) {
// this.authority = authority;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
// }
//
// Path: src/main/java/nl/uva/larissa/json/model/StatementResult.java
// public class StatementResult {
//
// private List<Statement> statements;
// // xAPI 1.0.1 4.2 Empty string if there are no more results to fetch
// private String more = "";
//
// @JsonIgnore
// private Date consistentThrough;
//
// public StatementResult(List<Statement> statements, Date consistentThrough) {
// this.statements = statements;
// this.consistentThrough = consistentThrough;
// }
//
// public Date getConsistentThrough() {
// return consistentThrough;
// }
//
// public void setConsistentThrough(Date consistentThrough) {
// this.consistentThrough = consistentThrough;
// }
//
// public List<Statement> getStatements() {
// return statements;
// }
//
// public void setStatements(List<Statement> statements) {
// this.statements = statements;
// }
//
// public String getMore() {
// return more;
// }
//
// public void setMore(String more) {
// this.more = more;
// }
// }
// Path: src/main/java/nl/uva/larissa/json/StatementPrinter.java
import java.io.IOException;
import nl.uva.larissa.json.model.Statement;
import nl.uva.larissa.json.model.StatementResult;
package nl.uva.larissa.json;
public interface StatementPrinter {
public String printStatement(Statement statement) throws IOException;
| public String print(StatementResult result) throws IOException; |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/service/AboutResource.java | // Path: src/main/java/nl/uva/larissa/json/model/About.java
// public class About {
// List<String> version;
// private Map<IRI, Object> extensions;
//
// public List<String> getVersion() {
// return version;
// }
//
// public void setVersion(List<String> version) {
// this.version = version;
// }
//
// public Map<IRI, Object> getExtensions() {
// return extensions;
// }
//
// public void setExtensions(Map<IRI, Object> extensions) {
// this.extensions = extensions;
// }
//
// }
| import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import nl.uva.larissa.json.model.About;
import org.apache.abdera.i18n.iri.IRI; | package nl.uva.larissa.service;
@Path("/xAPI/about")
public class AboutResource {
@GET
public Response getAbout() { | // Path: src/main/java/nl/uva/larissa/json/model/About.java
// public class About {
// List<String> version;
// private Map<IRI, Object> extensions;
//
// public List<String> getVersion() {
// return version;
// }
//
// public void setVersion(List<String> version) {
// this.version = version;
// }
//
// public Map<IRI, Object> getExtensions() {
// return extensions;
// }
//
// public void setExtensions(Map<IRI, Object> extensions) {
// this.extensions = extensions;
// }
//
// }
// Path: src/main/java/nl/uva/larissa/service/AboutResource.java
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import nl.uva.larissa.json.model.About;
import org.apache.abdera.i18n.iri.IRI;
package nl.uva.larissa.service;
@Path("/xAPI/about")
public class AboutResource {
@GET
public Response getAbout() { | About about = new About(); |
Apereo-Learning-Analytics-Initiative/Larissa | src/main/java/nl/uva/larissa/repository/StatementFilter.java | // Path: src/main/java/nl/uva/larissa/json/model/Agent.java
// @JsonInclude(Include.NON_NULL)
// public class Agent implements Actor, Authority, Instructor, StatementObject {
//
// private String objectType;
// private String name;
// @JsonUnwrapped
// @Valid
// @NotNull
// private IFI identifier;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public IFI getIdentifier() {
// return identifier;
// }
//
// public void setIdentifier(IFI identifier) {
// this.identifier = identifier;
// }
//
// public String getObjectType() {
// return objectType;
// }
//
// public void setObjectType(String objectType) {
// this.objectType = objectType;
// }
// }
| import nl.uva.larissa.json.model.Agent;
import java.util.Date;
import javax.ws.rs.QueryParam;
import org.apache.abdera.i18n.iri.IRI; | package nl.uva.larissa.repository;
public class StatementFilter {
private String statementId;
private String voidedStatementId;
// TODO or Identified Group! | // Path: src/main/java/nl/uva/larissa/json/model/Agent.java
// @JsonInclude(Include.NON_NULL)
// public class Agent implements Actor, Authority, Instructor, StatementObject {
//
// private String objectType;
// private String name;
// @JsonUnwrapped
// @Valid
// @NotNull
// private IFI identifier;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public IFI getIdentifier() {
// return identifier;
// }
//
// public void setIdentifier(IFI identifier) {
// this.identifier = identifier;
// }
//
// public String getObjectType() {
// return objectType;
// }
//
// public void setObjectType(String objectType) {
// this.objectType = objectType;
// }
// }
// Path: src/main/java/nl/uva/larissa/repository/StatementFilter.java
import nl.uva.larissa.json.model.Agent;
import java.util.Date;
import javax.ws.rs.QueryParam;
import org.apache.abdera.i18n.iri.IRI;
package nl.uva.larissa.repository;
public class StatementFilter {
private String statementId;
private String voidedStatementId;
// TODO or Identified Group! | private Agent agent; |
liaozhoubei/NetEasyNews | channelmanager/src/main/java/com/example/channelmanager/ItemDragHelperCallback.java | // Path: channelmanager/src/main/java/com/example/channelmanager/base/ItemDragListener.java
// public interface ItemDragListener {
// void onItemMove(int fromPosition, int toPosition);
//
// void onItemSwiped(int position);
// }
//
// Path: channelmanager/src/main/java/com/example/channelmanager/base/ItemDragVHListener.java
// public interface ItemDragVHListener {
// void onItemSelected();
//
// void onItemFinished();
// }
| import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import com.example.channelmanager.base.ItemDragListener;
import com.example.channelmanager.base.ItemDragVHListener; |
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags;
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager instanceof GridLayoutManager || layoutManager instanceof StaggeredGridLayoutManager) {
dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.START | ItemTouchHelper.END;
} else {
dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
}
int swipeFlags = 0;
return makeMovementFlags(dragFlags, swipeFlags);
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) {
if (source.getItemViewType() != target.getItemViewType())
return false;
mDragMoveListener.onItemMove(source.getAdapterPosition(), target.getAdapterPosition());
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) {
mDragMoveListener.onItemSwiped(viewHolder.getAdapterPosition());
}
@Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) { | // Path: channelmanager/src/main/java/com/example/channelmanager/base/ItemDragListener.java
// public interface ItemDragListener {
// void onItemMove(int fromPosition, int toPosition);
//
// void onItemSwiped(int position);
// }
//
// Path: channelmanager/src/main/java/com/example/channelmanager/base/ItemDragVHListener.java
// public interface ItemDragVHListener {
// void onItemSelected();
//
// void onItemFinished();
// }
// Path: channelmanager/src/main/java/com/example/channelmanager/ItemDragHelperCallback.java
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import com.example.channelmanager.base.ItemDragListener;
import com.example.channelmanager.base.ItemDragVHListener;
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags;
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager instanceof GridLayoutManager || layoutManager instanceof StaggeredGridLayoutManager) {
dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.START | ItemTouchHelper.END;
} else {
dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
}
int swipeFlags = 0;
return makeMovementFlags(dragFlags, swipeFlags);
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) {
if (source.getItemViewType() != target.getItemViewType())
return false;
mDragMoveListener.onItemMove(source.getAdapterPosition(), target.getAdapterPosition());
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) {
mDragMoveListener.onItemSwiped(viewHolder.getAdapterPosition());
}
@Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) { | ItemDragVHListener itemViewHolder = (ItemDragVHListener) viewHolder; |
liaozhoubei/NetEasyNews | app/src/main/java/cn/bproject/neteasynews/Utils/LocalCacheUtils.java | // Path: app/src/main/java/cn/bproject/neteasynews/Utils/MD5Encoder.java
// public static String hashKeyForDisk(String key) {
// String cacheKey;
// try {
// final MessageDigest mDigest = MessageDigest.getInstance("MD5");
// mDigest.update(key.getBytes());
// cacheKey = bytesToHexString(mDigest.digest());
// } catch (NoSuchAlgorithmException e) {
// cacheKey = String.valueOf(key.hashCode());
// }
// return cacheKey;
// }
| import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import static cn.bproject.neteasynews.Utils.MD5Encoder.hashKeyForDisk; | package cn.bproject.neteasynews.Utils;
/**
* Created by Administrator on 2016/12/8.
* 设置本地缓存
*/
public class LocalCacheUtils {
private static final String TAG = LocalCacheUtils.class.getSimpleName();
/**
* @param url 传入获取信息的网址,作为保存缓存的文件名
* @param content 传入要缓存的信息
*/
public static void setDiskLruCache(String url, String content) {
Context context = UIUtils.getContext();
DiskLruCache mDiskLruCache = null;
try {
File cacheDir = getDiskCacheDir(context, "news");
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
mDiskLruCache = DiskLruCache.open(cacheDir, getAppVersion(context), 1, 10 * 1024 * 1024);
| // Path: app/src/main/java/cn/bproject/neteasynews/Utils/MD5Encoder.java
// public static String hashKeyForDisk(String key) {
// String cacheKey;
// try {
// final MessageDigest mDigest = MessageDigest.getInstance("MD5");
// mDigest.update(key.getBytes());
// cacheKey = bytesToHexString(mDigest.digest());
// } catch (NoSuchAlgorithmException e) {
// cacheKey = String.valueOf(key.hashCode());
// }
// return cacheKey;
// }
// Path: app/src/main/java/cn/bproject/neteasynews/Utils/LocalCacheUtils.java
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import static cn.bproject.neteasynews.Utils.MD5Encoder.hashKeyForDisk;
package cn.bproject.neteasynews.Utils;
/**
* Created by Administrator on 2016/12/8.
* 设置本地缓存
*/
public class LocalCacheUtils {
private static final String TAG = LocalCacheUtils.class.getSimpleName();
/**
* @param url 传入获取信息的网址,作为保存缓存的文件名
* @param content 传入要缓存的信息
*/
public static void setDiskLruCache(String url, String content) {
Context context = UIUtils.getContext();
DiskLruCache mDiskLruCache = null;
try {
File cacheDir = getDiskCacheDir(context, "news");
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
mDiskLruCache = DiskLruCache.open(cacheDir, getAppVersion(context), 1, 10 * 1024 * 1024);
| String key = hashKeyForDisk(url); |
liaozhoubei/NetEasyNews | app/src/main/java/cn/bproject/neteasynews/Utils/ToastUtils.java | // Path: app/src/main/java/cn/bproject/neteasynews/MyApplication.java
// public class MyApplication extends Application {
// private static int mainThreadId;
// private static Handler handler;
// private static Context mContext;
// private static ThreadManager.ThreadPool mThreadPool;
//
// // private static MyApplication sMyApplication;
//
//
// public void setThreadPool(ThreadManager.ThreadPool threadPool) {
// mThreadPool = threadPool;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// mContext = getApplicationContext();
// handler = new Handler();
// mainThreadId = android.os.Process.myTid();
// mThreadPool = ThreadManager.getThreadPool();
//
// initBugly();
//
//
// }
//
// /**
// * 初始化bugly
// */
// private void initBugly() {
// // 获取当前包名
// String packageName = mContext.getPackageName();
// // 获取当前进程名
// String processName = getProcessName(android.os.Process.myPid());
// // 设置是否为上报进程
// CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(mContext);
// strategy.setUploadProcess(processName == null || processName.equals(packageName));
// CrashReport.initCrashReport(getApplicationContext(), "7a544c9222", false);
// }
//
// /**
// * 获取进程号对应的进程名
// *
// * @param pid 进程号
// * @return 进程名
// */
// private static String getProcessName(int pid) {
// BufferedReader reader = null;
// try {
// reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
// String processName = reader.readLine();
// if (!TextUtils.isEmpty(processName)) {
// processName = processName.trim();
// }
// return processName;
// } catch (Throwable throwable) {
// throwable.printStackTrace();
// } finally {
// try {
// if (reader != null) {
// reader.close();
// }
// } catch (IOException exception) {
// exception.printStackTrace();
// }
// }
// return null;
// }
//
//
// // public static MyApplication getInstance() {
// // // if语句下是不会走的,Application本身已单例
// // if (sMyApplication == null) {
// // synchronized (MyApplication.class) {
// // if (sMyApplication == null) {
// // sMyApplication = new MyApplication();
// // }
// // }
// // }
// // return sMyApplication;
// // }
//
//
// public static Context getContext() {
// return mContext;
// }
//
// public static Handler getHandler() {
// return handler;
// }
//
//
// public static int getMainThreadId() {
// return mainThreadId;
// }
//
// public static ThreadManager.ThreadPool getThreadPool() {
// return mThreadPool;
// }
// }
| import android.text.TextUtils;
import android.widget.Toast;
import cn.bproject.neteasynews.MyApplication; | package cn.bproject.neteasynews.Utils;
/**
* Created by Administrator on 2017/2/20.
*/
public class ToastUtils {
public static void showLong(String value){
if (!TextUtils.isEmpty(value)){ | // Path: app/src/main/java/cn/bproject/neteasynews/MyApplication.java
// public class MyApplication extends Application {
// private static int mainThreadId;
// private static Handler handler;
// private static Context mContext;
// private static ThreadManager.ThreadPool mThreadPool;
//
// // private static MyApplication sMyApplication;
//
//
// public void setThreadPool(ThreadManager.ThreadPool threadPool) {
// mThreadPool = threadPool;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// mContext = getApplicationContext();
// handler = new Handler();
// mainThreadId = android.os.Process.myTid();
// mThreadPool = ThreadManager.getThreadPool();
//
// initBugly();
//
//
// }
//
// /**
// * 初始化bugly
// */
// private void initBugly() {
// // 获取当前包名
// String packageName = mContext.getPackageName();
// // 获取当前进程名
// String processName = getProcessName(android.os.Process.myPid());
// // 设置是否为上报进程
// CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(mContext);
// strategy.setUploadProcess(processName == null || processName.equals(packageName));
// CrashReport.initCrashReport(getApplicationContext(), "7a544c9222", false);
// }
//
// /**
// * 获取进程号对应的进程名
// *
// * @param pid 进程号
// * @return 进程名
// */
// private static String getProcessName(int pid) {
// BufferedReader reader = null;
// try {
// reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
// String processName = reader.readLine();
// if (!TextUtils.isEmpty(processName)) {
// processName = processName.trim();
// }
// return processName;
// } catch (Throwable throwable) {
// throwable.printStackTrace();
// } finally {
// try {
// if (reader != null) {
// reader.close();
// }
// } catch (IOException exception) {
// exception.printStackTrace();
// }
// }
// return null;
// }
//
//
// // public static MyApplication getInstance() {
// // // if语句下是不会走的,Application本身已单例
// // if (sMyApplication == null) {
// // synchronized (MyApplication.class) {
// // if (sMyApplication == null) {
// // sMyApplication = new MyApplication();
// // }
// // }
// // }
// // return sMyApplication;
// // }
//
//
// public static Context getContext() {
// return mContext;
// }
//
// public static Handler getHandler() {
// return handler;
// }
//
//
// public static int getMainThreadId() {
// return mainThreadId;
// }
//
// public static ThreadManager.ThreadPool getThreadPool() {
// return mThreadPool;
// }
// }
// Path: app/src/main/java/cn/bproject/neteasynews/Utils/ToastUtils.java
import android.text.TextUtils;
import android.widget.Toast;
import cn.bproject.neteasynews.MyApplication;
package cn.bproject.neteasynews.Utils;
/**
* Created by Administrator on 2017/2/20.
*/
public class ToastUtils {
public static void showLong(String value){
if (!TextUtils.isEmpty(value)){ | Toast.makeText(MyApplication.getContext(), value, Toast.LENGTH_LONG).show(); |
liaozhoubei/NetEasyNews | library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/internal/FlipLoadingLayout.java | // Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Mode {
//
// /**
// * Disable all Pull-to-Refresh gesture and Refreshing handling
// */
// DISABLED(0x0),
//
// /**
// * Only allow the user to Pull from the start of the Refreshable View to
// * refresh. The start is either the Top or Left, depending on the
// * scrolling direction.
// */
// PULL_FROM_START(0x1),
//
// /**
// * Only allow the user to Pull from the end of the Refreshable View to
// * refresh. The start is either the Bottom or Right, depending on the
// * scrolling direction.
// */
// PULL_FROM_END(0x2),
//
// /**
// * Allow the user to both Pull from the start, from the end to refresh.
// */
// BOTH(0x3),
//
// /**
// * Disables Pull-to-Refresh gesture handling, but allows manually
// * setting the Refresh state via
// * {@link PullToRefreshBase#setRefreshing() setRefreshing()}.
// */
// MANUAL_REFRESH_ONLY(0x4);
//
// /**
// * @deprecated Use {@link #PULL_FROM_START} from now on.
// */
// public static Mode PULL_DOWN_TO_REFRESH = Mode.PULL_FROM_START;
//
// /**
// * @deprecated Use {@link #PULL_FROM_END} from now on.
// */
// public static Mode PULL_UP_TO_REFRESH = Mode.PULL_FROM_END;
//
// /**
// * Maps an int to a specific mode. This is needed when saving state, or
// * inflating the view from XML where the mode is given through a attr
// * int.
// *
// * @param modeInt - int to map a Mode to
// * @return Mode that modeInt maps to, or PULL_FROM_START by default.
// */
// static Mode mapIntToValue(final int modeInt) {
// for (Mode value : Mode.values()) {
// if (modeInt == value.getIntValue()) {
// return value;
// }
// }
//
// // If not, return default
// return getDefault();
// }
//
// static Mode getDefault() {
// return PULL_FROM_START;
// }
//
// private int mIntValue;
//
// // The modeInt values need to match those from attrs.xml
// Mode(int modeInt) {
// mIntValue = modeInt;
// }
//
// /**
// * @return true if the mode permits Pull-to-Refresh
// */
// boolean permitsPullToRefresh() {
// return !(this == DISABLED || this == MANUAL_REFRESH_ONLY);
// }
//
// /**
// * @return true if this mode wants the Loading Layout Header to be shown
// */
// public boolean showHeaderLoadingLayout() {
// return this == PULL_FROM_START || this == BOTH;
// }
//
// /**
// * @return true if this mode wants the Loading Layout Footer to be shown
// */
// public boolean showFooterLoadingLayout() {
// return this == PULL_FROM_END || this == BOTH || this == MANUAL_REFRESH_ONLY;
// }
//
// int getIntValue() {
// return mIntValue;
// }
//
// }
//
// Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Orientation {
// VERTICAL, HORIZONTAL;
// }
| import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView.ScaleType;
import com.handmark.pulltorefresh.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.PullToRefreshBase.Orientation;
import com.handmark.pulltorefresh.R; | /*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.handmark.pulltorefresh.internal;
@SuppressLint("ViewConstructor")
public class FlipLoadingLayout extends LoadingLayout {
static final int FLIP_ANIMATION_DURATION = 150;
private final Animation mRotateAnimation, mResetRotateAnimation;
| // Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Mode {
//
// /**
// * Disable all Pull-to-Refresh gesture and Refreshing handling
// */
// DISABLED(0x0),
//
// /**
// * Only allow the user to Pull from the start of the Refreshable View to
// * refresh. The start is either the Top or Left, depending on the
// * scrolling direction.
// */
// PULL_FROM_START(0x1),
//
// /**
// * Only allow the user to Pull from the end of the Refreshable View to
// * refresh. The start is either the Bottom or Right, depending on the
// * scrolling direction.
// */
// PULL_FROM_END(0x2),
//
// /**
// * Allow the user to both Pull from the start, from the end to refresh.
// */
// BOTH(0x3),
//
// /**
// * Disables Pull-to-Refresh gesture handling, but allows manually
// * setting the Refresh state via
// * {@link PullToRefreshBase#setRefreshing() setRefreshing()}.
// */
// MANUAL_REFRESH_ONLY(0x4);
//
// /**
// * @deprecated Use {@link #PULL_FROM_START} from now on.
// */
// public static Mode PULL_DOWN_TO_REFRESH = Mode.PULL_FROM_START;
//
// /**
// * @deprecated Use {@link #PULL_FROM_END} from now on.
// */
// public static Mode PULL_UP_TO_REFRESH = Mode.PULL_FROM_END;
//
// /**
// * Maps an int to a specific mode. This is needed when saving state, or
// * inflating the view from XML where the mode is given through a attr
// * int.
// *
// * @param modeInt - int to map a Mode to
// * @return Mode that modeInt maps to, or PULL_FROM_START by default.
// */
// static Mode mapIntToValue(final int modeInt) {
// for (Mode value : Mode.values()) {
// if (modeInt == value.getIntValue()) {
// return value;
// }
// }
//
// // If not, return default
// return getDefault();
// }
//
// static Mode getDefault() {
// return PULL_FROM_START;
// }
//
// private int mIntValue;
//
// // The modeInt values need to match those from attrs.xml
// Mode(int modeInt) {
// mIntValue = modeInt;
// }
//
// /**
// * @return true if the mode permits Pull-to-Refresh
// */
// boolean permitsPullToRefresh() {
// return !(this == DISABLED || this == MANUAL_REFRESH_ONLY);
// }
//
// /**
// * @return true if this mode wants the Loading Layout Header to be shown
// */
// public boolean showHeaderLoadingLayout() {
// return this == PULL_FROM_START || this == BOTH;
// }
//
// /**
// * @return true if this mode wants the Loading Layout Footer to be shown
// */
// public boolean showFooterLoadingLayout() {
// return this == PULL_FROM_END || this == BOTH || this == MANUAL_REFRESH_ONLY;
// }
//
// int getIntValue() {
// return mIntValue;
// }
//
// }
//
// Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Orientation {
// VERTICAL, HORIZONTAL;
// }
// Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/internal/FlipLoadingLayout.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView.ScaleType;
import com.handmark.pulltorefresh.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.PullToRefreshBase.Orientation;
import com.handmark.pulltorefresh.R;
/*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.handmark.pulltorefresh.internal;
@SuppressLint("ViewConstructor")
public class FlipLoadingLayout extends LoadingLayout {
static final int FLIP_ANIMATION_DURATION = 150;
private final Animation mRotateAnimation, mResetRotateAnimation;
| public FlipLoadingLayout(Context context, final Mode mode, final Orientation scrollDirection, TypedArray attrs) { |
liaozhoubei/NetEasyNews | library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/internal/FlipLoadingLayout.java | // Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Mode {
//
// /**
// * Disable all Pull-to-Refresh gesture and Refreshing handling
// */
// DISABLED(0x0),
//
// /**
// * Only allow the user to Pull from the start of the Refreshable View to
// * refresh. The start is either the Top or Left, depending on the
// * scrolling direction.
// */
// PULL_FROM_START(0x1),
//
// /**
// * Only allow the user to Pull from the end of the Refreshable View to
// * refresh. The start is either the Bottom or Right, depending on the
// * scrolling direction.
// */
// PULL_FROM_END(0x2),
//
// /**
// * Allow the user to both Pull from the start, from the end to refresh.
// */
// BOTH(0x3),
//
// /**
// * Disables Pull-to-Refresh gesture handling, but allows manually
// * setting the Refresh state via
// * {@link PullToRefreshBase#setRefreshing() setRefreshing()}.
// */
// MANUAL_REFRESH_ONLY(0x4);
//
// /**
// * @deprecated Use {@link #PULL_FROM_START} from now on.
// */
// public static Mode PULL_DOWN_TO_REFRESH = Mode.PULL_FROM_START;
//
// /**
// * @deprecated Use {@link #PULL_FROM_END} from now on.
// */
// public static Mode PULL_UP_TO_REFRESH = Mode.PULL_FROM_END;
//
// /**
// * Maps an int to a specific mode. This is needed when saving state, or
// * inflating the view from XML where the mode is given through a attr
// * int.
// *
// * @param modeInt - int to map a Mode to
// * @return Mode that modeInt maps to, or PULL_FROM_START by default.
// */
// static Mode mapIntToValue(final int modeInt) {
// for (Mode value : Mode.values()) {
// if (modeInt == value.getIntValue()) {
// return value;
// }
// }
//
// // If not, return default
// return getDefault();
// }
//
// static Mode getDefault() {
// return PULL_FROM_START;
// }
//
// private int mIntValue;
//
// // The modeInt values need to match those from attrs.xml
// Mode(int modeInt) {
// mIntValue = modeInt;
// }
//
// /**
// * @return true if the mode permits Pull-to-Refresh
// */
// boolean permitsPullToRefresh() {
// return !(this == DISABLED || this == MANUAL_REFRESH_ONLY);
// }
//
// /**
// * @return true if this mode wants the Loading Layout Header to be shown
// */
// public boolean showHeaderLoadingLayout() {
// return this == PULL_FROM_START || this == BOTH;
// }
//
// /**
// * @return true if this mode wants the Loading Layout Footer to be shown
// */
// public boolean showFooterLoadingLayout() {
// return this == PULL_FROM_END || this == BOTH || this == MANUAL_REFRESH_ONLY;
// }
//
// int getIntValue() {
// return mIntValue;
// }
//
// }
//
// Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Orientation {
// VERTICAL, HORIZONTAL;
// }
| import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView.ScaleType;
import com.handmark.pulltorefresh.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.PullToRefreshBase.Orientation;
import com.handmark.pulltorefresh.R; | /*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.handmark.pulltorefresh.internal;
@SuppressLint("ViewConstructor")
public class FlipLoadingLayout extends LoadingLayout {
static final int FLIP_ANIMATION_DURATION = 150;
private final Animation mRotateAnimation, mResetRotateAnimation;
| // Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Mode {
//
// /**
// * Disable all Pull-to-Refresh gesture and Refreshing handling
// */
// DISABLED(0x0),
//
// /**
// * Only allow the user to Pull from the start of the Refreshable View to
// * refresh. The start is either the Top or Left, depending on the
// * scrolling direction.
// */
// PULL_FROM_START(0x1),
//
// /**
// * Only allow the user to Pull from the end of the Refreshable View to
// * refresh. The start is either the Bottom or Right, depending on the
// * scrolling direction.
// */
// PULL_FROM_END(0x2),
//
// /**
// * Allow the user to both Pull from the start, from the end to refresh.
// */
// BOTH(0x3),
//
// /**
// * Disables Pull-to-Refresh gesture handling, but allows manually
// * setting the Refresh state via
// * {@link PullToRefreshBase#setRefreshing() setRefreshing()}.
// */
// MANUAL_REFRESH_ONLY(0x4);
//
// /**
// * @deprecated Use {@link #PULL_FROM_START} from now on.
// */
// public static Mode PULL_DOWN_TO_REFRESH = Mode.PULL_FROM_START;
//
// /**
// * @deprecated Use {@link #PULL_FROM_END} from now on.
// */
// public static Mode PULL_UP_TO_REFRESH = Mode.PULL_FROM_END;
//
// /**
// * Maps an int to a specific mode. This is needed when saving state, or
// * inflating the view from XML where the mode is given through a attr
// * int.
// *
// * @param modeInt - int to map a Mode to
// * @return Mode that modeInt maps to, or PULL_FROM_START by default.
// */
// static Mode mapIntToValue(final int modeInt) {
// for (Mode value : Mode.values()) {
// if (modeInt == value.getIntValue()) {
// return value;
// }
// }
//
// // If not, return default
// return getDefault();
// }
//
// static Mode getDefault() {
// return PULL_FROM_START;
// }
//
// private int mIntValue;
//
// // The modeInt values need to match those from attrs.xml
// Mode(int modeInt) {
// mIntValue = modeInt;
// }
//
// /**
// * @return true if the mode permits Pull-to-Refresh
// */
// boolean permitsPullToRefresh() {
// return !(this == DISABLED || this == MANUAL_REFRESH_ONLY);
// }
//
// /**
// * @return true if this mode wants the Loading Layout Header to be shown
// */
// public boolean showHeaderLoadingLayout() {
// return this == PULL_FROM_START || this == BOTH;
// }
//
// /**
// * @return true if this mode wants the Loading Layout Footer to be shown
// */
// public boolean showFooterLoadingLayout() {
// return this == PULL_FROM_END || this == BOTH || this == MANUAL_REFRESH_ONLY;
// }
//
// int getIntValue() {
// return mIntValue;
// }
//
// }
//
// Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Orientation {
// VERTICAL, HORIZONTAL;
// }
// Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/internal/FlipLoadingLayout.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView.ScaleType;
import com.handmark.pulltorefresh.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.PullToRefreshBase.Orientation;
import com.handmark.pulltorefresh.R;
/*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.handmark.pulltorefresh.internal;
@SuppressLint("ViewConstructor")
public class FlipLoadingLayout extends LoadingLayout {
static final int FLIP_ANIMATION_DURATION = 150;
private final Animation mRotateAnimation, mResetRotateAnimation;
| public FlipLoadingLayout(Context context, final Mode mode, final Orientation scrollDirection, TypedArray attrs) { |
liaozhoubei/NetEasyNews | app/src/main/java/cn/bproject/neteasynews/adapter/PicListAdapter.java | // Path: app/src/main/java/cn/bproject/neteasynews/bean/PicListBean.java
// public class PicListBean {
//
// /**
// * desc : Hendo除了COS男版蜘蛛侠外更是挑战了一下原作中由蜘蛛侠女友温格所变身的女版蜘蛛,效果更是到位。女版蜘蛛侠会不会更厉害,更值得期待?
// * pvnum :
// * createdate : 2016-12-27 01:49:02
// * scover : http://img3.cache.netease.com/photo/0031/2016-12-27/s_C98O8VGL6LRK0031.jpg
// * setname : 女版蜘蛛侠会不会更厉害?值得期待!
// * cover : http://img4.cache.netease.com/photo/0031/2016-12-27/C98O8VGL6LRK0031.jpg
// * pics : ["http://img3.cache.netease.com/photo/0031/2016-12-27/C98O8UBL6LRK0031.jpg","http://img3.cache.netease.com/photo/0031/2016-12-27/C98O8UPE6LRK0031.jpg","http://img4.cache.netease.com/photo/0031/2016-12-27/C98O8UVI6LRK0031.jpg"]
// * clientcover1 :
// * replynum : 217
// * topicname :
// * setid : 91416
// * seturl : http://play.163.com/photoview/6LRK0031/91416.html
// * datetime : 2016-12-27 01:57:49
// * clientcover :
// * imgsum : 16
// * tcover : http://img4.cache.netease.com/photo/0031/2016-12-27/t_C98O8VGL6LRK0031.jpg
// */
//
// // private List<PicList> mPicLists;
// //
// // public List<PicList> getPicLists() {
// // return mPicLists;
// // }
// //
// // public void setPicLists(List<PicList> picLists) {
// // mPicLists = picLists;
// // }
// //
// // public class PicList{
// private String desc;
// // 创建时间
// private String createdate;
// private String setname;
// private String cover;
// private String setid;
// private String seturl;
// // 发布时间
// private String datetime;
// // 图片总数
// private String imgsum;
// private List<String> pics;
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public String getCreatedate() {
// return createdate;
// }
//
// public void setCreatedate(String createdate) {
// this.createdate = createdate;
// }
//
// public String getSetname() {
// return setname;
// }
//
// public void setSetname(String setname) {
// this.setname = setname;
// }
//
// public String getCover() {
// return cover;
// }
//
// public void setCover(String cover) {
// this.cover = cover;
// }
//
// public String getSetid() {
// return setid;
// }
//
// public void setSetid(String setid) {
// this.setid = setid;
// }
//
// public String getSeturl() {
// return seturl;
// }
//
// public void setSeturl(String seturl) {
// this.seturl = seturl;
// }
//
// public String getDatetime() {
// return datetime;
// }
//
// public void setDatetime(String datetime) {
// this.datetime = datetime;
// }
//
// public String getImgsum() {
// return imgsum;
// }
//
// public void setImgsum(String imgsum) {
// this.imgsum = imgsum;
// }
//
// public List<String> getPics() {
// return pics;
// }
//
// public void setPics(List<String> pics) {
// this.pics = pics;
// }
//
// @Override
// public String toString() {
// return "PicListBean{" +
// "setname='" + setname + '\'' +
// ", cover='" + cover + '\'' +
// ", createdate='" + createdate + '\'' +
// '}';
// }
//
//
// // }
//
//
//
//
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.aspsine.irecyclerview.IViewHolder;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import cn.bproject.neteasynews.R;
import cn.bproject.neteasynews.bean.PicListBean; | package cn.bproject.neteasynews.adapter;
/**
* Created by liaozhoubei on 2017/1/7.
*/
public class PicListAdapter extends RecyclerView.Adapter<PicListAdapter.ViewHolder> {
private Context mContext; | // Path: app/src/main/java/cn/bproject/neteasynews/bean/PicListBean.java
// public class PicListBean {
//
// /**
// * desc : Hendo除了COS男版蜘蛛侠外更是挑战了一下原作中由蜘蛛侠女友温格所变身的女版蜘蛛,效果更是到位。女版蜘蛛侠会不会更厉害,更值得期待?
// * pvnum :
// * createdate : 2016-12-27 01:49:02
// * scover : http://img3.cache.netease.com/photo/0031/2016-12-27/s_C98O8VGL6LRK0031.jpg
// * setname : 女版蜘蛛侠会不会更厉害?值得期待!
// * cover : http://img4.cache.netease.com/photo/0031/2016-12-27/C98O8VGL6LRK0031.jpg
// * pics : ["http://img3.cache.netease.com/photo/0031/2016-12-27/C98O8UBL6LRK0031.jpg","http://img3.cache.netease.com/photo/0031/2016-12-27/C98O8UPE6LRK0031.jpg","http://img4.cache.netease.com/photo/0031/2016-12-27/C98O8UVI6LRK0031.jpg"]
// * clientcover1 :
// * replynum : 217
// * topicname :
// * setid : 91416
// * seturl : http://play.163.com/photoview/6LRK0031/91416.html
// * datetime : 2016-12-27 01:57:49
// * clientcover :
// * imgsum : 16
// * tcover : http://img4.cache.netease.com/photo/0031/2016-12-27/t_C98O8VGL6LRK0031.jpg
// */
//
// // private List<PicList> mPicLists;
// //
// // public List<PicList> getPicLists() {
// // return mPicLists;
// // }
// //
// // public void setPicLists(List<PicList> picLists) {
// // mPicLists = picLists;
// // }
// //
// // public class PicList{
// private String desc;
// // 创建时间
// private String createdate;
// private String setname;
// private String cover;
// private String setid;
// private String seturl;
// // 发布时间
// private String datetime;
// // 图片总数
// private String imgsum;
// private List<String> pics;
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public String getCreatedate() {
// return createdate;
// }
//
// public void setCreatedate(String createdate) {
// this.createdate = createdate;
// }
//
// public String getSetname() {
// return setname;
// }
//
// public void setSetname(String setname) {
// this.setname = setname;
// }
//
// public String getCover() {
// return cover;
// }
//
// public void setCover(String cover) {
// this.cover = cover;
// }
//
// public String getSetid() {
// return setid;
// }
//
// public void setSetid(String setid) {
// this.setid = setid;
// }
//
// public String getSeturl() {
// return seturl;
// }
//
// public void setSeturl(String seturl) {
// this.seturl = seturl;
// }
//
// public String getDatetime() {
// return datetime;
// }
//
// public void setDatetime(String datetime) {
// this.datetime = datetime;
// }
//
// public String getImgsum() {
// return imgsum;
// }
//
// public void setImgsum(String imgsum) {
// this.imgsum = imgsum;
// }
//
// public List<String> getPics() {
// return pics;
// }
//
// public void setPics(List<String> pics) {
// this.pics = pics;
// }
//
// @Override
// public String toString() {
// return "PicListBean{" +
// "setname='" + setname + '\'' +
// ", cover='" + cover + '\'' +
// ", createdate='" + createdate + '\'' +
// '}';
// }
//
//
// // }
//
//
//
//
// }
// Path: app/src/main/java/cn/bproject/neteasynews/adapter/PicListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.aspsine.irecyclerview.IViewHolder;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import cn.bproject.neteasynews.R;
import cn.bproject.neteasynews.bean.PicListBean;
package cn.bproject.neteasynews.adapter;
/**
* Created by liaozhoubei on 2017/1/7.
*/
public class PicListAdapter extends RecyclerView.Adapter<PicListAdapter.ViewHolder> {
private Context mContext; | private ArrayList<PicListBean> mPicListBeens; |
liaozhoubei/NetEasyNews | app/src/main/java/cn/bproject/neteasynews/MyApplication.java | // Path: app/src/main/java/cn/bproject/neteasynews/Utils/ThreadManager.java
// public class ThreadManager {
//
// private static ThreadPool mThreadPool;
//
// /**
// * 创建线程池,使用单例模式,在Applicaiton中初始化
// * @return 返回线程池
// */
// public static ThreadPool getThreadPool() {
// if (mThreadPool == null) {
// synchronized (ThreadManager.class) {
// if (mThreadPool == null) {
// int cpuCount = Runtime.getRuntime().availableProcessors();// 获取cpu数量
// System.out.println("cup个数:" + cpuCount);
//
// // int threadCount = cpuCount * 2 + 1;//线程个数
// int threadCount = 10;
// mThreadPool = new ThreadPool(threadCount, threadCount, 1L);
// }
// }
// }
//
// return mThreadPool;
// }
//
// // 线程池
// public static class ThreadPool {
//
// private int corePoolSize;// 核心线程数
// private int maximumPoolSize;// 最大线程数
// private long keepAliveTime;// 休息时间
//
// private ThreadPoolExecutor executor;
//
// private ThreadPool(int corePoolSize, int maximumPoolSize,
// long keepAliveTime) {
// this.corePoolSize = corePoolSize;
// this.maximumPoolSize = maximumPoolSize;
// this.keepAliveTime = keepAliveTime;
// }
//
//
// public void execute(Runnable r) {
// if (executor == null) {
// executor = new ThreadPoolExecutor(corePoolSize,
// maximumPoolSize, keepAliveTime, TimeUnit.SECONDS,
// new LinkedBlockingQueue<Runnable>(),
// Executors.defaultThreadFactory(), new AbortPolicy());
// // 参1:核心线程数;参2:最大线程数;参3:线程休眠时间;参4:时间单位;参5:线程队列;参6:生产线程的工厂;参7:线程异常处理策略
// }
//
// // 线程池执行一个Runnable对象, 具体运行时机线程池说了算
// executor.execute(r);
// }
//
// // 取消任务
// public void cancel(Runnable r) {
// if (executor != null) {
// // 从线程队列中移除对象
// executor.getQueue().remove(r);
// }
// }
//
// }
// }
| import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import com.tencent.bugly.crashreport.CrashReport;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import cn.bproject.neteasynews.Utils.ThreadManager; | package cn.bproject.neteasynews;
/**
* Created by Bei on 2016/12/24.
*/
public class MyApplication extends Application {
private static int mainThreadId;
private static Handler handler;
private static Context mContext; | // Path: app/src/main/java/cn/bproject/neteasynews/Utils/ThreadManager.java
// public class ThreadManager {
//
// private static ThreadPool mThreadPool;
//
// /**
// * 创建线程池,使用单例模式,在Applicaiton中初始化
// * @return 返回线程池
// */
// public static ThreadPool getThreadPool() {
// if (mThreadPool == null) {
// synchronized (ThreadManager.class) {
// if (mThreadPool == null) {
// int cpuCount = Runtime.getRuntime().availableProcessors();// 获取cpu数量
// System.out.println("cup个数:" + cpuCount);
//
// // int threadCount = cpuCount * 2 + 1;//线程个数
// int threadCount = 10;
// mThreadPool = new ThreadPool(threadCount, threadCount, 1L);
// }
// }
// }
//
// return mThreadPool;
// }
//
// // 线程池
// public static class ThreadPool {
//
// private int corePoolSize;// 核心线程数
// private int maximumPoolSize;// 最大线程数
// private long keepAliveTime;// 休息时间
//
// private ThreadPoolExecutor executor;
//
// private ThreadPool(int corePoolSize, int maximumPoolSize,
// long keepAliveTime) {
// this.corePoolSize = corePoolSize;
// this.maximumPoolSize = maximumPoolSize;
// this.keepAliveTime = keepAliveTime;
// }
//
//
// public void execute(Runnable r) {
// if (executor == null) {
// executor = new ThreadPoolExecutor(corePoolSize,
// maximumPoolSize, keepAliveTime, TimeUnit.SECONDS,
// new LinkedBlockingQueue<Runnable>(),
// Executors.defaultThreadFactory(), new AbortPolicy());
// // 参1:核心线程数;参2:最大线程数;参3:线程休眠时间;参4:时间单位;参5:线程队列;参6:生产线程的工厂;参7:线程异常处理策略
// }
//
// // 线程池执行一个Runnable对象, 具体运行时机线程池说了算
// executor.execute(r);
// }
//
// // 取消任务
// public void cancel(Runnable r) {
// if (executor != null) {
// // 从线程队列中移除对象
// executor.getQueue().remove(r);
// }
// }
//
// }
// }
// Path: app/src/main/java/cn/bproject/neteasynews/MyApplication.java
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import com.tencent.bugly.crashreport.CrashReport;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import cn.bproject.neteasynews.Utils.ThreadManager;
package cn.bproject.neteasynews;
/**
* Created by Bei on 2016/12/24.
*/
public class MyApplication extends Application {
private static int mainThreadId;
private static Handler handler;
private static Context mContext; | private static ThreadManager.ThreadPool mThreadPool; |
liaozhoubei/NetEasyNews | library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/internal/RotateLoadingLayout.java | // Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Mode {
//
// /**
// * Disable all Pull-to-Refresh gesture and Refreshing handling
// */
// DISABLED(0x0),
//
// /**
// * Only allow the user to Pull from the start of the Refreshable View to
// * refresh. The start is either the Top or Left, depending on the
// * scrolling direction.
// */
// PULL_FROM_START(0x1),
//
// /**
// * Only allow the user to Pull from the end of the Refreshable View to
// * refresh. The start is either the Bottom or Right, depending on the
// * scrolling direction.
// */
// PULL_FROM_END(0x2),
//
// /**
// * Allow the user to both Pull from the start, from the end to refresh.
// */
// BOTH(0x3),
//
// /**
// * Disables Pull-to-Refresh gesture handling, but allows manually
// * setting the Refresh state via
// * {@link PullToRefreshBase#setRefreshing() setRefreshing()}.
// */
// MANUAL_REFRESH_ONLY(0x4);
//
// /**
// * @deprecated Use {@link #PULL_FROM_START} from now on.
// */
// public static Mode PULL_DOWN_TO_REFRESH = Mode.PULL_FROM_START;
//
// /**
// * @deprecated Use {@link #PULL_FROM_END} from now on.
// */
// public static Mode PULL_UP_TO_REFRESH = Mode.PULL_FROM_END;
//
// /**
// * Maps an int to a specific mode. This is needed when saving state, or
// * inflating the view from XML where the mode is given through a attr
// * int.
// *
// * @param modeInt - int to map a Mode to
// * @return Mode that modeInt maps to, or PULL_FROM_START by default.
// */
// static Mode mapIntToValue(final int modeInt) {
// for (Mode value : Mode.values()) {
// if (modeInt == value.getIntValue()) {
// return value;
// }
// }
//
// // If not, return default
// return getDefault();
// }
//
// static Mode getDefault() {
// return PULL_FROM_START;
// }
//
// private int mIntValue;
//
// // The modeInt values need to match those from attrs.xml
// Mode(int modeInt) {
// mIntValue = modeInt;
// }
//
// /**
// * @return true if the mode permits Pull-to-Refresh
// */
// boolean permitsPullToRefresh() {
// return !(this == DISABLED || this == MANUAL_REFRESH_ONLY);
// }
//
// /**
// * @return true if this mode wants the Loading Layout Header to be shown
// */
// public boolean showHeaderLoadingLayout() {
// return this == PULL_FROM_START || this == BOTH;
// }
//
// /**
// * @return true if this mode wants the Loading Layout Footer to be shown
// */
// public boolean showFooterLoadingLayout() {
// return this == PULL_FROM_END || this == BOTH || this == MANUAL_REFRESH_ONLY;
// }
//
// int getIntValue() {
// return mIntValue;
// }
//
// }
//
// Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Orientation {
// VERTICAL, HORIZONTAL;
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView.ScaleType;
import com.handmark.pulltorefresh.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.PullToRefreshBase.Orientation;
import com.handmark.pulltorefresh.R; | /*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.handmark.pulltorefresh.internal;
public class RotateLoadingLayout extends LoadingLayout {
static final int ROTATION_ANIMATION_DURATION = 1200;
private final Animation mRotateAnimation;
private final Matrix mHeaderImageMatrix;
private float mRotationPivotX, mRotationPivotY;
private final boolean mRotateDrawableWhilePulling;
| // Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Mode {
//
// /**
// * Disable all Pull-to-Refresh gesture and Refreshing handling
// */
// DISABLED(0x0),
//
// /**
// * Only allow the user to Pull from the start of the Refreshable View to
// * refresh. The start is either the Top or Left, depending on the
// * scrolling direction.
// */
// PULL_FROM_START(0x1),
//
// /**
// * Only allow the user to Pull from the end of the Refreshable View to
// * refresh. The start is either the Bottom or Right, depending on the
// * scrolling direction.
// */
// PULL_FROM_END(0x2),
//
// /**
// * Allow the user to both Pull from the start, from the end to refresh.
// */
// BOTH(0x3),
//
// /**
// * Disables Pull-to-Refresh gesture handling, but allows manually
// * setting the Refresh state via
// * {@link PullToRefreshBase#setRefreshing() setRefreshing()}.
// */
// MANUAL_REFRESH_ONLY(0x4);
//
// /**
// * @deprecated Use {@link #PULL_FROM_START} from now on.
// */
// public static Mode PULL_DOWN_TO_REFRESH = Mode.PULL_FROM_START;
//
// /**
// * @deprecated Use {@link #PULL_FROM_END} from now on.
// */
// public static Mode PULL_UP_TO_REFRESH = Mode.PULL_FROM_END;
//
// /**
// * Maps an int to a specific mode. This is needed when saving state, or
// * inflating the view from XML where the mode is given through a attr
// * int.
// *
// * @param modeInt - int to map a Mode to
// * @return Mode that modeInt maps to, or PULL_FROM_START by default.
// */
// static Mode mapIntToValue(final int modeInt) {
// for (Mode value : Mode.values()) {
// if (modeInt == value.getIntValue()) {
// return value;
// }
// }
//
// // If not, return default
// return getDefault();
// }
//
// static Mode getDefault() {
// return PULL_FROM_START;
// }
//
// private int mIntValue;
//
// // The modeInt values need to match those from attrs.xml
// Mode(int modeInt) {
// mIntValue = modeInt;
// }
//
// /**
// * @return true if the mode permits Pull-to-Refresh
// */
// boolean permitsPullToRefresh() {
// return !(this == DISABLED || this == MANUAL_REFRESH_ONLY);
// }
//
// /**
// * @return true if this mode wants the Loading Layout Header to be shown
// */
// public boolean showHeaderLoadingLayout() {
// return this == PULL_FROM_START || this == BOTH;
// }
//
// /**
// * @return true if this mode wants the Loading Layout Footer to be shown
// */
// public boolean showFooterLoadingLayout() {
// return this == PULL_FROM_END || this == BOTH || this == MANUAL_REFRESH_ONLY;
// }
//
// int getIntValue() {
// return mIntValue;
// }
//
// }
//
// Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Orientation {
// VERTICAL, HORIZONTAL;
// }
// Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/internal/RotateLoadingLayout.java
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView.ScaleType;
import com.handmark.pulltorefresh.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.PullToRefreshBase.Orientation;
import com.handmark.pulltorefresh.R;
/*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.handmark.pulltorefresh.internal;
public class RotateLoadingLayout extends LoadingLayout {
static final int ROTATION_ANIMATION_DURATION = 1200;
private final Animation mRotateAnimation;
private final Matrix mHeaderImageMatrix;
private float mRotationPivotX, mRotationPivotY;
private final boolean mRotateDrawableWhilePulling;
| public RotateLoadingLayout(Context context, Mode mode, Orientation scrollDirection, TypedArray attrs) { |
liaozhoubei/NetEasyNews | library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/internal/RotateLoadingLayout.java | // Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Mode {
//
// /**
// * Disable all Pull-to-Refresh gesture and Refreshing handling
// */
// DISABLED(0x0),
//
// /**
// * Only allow the user to Pull from the start of the Refreshable View to
// * refresh. The start is either the Top or Left, depending on the
// * scrolling direction.
// */
// PULL_FROM_START(0x1),
//
// /**
// * Only allow the user to Pull from the end of the Refreshable View to
// * refresh. The start is either the Bottom or Right, depending on the
// * scrolling direction.
// */
// PULL_FROM_END(0x2),
//
// /**
// * Allow the user to both Pull from the start, from the end to refresh.
// */
// BOTH(0x3),
//
// /**
// * Disables Pull-to-Refresh gesture handling, but allows manually
// * setting the Refresh state via
// * {@link PullToRefreshBase#setRefreshing() setRefreshing()}.
// */
// MANUAL_REFRESH_ONLY(0x4);
//
// /**
// * @deprecated Use {@link #PULL_FROM_START} from now on.
// */
// public static Mode PULL_DOWN_TO_REFRESH = Mode.PULL_FROM_START;
//
// /**
// * @deprecated Use {@link #PULL_FROM_END} from now on.
// */
// public static Mode PULL_UP_TO_REFRESH = Mode.PULL_FROM_END;
//
// /**
// * Maps an int to a specific mode. This is needed when saving state, or
// * inflating the view from XML where the mode is given through a attr
// * int.
// *
// * @param modeInt - int to map a Mode to
// * @return Mode that modeInt maps to, or PULL_FROM_START by default.
// */
// static Mode mapIntToValue(final int modeInt) {
// for (Mode value : Mode.values()) {
// if (modeInt == value.getIntValue()) {
// return value;
// }
// }
//
// // If not, return default
// return getDefault();
// }
//
// static Mode getDefault() {
// return PULL_FROM_START;
// }
//
// private int mIntValue;
//
// // The modeInt values need to match those from attrs.xml
// Mode(int modeInt) {
// mIntValue = modeInt;
// }
//
// /**
// * @return true if the mode permits Pull-to-Refresh
// */
// boolean permitsPullToRefresh() {
// return !(this == DISABLED || this == MANUAL_REFRESH_ONLY);
// }
//
// /**
// * @return true if this mode wants the Loading Layout Header to be shown
// */
// public boolean showHeaderLoadingLayout() {
// return this == PULL_FROM_START || this == BOTH;
// }
//
// /**
// * @return true if this mode wants the Loading Layout Footer to be shown
// */
// public boolean showFooterLoadingLayout() {
// return this == PULL_FROM_END || this == BOTH || this == MANUAL_REFRESH_ONLY;
// }
//
// int getIntValue() {
// return mIntValue;
// }
//
// }
//
// Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Orientation {
// VERTICAL, HORIZONTAL;
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView.ScaleType;
import com.handmark.pulltorefresh.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.PullToRefreshBase.Orientation;
import com.handmark.pulltorefresh.R; | /*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.handmark.pulltorefresh.internal;
public class RotateLoadingLayout extends LoadingLayout {
static final int ROTATION_ANIMATION_DURATION = 1200;
private final Animation mRotateAnimation;
private final Matrix mHeaderImageMatrix;
private float mRotationPivotX, mRotationPivotY;
private final boolean mRotateDrawableWhilePulling;
| // Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Mode {
//
// /**
// * Disable all Pull-to-Refresh gesture and Refreshing handling
// */
// DISABLED(0x0),
//
// /**
// * Only allow the user to Pull from the start of the Refreshable View to
// * refresh. The start is either the Top or Left, depending on the
// * scrolling direction.
// */
// PULL_FROM_START(0x1),
//
// /**
// * Only allow the user to Pull from the end of the Refreshable View to
// * refresh. The start is either the Bottom or Right, depending on the
// * scrolling direction.
// */
// PULL_FROM_END(0x2),
//
// /**
// * Allow the user to both Pull from the start, from the end to refresh.
// */
// BOTH(0x3),
//
// /**
// * Disables Pull-to-Refresh gesture handling, but allows manually
// * setting the Refresh state via
// * {@link PullToRefreshBase#setRefreshing() setRefreshing()}.
// */
// MANUAL_REFRESH_ONLY(0x4);
//
// /**
// * @deprecated Use {@link #PULL_FROM_START} from now on.
// */
// public static Mode PULL_DOWN_TO_REFRESH = Mode.PULL_FROM_START;
//
// /**
// * @deprecated Use {@link #PULL_FROM_END} from now on.
// */
// public static Mode PULL_UP_TO_REFRESH = Mode.PULL_FROM_END;
//
// /**
// * Maps an int to a specific mode. This is needed when saving state, or
// * inflating the view from XML where the mode is given through a attr
// * int.
// *
// * @param modeInt - int to map a Mode to
// * @return Mode that modeInt maps to, or PULL_FROM_START by default.
// */
// static Mode mapIntToValue(final int modeInt) {
// for (Mode value : Mode.values()) {
// if (modeInt == value.getIntValue()) {
// return value;
// }
// }
//
// // If not, return default
// return getDefault();
// }
//
// static Mode getDefault() {
// return PULL_FROM_START;
// }
//
// private int mIntValue;
//
// // The modeInt values need to match those from attrs.xml
// Mode(int modeInt) {
// mIntValue = modeInt;
// }
//
// /**
// * @return true if the mode permits Pull-to-Refresh
// */
// boolean permitsPullToRefresh() {
// return !(this == DISABLED || this == MANUAL_REFRESH_ONLY);
// }
//
// /**
// * @return true if this mode wants the Loading Layout Header to be shown
// */
// public boolean showHeaderLoadingLayout() {
// return this == PULL_FROM_START || this == BOTH;
// }
//
// /**
// * @return true if this mode wants the Loading Layout Footer to be shown
// */
// public boolean showFooterLoadingLayout() {
// return this == PULL_FROM_END || this == BOTH || this == MANUAL_REFRESH_ONLY;
// }
//
// int getIntValue() {
// return mIntValue;
// }
//
// }
//
// Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/PullToRefreshBase.java
// public static enum Orientation {
// VERTICAL, HORIZONTAL;
// }
// Path: library/pulltorefresh/src/main/java/com/handmark/pulltorefresh/internal/RotateLoadingLayout.java
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView.ScaleType;
import com.handmark.pulltorefresh.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.PullToRefreshBase.Orientation;
import com.handmark.pulltorefresh.R;
/*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.handmark.pulltorefresh.internal;
public class RotateLoadingLayout extends LoadingLayout {
static final int ROTATION_ANIMATION_DURATION = 1200;
private final Animation mRotateAnimation;
private final Matrix mHeaderImageMatrix;
private float mRotationPivotX, mRotationPivotY;
private final boolean mRotateDrawableWhilePulling;
| public RotateLoadingLayout(Context context, Mode mode, Orientation scrollDirection, TypedArray attrs) { |
liaozhoubei/NetEasyNews | app/src/main/java/cn/bproject/neteasynews/widget/NormalTitleBar.java | // Path: app/src/main/java/cn/bproject/neteasynews/Utils/DensityUtils.java
// public class DensityUtils {
//
// public static int getScreenWidth(Context context) {
// DisplayMetrics dm = new DisplayMetrics();
// ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
// return dm.widthPixels;
// }
//
// public static int getScreenHeight(Context context) {
// DisplayMetrics dm = new DisplayMetrics();
// ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
// return dm.heightPixels;
// }
//
// public static int getScreenHeightWithDecorations(Context context) {
// int heightPixels;
// WindowManager w = ((Activity) context).getWindowManager();
// Display d = w.getDefaultDisplay();
// android.graphics.Point realSize = new android.graphics.Point();
// try {
// Display.class.getMethod("getRealSize", android.graphics.Point.class).invoke(d, realSize);
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// }
// heightPixels = realSize.y;
// return heightPixels;
// }
//
// /**
// * 获得状态栏的高度
// * 注意:该方法只能在Activity类中使用,在测试模式下失败
// * @param context
// * @return
// */
// public static int getStatusBarHeight(Context context) {
// int statusBarHeight = -1;
// try {
// Class<?> clazz = Class.forName("com.android.internal.R$dimen");
// Object object = clazz.newInstance();
// int height = Integer.parseInt(clazz.getField("status_bar_height")
// .get(object).toString());
// statusBarHeight = context.getResources().getDimensionPixelSize(height);
// } catch (Exception e) {
// e.printStackTrace();
// }
// return statusBarHeight;
// }
//
//
// public static int dip2px(Context context, float dpValue) {
// final float scale = context.getResources().getDisplayMetrics().density;
// return (int) (dpValue * scale + 0.5f);
// }
//
// public static int px2dip(Context context, float pxValue) {
// final float scale = context.getResources().getDisplayMetrics().density;
// return (int) (pxValue / scale + 0.5f);
// }
// }
| import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.bproject.neteasynews.R;
import cn.bproject.neteasynews.Utils.DensityUtils; | package cn.bproject.neteasynews.widget;
/**
* Created by liaozhoubei on 2017/1/9.
*/
public class NormalTitleBar extends RelativeLayout{
private ImageView ivRight;
private TextView ivBack,tvTitle, tvRight;
private RelativeLayout rlCommonTitle;
private Context context;
public NormalTitleBar(Context context) {
super(context);
this.context = context;
}
public NormalTitleBar(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
View.inflate(context, R.layout.bar_normal, this);
ivBack = (TextView) findViewById(R.id.tv_back);
tvTitle = (TextView) findViewById(R.id.tv_title);
tvRight = (TextView) findViewById(R.id.tv_right);
ivRight = (ImageView) findViewById(R.id.image_right);
rlCommonTitle = (RelativeLayout) findViewById(R.id.common_title);
}
public NormalTitleBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setHeaderHeight() { | // Path: app/src/main/java/cn/bproject/neteasynews/Utils/DensityUtils.java
// public class DensityUtils {
//
// public static int getScreenWidth(Context context) {
// DisplayMetrics dm = new DisplayMetrics();
// ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
// return dm.widthPixels;
// }
//
// public static int getScreenHeight(Context context) {
// DisplayMetrics dm = new DisplayMetrics();
// ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
// return dm.heightPixels;
// }
//
// public static int getScreenHeightWithDecorations(Context context) {
// int heightPixels;
// WindowManager w = ((Activity) context).getWindowManager();
// Display d = w.getDefaultDisplay();
// android.graphics.Point realSize = new android.graphics.Point();
// try {
// Display.class.getMethod("getRealSize", android.graphics.Point.class).invoke(d, realSize);
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// }
// heightPixels = realSize.y;
// return heightPixels;
// }
//
// /**
// * 获得状态栏的高度
// * 注意:该方法只能在Activity类中使用,在测试模式下失败
// * @param context
// * @return
// */
// public static int getStatusBarHeight(Context context) {
// int statusBarHeight = -1;
// try {
// Class<?> clazz = Class.forName("com.android.internal.R$dimen");
// Object object = clazz.newInstance();
// int height = Integer.parseInt(clazz.getField("status_bar_height")
// .get(object).toString());
// statusBarHeight = context.getResources().getDimensionPixelSize(height);
// } catch (Exception e) {
// e.printStackTrace();
// }
// return statusBarHeight;
// }
//
//
// public static int dip2px(Context context, float dpValue) {
// final float scale = context.getResources().getDisplayMetrics().density;
// return (int) (dpValue * scale + 0.5f);
// }
//
// public static int px2dip(Context context, float pxValue) {
// final float scale = context.getResources().getDisplayMetrics().density;
// return (int) (pxValue / scale + 0.5f);
// }
// }
// Path: app/src/main/java/cn/bproject/neteasynews/widget/NormalTitleBar.java
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.bproject.neteasynews.R;
import cn.bproject.neteasynews.Utils.DensityUtils;
package cn.bproject.neteasynews.widget;
/**
* Created by liaozhoubei on 2017/1/9.
*/
public class NormalTitleBar extends RelativeLayout{
private ImageView ivRight;
private TextView ivBack,tvTitle, tvRight;
private RelativeLayout rlCommonTitle;
private Context context;
public NormalTitleBar(Context context) {
super(context);
this.context = context;
}
public NormalTitleBar(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
View.inflate(context, R.layout.bar_normal, this);
ivBack = (TextView) findViewById(R.id.tv_back);
tvTitle = (TextView) findViewById(R.id.tv_title);
tvRight = (TextView) findViewById(R.id.tv_right);
ivRight = (ImageView) findViewById(R.id.image_right);
rlCommonTitle = (RelativeLayout) findViewById(R.id.common_title);
}
public NormalTitleBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setHeaderHeight() { | rlCommonTitle.setPadding(0, DensityUtils.getStatusBarHeight(context), 0, 0); |
liaozhoubei/NetEasyNews | app/src/main/java/cn/bproject/neteasynews/Utils/UIUtils.java | // Path: app/src/main/java/cn/bproject/neteasynews/MyApplication.java
// public class MyApplication extends Application {
// private static int mainThreadId;
// private static Handler handler;
// private static Context mContext;
// private static ThreadManager.ThreadPool mThreadPool;
//
// // private static MyApplication sMyApplication;
//
//
// public void setThreadPool(ThreadManager.ThreadPool threadPool) {
// mThreadPool = threadPool;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// mContext = getApplicationContext();
// handler = new Handler();
// mainThreadId = android.os.Process.myTid();
// mThreadPool = ThreadManager.getThreadPool();
//
// initBugly();
//
//
// }
//
// /**
// * 初始化bugly
// */
// private void initBugly() {
// // 获取当前包名
// String packageName = mContext.getPackageName();
// // 获取当前进程名
// String processName = getProcessName(android.os.Process.myPid());
// // 设置是否为上报进程
// CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(mContext);
// strategy.setUploadProcess(processName == null || processName.equals(packageName));
// CrashReport.initCrashReport(getApplicationContext(), "7a544c9222", false);
// }
//
// /**
// * 获取进程号对应的进程名
// *
// * @param pid 进程号
// * @return 进程名
// */
// private static String getProcessName(int pid) {
// BufferedReader reader = null;
// try {
// reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
// String processName = reader.readLine();
// if (!TextUtils.isEmpty(processName)) {
// processName = processName.trim();
// }
// return processName;
// } catch (Throwable throwable) {
// throwable.printStackTrace();
// } finally {
// try {
// if (reader != null) {
// reader.close();
// }
// } catch (IOException exception) {
// exception.printStackTrace();
// }
// }
// return null;
// }
//
//
// // public static MyApplication getInstance() {
// // // if语句下是不会走的,Application本身已单例
// // if (sMyApplication == null) {
// // synchronized (MyApplication.class) {
// // if (sMyApplication == null) {
// // sMyApplication = new MyApplication();
// // }
// // }
// // }
// // return sMyApplication;
// // }
//
//
// public static Context getContext() {
// return mContext;
// }
//
// public static Handler getHandler() {
// return handler;
// }
//
//
// public static int getMainThreadId() {
// return mainThreadId;
// }
//
// public static ThreadManager.ThreadPool getThreadPool() {
// return mThreadPool;
// }
// }
| import android.content.Context;
import android.os.Handler;
import cn.bproject.neteasynews.MyApplication; | package cn.bproject.neteasynews.Utils;
public class UIUtils {
public static Context getContext() { | // Path: app/src/main/java/cn/bproject/neteasynews/MyApplication.java
// public class MyApplication extends Application {
// private static int mainThreadId;
// private static Handler handler;
// private static Context mContext;
// private static ThreadManager.ThreadPool mThreadPool;
//
// // private static MyApplication sMyApplication;
//
//
// public void setThreadPool(ThreadManager.ThreadPool threadPool) {
// mThreadPool = threadPool;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// mContext = getApplicationContext();
// handler = new Handler();
// mainThreadId = android.os.Process.myTid();
// mThreadPool = ThreadManager.getThreadPool();
//
// initBugly();
//
//
// }
//
// /**
// * 初始化bugly
// */
// private void initBugly() {
// // 获取当前包名
// String packageName = mContext.getPackageName();
// // 获取当前进程名
// String processName = getProcessName(android.os.Process.myPid());
// // 设置是否为上报进程
// CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(mContext);
// strategy.setUploadProcess(processName == null || processName.equals(packageName));
// CrashReport.initCrashReport(getApplicationContext(), "7a544c9222", false);
// }
//
// /**
// * 获取进程号对应的进程名
// *
// * @param pid 进程号
// * @return 进程名
// */
// private static String getProcessName(int pid) {
// BufferedReader reader = null;
// try {
// reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
// String processName = reader.readLine();
// if (!TextUtils.isEmpty(processName)) {
// processName = processName.trim();
// }
// return processName;
// } catch (Throwable throwable) {
// throwable.printStackTrace();
// } finally {
// try {
// if (reader != null) {
// reader.close();
// }
// } catch (IOException exception) {
// exception.printStackTrace();
// }
// }
// return null;
// }
//
//
// // public static MyApplication getInstance() {
// // // if语句下是不会走的,Application本身已单例
// // if (sMyApplication == null) {
// // synchronized (MyApplication.class) {
// // if (sMyApplication == null) {
// // sMyApplication = new MyApplication();
// // }
// // }
// // }
// // return sMyApplication;
// // }
//
//
// public static Context getContext() {
// return mContext;
// }
//
// public static Handler getHandler() {
// return handler;
// }
//
//
// public static int getMainThreadId() {
// return mainThreadId;
// }
//
// public static ThreadManager.ThreadPool getThreadPool() {
// return mThreadPool;
// }
// }
// Path: app/src/main/java/cn/bproject/neteasynews/Utils/UIUtils.java
import android.content.Context;
import android.os.Handler;
import cn.bproject.neteasynews.MyApplication;
package cn.bproject.neteasynews.Utils;
public class UIUtils {
public static Context getContext() { | return MyApplication.getContext(); |
karthikj1/JRegexPlus | karthik/regex/ECloseCache.java | // Path: karthik/regex/dataStructures/Stack.java
// public class Stack<T> {
//
// StackItem<T> top;
//
// public Stack() {
// top = null;
// }
//
// public T push(T data) {
// StackItem<T> newStackItem = new StackItem<T>(data);
//
// if (this.isEmpty()) {
// top = newStackItem;
// } else {
// newStackItem.setNext(top);
// top = newStackItem;
// }
// return newStackItem.data;
// }
//
// public boolean isEmpty() {
// return (top == null);
// }
//
// public T pop() {
// StackItem<T> newStackItem;
//
// if (this.isEmpty()) // stack is empty so top will be null
// return null;
//
// newStackItem = top;
// top = top.getNext();
//
// return newStackItem.data;
// }
//
// public T peek() {
// if(isEmpty())
// return null;
// return top.data;
// }
//
// class StackItem<T> {
//
// private StackItem<T> next;
// T data;
//
// StackItem(T item) {
// data = item;
// next = null;
// }
//
// StackItem<T> getNext() {
// return next;
// }
//
// StackItem<T> setNext(T item) {
// next = new StackItem<T>(item);
// return next;
// }
//
// StackItem<T> setNext(StackItem<T> item) {
// next = item;
// return item;
// }
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import karthik.regex.dataStructures.Stack; | /*
* Copyright (C) 2014 karthik
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
package karthik.regex;
/**
*
* @author karthik
*/
class ECloseCache {
private Map<Integer, Integer[]> eclose_cache;
private ECloseCache(Map<Integer, Integer[]> cache) {
eclose_cache = cache;
}
Integer[] get_eps_transitions(Integer source_state) {
Integer[] return_array = eclose_cache.get(source_state);
return (return_array == null) ? new Integer[0] : return_array;
}
static ECloseCache create_eclose_cache(TransitionTable transition_table) {
// e-closes every state in the transition matrix
Integer[] eclose_array_for_one_state;
Map<Integer, Integer[]> return_map = new HashMap<>();
Integer numStates = transition_table.getNumStates();
for (Integer source_state = 0; source_state < numStates; source_state++) {
eclose_array_for_one_state = calc_eclose_states(transition_table,
source_state);
return_map.put(source_state, eclose_array_for_one_state);
}
return new ECloseCache(return_map);
}
private static Integer[] calc_eclose_states(TransitionTable transition_table,
Integer current_state) {
Map<Integer, Integer> eclose_map = new HashMap<>(); | // Path: karthik/regex/dataStructures/Stack.java
// public class Stack<T> {
//
// StackItem<T> top;
//
// public Stack() {
// top = null;
// }
//
// public T push(T data) {
// StackItem<T> newStackItem = new StackItem<T>(data);
//
// if (this.isEmpty()) {
// top = newStackItem;
// } else {
// newStackItem.setNext(top);
// top = newStackItem;
// }
// return newStackItem.data;
// }
//
// public boolean isEmpty() {
// return (top == null);
// }
//
// public T pop() {
// StackItem<T> newStackItem;
//
// if (this.isEmpty()) // stack is empty so top will be null
// return null;
//
// newStackItem = top;
// top = top.getNext();
//
// return newStackItem.data;
// }
//
// public T peek() {
// if(isEmpty())
// return null;
// return top.data;
// }
//
// class StackItem<T> {
//
// private StackItem<T> next;
// T data;
//
// StackItem(T item) {
// data = item;
// next = null;
// }
//
// StackItem<T> getNext() {
// return next;
// }
//
// StackItem<T> setNext(T item) {
// next = new StackItem<T>(item);
// return next;
// }
//
// StackItem<T> setNext(StackItem<T> item) {
// next = item;
// return item;
// }
// }
//
// }
// Path: karthik/regex/ECloseCache.java
import java.util.HashMap;
import java.util.Map;
import karthik.regex.dataStructures.Stack;
/*
* Copyright (C) 2014 karthik
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
package karthik.regex;
/**
*
* @author karthik
*/
class ECloseCache {
private Map<Integer, Integer[]> eclose_cache;
private ECloseCache(Map<Integer, Integer[]> cache) {
eclose_cache = cache;
}
Integer[] get_eps_transitions(Integer source_state) {
Integer[] return_array = eclose_cache.get(source_state);
return (return_array == null) ? new Integer[0] : return_array;
}
static ECloseCache create_eclose_cache(TransitionTable transition_table) {
// e-closes every state in the transition matrix
Integer[] eclose_array_for_one_state;
Map<Integer, Integer[]> return_map = new HashMap<>();
Integer numStates = transition_table.getNumStates();
for (Integer source_state = 0; source_state < numStates; source_state++) {
eclose_array_for_one_state = calc_eclose_states(transition_table,
source_state);
return_map.put(source_state, eclose_array_for_one_state);
}
return new ECloseCache(return_map);
}
private static Integer[] calc_eclose_states(TransitionTable transition_table,
Integer current_state) {
Map<Integer, Integer> eclose_map = new HashMap<>(); | Stack<Integer> tempStack = new Stack<>(); |
karthikj1/JRegexPlus | karthik/regex/Pattern.java | // Path: karthik/regex/RegexTokenNames.java
// enum RegexTokenNames {
//
// CHAR, CHAR_CLASS, WHITESPACE, DOT, DIGIT, WORD,
// NONDIGIT, NONWORD, NONWHITESPACE,
// TAB, NEWLINE, FORMFEED, CARR_RETURN,
// BRACE, STAR, PLUS, QUESTION,
// LAZY_BRACE, LAZY_STAR, LAZY_PLUS, LAZY_QUESTION,
// OR, AND, EPSILON,
// GROUP, LOOKAHEAD, LOOKBEHIND,
// WORD_BOUNDARY, NON_WORD_BOUNDARY,
// STRING_START, STRING_END, LINE_START, LINE_END, JAVA_Z_STRING_END,
// BACKREFERENCE, ENDBACKREFERENCE, BACKREF_STRING
// }
//
// Path: karthik/regex/dataStructures/Stack.java
// public class Stack<T> {
//
// StackItem<T> top;
//
// public Stack() {
// top = null;
// }
//
// public T push(T data) {
// StackItem<T> newStackItem = new StackItem<T>(data);
//
// if (this.isEmpty()) {
// top = newStackItem;
// } else {
// newStackItem.setNext(top);
// top = newStackItem;
// }
// return newStackItem.data;
// }
//
// public boolean isEmpty() {
// return (top == null);
// }
//
// public T pop() {
// StackItem<T> newStackItem;
//
// if (this.isEmpty()) // stack is empty so top will be null
// return null;
//
// newStackItem = top;
// top = top.getNext();
//
// return newStackItem.data;
// }
//
// public T peek() {
// if(isEmpty())
// return null;
// return top.data;
// }
//
// class StackItem<T> {
//
// private StackItem<T> next;
// T data;
//
// StackItem(T item) {
// data = item;
// next = null;
// }
//
// StackItem<T> getNext() {
// return next;
// }
//
// StackItem<T> setNext(T item) {
// next = new StackItem<T>(item);
// return next;
// }
//
// StackItem<T> setNext(StackItem<T> item) {
// next = item;
// return item;
// }
// }
//
// }
//
// Path: karthik/regex/dataStructures/Tree.java
// public class Tree<T> {
//
// protected TreeNode<T> root;
//
// public Tree() {
// root = null;
// }
//
// public Tree(T data, Tree<T> leftSubTree, Tree<T> rightSubTree) {
// root = null;
// addItem(data, leftSubTree, rightSubTree);
// }
//
// public Tree<T> addItem(T data, Tree<T> leftSubTree, Tree<T> rightSubTree) // always creates new tree with added item at root
// {
// TreeNode<T> node;
//
// node = new TreeNode<T>(data);
// if (root == null)
// root = node;
//
// root.setLeft((leftSubTree == null) ? null : leftSubTree.root);
// root.setRight((rightSubTree == null) ? null : rightSubTree.root);
//
// return this;
// }
//
// public void traverse() {
// if (root == null)
// return;
//
// recTraverse(root);
// }
//
// protected void recTraverse(TreeNode<T> current) {
// if (current == null)
// return;
//
// recTraverse(current.getLeft());
// current.display();
// recTraverse(current.getRight());
//
// return;
// }
//
// public boolean isEmpty() {
// return (root == null);
// }
//
// public boolean isLeaf(TreeNode<T> current) {
// if ((current.getLeft() == null) && (current.getRight() == null))
// return true;
// else
// return false;
// }
//
// class TreeNode<T> {
//
// protected T data;
// protected TreeNode<T> left, right;
//
// TreeNode(T i) {
// data = i;
// left = right = null;
// }
//
// T getData() {
// return data;
// }
//
// void display() {
// System.out.print(data.toString() + " ");
// }
//
// TreeNode<T> getLeft() {
// return left;
// }
//
// TreeNode<T> getRight() {
// return right;
// }
//
// void setLeft(TreeNode<T> newnode) {
// left = newnode;
// }
//
// void setRight(TreeNode<T> newnode) {
// right = newnode;
// }
// }
// }
| import karthik.regex.RegexTokenNames;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import karthik.regex.dataStructures.Stack;
import karthik.regex.dataStructures.Tree; | ParseObject parse() throws ParserException {
if (LOG) {
for (RegexToken tok : tokens)
System.out.print(tok.toString() + " ");
System.out.println("");
}
if (RE()) {
TransitionTable transitions = matcherStack.pop();
// above stores number of capturing groups in transition matrix
return new ParseObject(debug_tree_stack.pop(), transitions);
}
throw new ParserException("Regex could not be parsed");
}
private boolean RE() throws ParserException {
if (getCurrentToken() == null)
return false;
if (simpleRE() && union() && getCurrentToken() == null)
return true;
return false;
}
private boolean union() throws ParserException {
if (getCurrentToken() == null)
return true;
| // Path: karthik/regex/RegexTokenNames.java
// enum RegexTokenNames {
//
// CHAR, CHAR_CLASS, WHITESPACE, DOT, DIGIT, WORD,
// NONDIGIT, NONWORD, NONWHITESPACE,
// TAB, NEWLINE, FORMFEED, CARR_RETURN,
// BRACE, STAR, PLUS, QUESTION,
// LAZY_BRACE, LAZY_STAR, LAZY_PLUS, LAZY_QUESTION,
// OR, AND, EPSILON,
// GROUP, LOOKAHEAD, LOOKBEHIND,
// WORD_BOUNDARY, NON_WORD_BOUNDARY,
// STRING_START, STRING_END, LINE_START, LINE_END, JAVA_Z_STRING_END,
// BACKREFERENCE, ENDBACKREFERENCE, BACKREF_STRING
// }
//
// Path: karthik/regex/dataStructures/Stack.java
// public class Stack<T> {
//
// StackItem<T> top;
//
// public Stack() {
// top = null;
// }
//
// public T push(T data) {
// StackItem<T> newStackItem = new StackItem<T>(data);
//
// if (this.isEmpty()) {
// top = newStackItem;
// } else {
// newStackItem.setNext(top);
// top = newStackItem;
// }
// return newStackItem.data;
// }
//
// public boolean isEmpty() {
// return (top == null);
// }
//
// public T pop() {
// StackItem<T> newStackItem;
//
// if (this.isEmpty()) // stack is empty so top will be null
// return null;
//
// newStackItem = top;
// top = top.getNext();
//
// return newStackItem.data;
// }
//
// public T peek() {
// if(isEmpty())
// return null;
// return top.data;
// }
//
// class StackItem<T> {
//
// private StackItem<T> next;
// T data;
//
// StackItem(T item) {
// data = item;
// next = null;
// }
//
// StackItem<T> getNext() {
// return next;
// }
//
// StackItem<T> setNext(T item) {
// next = new StackItem<T>(item);
// return next;
// }
//
// StackItem<T> setNext(StackItem<T> item) {
// next = item;
// return item;
// }
// }
//
// }
//
// Path: karthik/regex/dataStructures/Tree.java
// public class Tree<T> {
//
// protected TreeNode<T> root;
//
// public Tree() {
// root = null;
// }
//
// public Tree(T data, Tree<T> leftSubTree, Tree<T> rightSubTree) {
// root = null;
// addItem(data, leftSubTree, rightSubTree);
// }
//
// public Tree<T> addItem(T data, Tree<T> leftSubTree, Tree<T> rightSubTree) // always creates new tree with added item at root
// {
// TreeNode<T> node;
//
// node = new TreeNode<T>(data);
// if (root == null)
// root = node;
//
// root.setLeft((leftSubTree == null) ? null : leftSubTree.root);
// root.setRight((rightSubTree == null) ? null : rightSubTree.root);
//
// return this;
// }
//
// public void traverse() {
// if (root == null)
// return;
//
// recTraverse(root);
// }
//
// protected void recTraverse(TreeNode<T> current) {
// if (current == null)
// return;
//
// recTraverse(current.getLeft());
// current.display();
// recTraverse(current.getRight());
//
// return;
// }
//
// public boolean isEmpty() {
// return (root == null);
// }
//
// public boolean isLeaf(TreeNode<T> current) {
// if ((current.getLeft() == null) && (current.getRight() == null))
// return true;
// else
// return false;
// }
//
// class TreeNode<T> {
//
// protected T data;
// protected TreeNode<T> left, right;
//
// TreeNode(T i) {
// data = i;
// left = right = null;
// }
//
// T getData() {
// return data;
// }
//
// void display() {
// System.out.print(data.toString() + " ");
// }
//
// TreeNode<T> getLeft() {
// return left;
// }
//
// TreeNode<T> getRight() {
// return right;
// }
//
// void setLeft(TreeNode<T> newnode) {
// left = newnode;
// }
//
// void setRight(TreeNode<T> newnode) {
// right = newnode;
// }
// }
// }
// Path: karthik/regex/Pattern.java
import karthik.regex.RegexTokenNames;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import karthik.regex.dataStructures.Stack;
import karthik.regex.dataStructures.Tree;
ParseObject parse() throws ParserException {
if (LOG) {
for (RegexToken tok : tokens)
System.out.print(tok.toString() + " ");
System.out.println("");
}
if (RE()) {
TransitionTable transitions = matcherStack.pop();
// above stores number of capturing groups in transition matrix
return new ParseObject(debug_tree_stack.pop(), transitions);
}
throw new ParserException("Regex could not be parsed");
}
private boolean RE() throws ParserException {
if (getCurrentToken() == null)
return false;
if (simpleRE() && union() && getCurrentToken() == null)
return true;
return false;
}
private boolean union() throws ParserException {
if (getCurrentToken() == null)
return true;
| if (getCurrentToken().getType() == RegexTokenNames.OR) { |
karthikj1/JRegexPlus | karthik/regex/BackRefRegexToken.java | // Path: karthik/regex/MatcherException.java
// public class MatcherException extends Exception {
//
// public MatcherException() {
// super();
// }
//
// public MatcherException(String msg) {
// super(msg);
// }
//
// public MatcherException(String msg, Throwable t) {
// super(msg, t);
// }
//
// }
| import karthik.regex.MatcherException; | /*
* Copyright (C) 2014 karthik
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
package karthik.regex;
/**
*
* @author karthik
*/
public class BackRefRegexToken extends RegexToken {
static Integer INVALID_ID = -1;
private Integer backRefID = INVALID_ID;
private CharSequence group_name = "";
protected BackRefRegexToken() {
}
BackRefRegexToken(Integer id) {
backRefID = id;
type = RegexTokenNames.BACKREFERENCE;
}
BackRefRegexToken(CharSequence name) {
group_name = name;
type = RegexTokenNames.BACKREFERENCE;
}
| // Path: karthik/regex/MatcherException.java
// public class MatcherException extends Exception {
//
// public MatcherException() {
// super();
// }
//
// public MatcherException(String msg) {
// super(msg);
// }
//
// public MatcherException(String msg, Throwable t) {
// super(msg, t);
// }
//
// }
// Path: karthik/regex/BackRefRegexToken.java
import karthik.regex.MatcherException;
/*
* Copyright (C) 2014 karthik
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
package karthik.regex;
/**
*
* @author karthik
*/
public class BackRefRegexToken extends RegexToken {
static Integer INVALID_ID = -1;
private Integer backRefID = INVALID_ID;
private CharSequence group_name = "";
protected BackRefRegexToken() {
}
BackRefRegexToken(Integer id) {
backRefID = id;
type = RegexTokenNames.BACKREFERENCE;
}
BackRefRegexToken(CharSequence name) {
group_name = name;
type = RegexTokenNames.BACKREFERENCE;
}
| public boolean matches(CharSequence s, Integer pos) throws MatcherException { |
karthikj1/JRegexPlus | karthik/regex/NFASimulator.java | // Path: karthik/regex/dataStructures/Stack.java
// public class Stack<T> {
//
// StackItem<T> top;
//
// public Stack() {
// top = null;
// }
//
// public T push(T data) {
// StackItem<T> newStackItem = new StackItem<T>(data);
//
// if (this.isEmpty()) {
// top = newStackItem;
// } else {
// newStackItem.setNext(top);
// top = newStackItem;
// }
// return newStackItem.data;
// }
//
// public boolean isEmpty() {
// return (top == null);
// }
//
// public T pop() {
// StackItem<T> newStackItem;
//
// if (this.isEmpty()) // stack is empty so top will be null
// return null;
//
// newStackItem = top;
// top = top.getNext();
//
// return newStackItem.data;
// }
//
// public T peek() {
// if(isEmpty())
// return null;
// return top.data;
// }
//
// class StackItem<T> {
//
// private StackItem<T> next;
// T data;
//
// StackItem(T item) {
// data = item;
// next = null;
// }
//
// StackItem<T> getNext() {
// return next;
// }
//
// StackItem<T> setNext(T item) {
// next = new StackItem<T>(item);
// return next;
// }
//
// StackItem<T> setNext(StackItem<T> item) {
// next = item;
// return item;
// }
// }
//
// }
| import karthik.regex.dataStructures.Stack; | /*
* Copyright (C) 2014 karthik
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
package karthik.regex;
/**
*
* @author karthik
*/
class NFASimulator {
protected Integer finish;
protected TransitionTable original_start_table;
protected TransitionTable transMatrix;
protected CharSequence regex_string = "";
protected Integer string_index; // global pointer that keeps track of our position in the search string
protected String search_string;
protected Integer region_start, region_end;
| // Path: karthik/regex/dataStructures/Stack.java
// public class Stack<T> {
//
// StackItem<T> top;
//
// public Stack() {
// top = null;
// }
//
// public T push(T data) {
// StackItem<T> newStackItem = new StackItem<T>(data);
//
// if (this.isEmpty()) {
// top = newStackItem;
// } else {
// newStackItem.setNext(top);
// top = newStackItem;
// }
// return newStackItem.data;
// }
//
// public boolean isEmpty() {
// return (top == null);
// }
//
// public T pop() {
// StackItem<T> newStackItem;
//
// if (this.isEmpty()) // stack is empty so top will be null
// return null;
//
// newStackItem = top;
// top = top.getNext();
//
// return newStackItem.data;
// }
//
// public T peek() {
// if(isEmpty())
// return null;
// return top.data;
// }
//
// class StackItem<T> {
//
// private StackItem<T> next;
// T data;
//
// StackItem(T item) {
// data = item;
// next = null;
// }
//
// StackItem<T> getNext() {
// return next;
// }
//
// StackItem<T> setNext(T item) {
// next = new StackItem<T>(item);
// return next;
// }
//
// StackItem<T> setNext(StackItem<T> item) {
// next = item;
// return item;
// }
// }
//
// }
// Path: karthik/regex/NFASimulator.java
import karthik.regex.dataStructures.Stack;
/*
* Copyright (C) 2014 karthik
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
package karthik.regex;
/**
*
* @author karthik
*/
class NFASimulator {
protected Integer finish;
protected TransitionTable original_start_table;
protected TransitionTable transMatrix;
protected CharSequence regex_string = "";
protected Integer string_index; // global pointer that keeps track of our position in the search string
protected String search_string;
protected Integer region_start, region_end;
| protected Stack<Integer> boundary_stack = new Stack<>(); |
karthikj1/JRegexPlus | karthik/regex/Tokenizer.java | // Path: karthik/regex/RegexTokenNames.java
// enum RegexTokenNames {
//
// CHAR, CHAR_CLASS, WHITESPACE, DOT, DIGIT, WORD,
// NONDIGIT, NONWORD, NONWHITESPACE,
// TAB, NEWLINE, FORMFEED, CARR_RETURN,
// BRACE, STAR, PLUS, QUESTION,
// LAZY_BRACE, LAZY_STAR, LAZY_PLUS, LAZY_QUESTION,
// OR, AND, EPSILON,
// GROUP, LOOKAHEAD, LOOKBEHIND,
// WORD_BOUNDARY, NON_WORD_BOUNDARY,
// STRING_START, STRING_END, LINE_START, LINE_END, JAVA_Z_STRING_END,
// BACKREFERENCE, ENDBACKREFERENCE, BACKREF_STRING
// }
| import karthik.regex.RegexTokenNames;
import java.util.ArrayList; | // inGroup is true if the parser is inside a group enclosed by parentheses
char currentChar;
try {
while (indexPos < len) {
currentChar = inputString.charAt(indexPos++);
switch (currentChar) {
case '\\':
currentChar = inputString.charAt(indexPos++);
handleEscapeChars(tokens, currentChar);
break;
case '[':
indexPos--;
tokens.add(parseCharClass());
break;
case '(':
if (inputString.charAt(indexPos) == '?') {
RegexToken lookaround_tok = handleLookaround_and_flags();
if (lookaround_tok != null)
tokens.add(lookaround_tok);
// null token means it was a flag so nothing to do
} else
tokens.add(parseGroup());
break;
case ')':
if (inGroup)
return;
// ) treated like ordinary character when not preceded by matching left parentheses | // Path: karthik/regex/RegexTokenNames.java
// enum RegexTokenNames {
//
// CHAR, CHAR_CLASS, WHITESPACE, DOT, DIGIT, WORD,
// NONDIGIT, NONWORD, NONWHITESPACE,
// TAB, NEWLINE, FORMFEED, CARR_RETURN,
// BRACE, STAR, PLUS, QUESTION,
// LAZY_BRACE, LAZY_STAR, LAZY_PLUS, LAZY_QUESTION,
// OR, AND, EPSILON,
// GROUP, LOOKAHEAD, LOOKBEHIND,
// WORD_BOUNDARY, NON_WORD_BOUNDARY,
// STRING_START, STRING_END, LINE_START, LINE_END, JAVA_Z_STRING_END,
// BACKREFERENCE, ENDBACKREFERENCE, BACKREF_STRING
// }
// Path: karthik/regex/Tokenizer.java
import karthik.regex.RegexTokenNames;
import java.util.ArrayList;
// inGroup is true if the parser is inside a group enclosed by parentheses
char currentChar;
try {
while (indexPos < len) {
currentChar = inputString.charAt(indexPos++);
switch (currentChar) {
case '\\':
currentChar = inputString.charAt(indexPos++);
handleEscapeChars(tokens, currentChar);
break;
case '[':
indexPos--;
tokens.add(parseCharClass());
break;
case '(':
if (inputString.charAt(indexPos) == '?') {
RegexToken lookaround_tok = handleLookaround_and_flags();
if (lookaround_tok != null)
tokens.add(lookaround_tok);
// null token means it was a flag so nothing to do
} else
tokens.add(parseGroup());
break;
case ')':
if (inGroup)
return;
// ) treated like ordinary character when not preceded by matching left parentheses | tokens.add(new RegexToken(RegexTokenNames.CHAR, |
karthikj1/JRegexPlus | karthik/regex/TransitionTable.java | // Path: karthik/regex/RegexTokenNames.java
// enum RegexTokenNames {
//
// CHAR, CHAR_CLASS, WHITESPACE, DOT, DIGIT, WORD,
// NONDIGIT, NONWORD, NONWHITESPACE,
// TAB, NEWLINE, FORMFEED, CARR_RETURN,
// BRACE, STAR, PLUS, QUESTION,
// LAZY_BRACE, LAZY_STAR, LAZY_PLUS, LAZY_QUESTION,
// OR, AND, EPSILON,
// GROUP, LOOKAHEAD, LOOKBEHIND,
// WORD_BOUNDARY, NON_WORD_BOUNDARY,
// STRING_START, STRING_END, LINE_START, LINE_END, JAVA_Z_STRING_END,
// BACKREFERENCE, ENDBACKREFERENCE, BACKREF_STRING
// }
| import karthik.regex.RegexTokenNames;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set; | Integer starting_num_states = getNumStates();
Integer n2States = n2.getNumStates();
contains_backref = contains_backref | n2.contains_backref;
Integer oldStart = start;
Integer oldFinish = finish;
// clone matrix from TransitionTable n2 to new matrix
expand_table(n2States + 2);
for (Integer i = 0; i < n2States; i++)
for (Integer j : n2.get_all_transitions(i)) {
token = n2.getTransition(i, j);
setTransition(starting_num_states + i, starting_num_states + j,
token);
}
start = getNumStates() - 2;
finish = getNumStates() - 1;
// set e-transitions for new start_index state
setTransition(start, oldStart, eps);
setTransition(start, n2.getStart() + starting_num_states, eps);
// set e-transition to go to new finish state
setTransition(oldFinish, finish, eps);
setTransition(n2.getFinish() + starting_num_states, finish, eps);
return this;
}
TransitionTable plus(Integer quantGroupID, Integer uniqueID) {
// plus implemented as a+ = a.a* | // Path: karthik/regex/RegexTokenNames.java
// enum RegexTokenNames {
//
// CHAR, CHAR_CLASS, WHITESPACE, DOT, DIGIT, WORD,
// NONDIGIT, NONWORD, NONWHITESPACE,
// TAB, NEWLINE, FORMFEED, CARR_RETURN,
// BRACE, STAR, PLUS, QUESTION,
// LAZY_BRACE, LAZY_STAR, LAZY_PLUS, LAZY_QUESTION,
// OR, AND, EPSILON,
// GROUP, LOOKAHEAD, LOOKBEHIND,
// WORD_BOUNDARY, NON_WORD_BOUNDARY,
// STRING_START, STRING_END, LINE_START, LINE_END, JAVA_Z_STRING_END,
// BACKREFERENCE, ENDBACKREFERENCE, BACKREF_STRING
// }
// Path: karthik/regex/TransitionTable.java
import karthik.regex.RegexTokenNames;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
Integer starting_num_states = getNumStates();
Integer n2States = n2.getNumStates();
contains_backref = contains_backref | n2.contains_backref;
Integer oldStart = start;
Integer oldFinish = finish;
// clone matrix from TransitionTable n2 to new matrix
expand_table(n2States + 2);
for (Integer i = 0; i < n2States; i++)
for (Integer j : n2.get_all_transitions(i)) {
token = n2.getTransition(i, j);
setTransition(starting_num_states + i, starting_num_states + j,
token);
}
start = getNumStates() - 2;
finish = getNumStates() - 1;
// set e-transitions for new start_index state
setTransition(start, oldStart, eps);
setTransition(start, n2.getStart() + starting_num_states, eps);
// set e-transition to go to new finish state
setTransition(oldFinish, finish, eps);
setTransition(n2.getFinish() + starting_num_states, finish, eps);
return this;
}
TransitionTable plus(Integer quantGroupID, Integer uniqueID) {
// plus implemented as a+ = a.a* | RegexTokenNames tok_type = (uniqueID == Pattern.GREEDY_ID) ? RegexTokenNames.PLUS : RegexTokenNames.LAZY_PLUS; |
BuildmLearn/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/Constants.java | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/VideoContract.java
// public class VideoContract {
//
// public static final class Videos implements BaseColumns {
//
// public static final String TABLE_NAME = "videos";
//
// public static final String TITLE = "title";
// public static final String DESCRIPTION = "description";
// public static final String LINK = "link";
// public static final String THUMBNAIL_URL = "thumbnail_url";
//
// }
// }
| import org.buildmlearn.toolkit.videocollectiontemplate.data.VideoContract; | package org.buildmlearn.toolkit.videocollectiontemplate;
/**
* @brief Constants used in video collection template's simulator relating databases.
* <p/>
* Created by Anupam (opticod) on 13/5/16.
*/
public class Constants {
public static final String[] VIDEO_COLUMNS = { | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/VideoContract.java
// public class VideoContract {
//
// public static final class Videos implements BaseColumns {
//
// public static final String TABLE_NAME = "videos";
//
// public static final String TITLE = "title";
// public static final String DESCRIPTION = "description";
// public static final String LINK = "link";
// public static final String THUMBNAIL_URL = "thumbnail_url";
//
// }
// }
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/Constants.java
import org.buildmlearn.toolkit.videocollectiontemplate.data.VideoContract;
package org.buildmlearn.toolkit.videocollectiontemplate;
/**
* @brief Constants used in video collection template's simulator relating databases.
* <p/>
* Created by Anupam (opticod) on 13/5/16.
*/
public class Constants {
public static final String[] VIDEO_COLUMNS = { | VideoContract.Videos.TABLE_NAME + "." + VideoContract.Videos._ID, |
BuildmLearn/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/DataUtils.java | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/Constants.java
// public class Constants {
// public static final String[] VIDEO_COLUMNS = {
// VideoContract.Videos.TABLE_NAME + "." + VideoContract.Videos._ID,
// VideoContract.Videos.TITLE,
// VideoContract.Videos.DESCRIPTION,
// VideoContract.Videos.LINK,
// VideoContract.Videos.THUMBNAIL_URL
// };
// public static final int COL_TITLE = 1;
// public static final int COL_DESCRIPTION = 2;
// public static final int COL_LINK = 3;
// public static final int COL_THUMBNAIL_URL = 4;
// public static String XMLFileName = "video_content.xml";
// }
| import org.buildmlearn.toolkit.videocollectiontemplate.Constants;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; | package org.buildmlearn.toolkit.videocollectiontemplate.data;
/**
* @brief Contains xml data utils for video collection template's simulator.
* <p/>
* Created by Anupam (opticod) on 13/5/16.
*/
public class DataUtils {
public static String[] readTitleAuthor() {
String result[] = new String[2];
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db;
Document doc;
try { | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/Constants.java
// public class Constants {
// public static final String[] VIDEO_COLUMNS = {
// VideoContract.Videos.TABLE_NAME + "." + VideoContract.Videos._ID,
// VideoContract.Videos.TITLE,
// VideoContract.Videos.DESCRIPTION,
// VideoContract.Videos.LINK,
// VideoContract.Videos.THUMBNAIL_URL
// };
// public static final int COL_TITLE = 1;
// public static final int COL_DESCRIPTION = 2;
// public static final int COL_LINK = 3;
// public static final int COL_THUMBNAIL_URL = 4;
// public static String XMLFileName = "video_content.xml";
// }
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/DataUtils.java
import org.buildmlearn.toolkit.videocollectiontemplate.Constants;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
package org.buildmlearn.toolkit.videocollectiontemplate.data;
/**
* @brief Contains xml data utils for video collection template's simulator.
* <p/>
* Created by Anupam (opticod) on 13/5/16.
*/
public class DataUtils {
public static String[] readTitleAuthor() {
String result[] = new String[2];
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db;
Document doc;
try { | File fXmlFile = new File(Constants.XMLFileName); |
BuildmLearn/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/fragment/LoadApkFragment.java | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/ToolkitApplication.java
// public class ToolkitApplication extends Application {
//
// private static String dir;
//
// private static boolean isExternalStorageAvailable = false;
//
// /**
// * @return Folder path
// * @brief Returns folder path for unzipped apks
// */
// public static String getUnZipDir() {
// return dir + Constants.UNZIP;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// storagePathsValidate();
// }
//
// public void storagePathsValidate() {
// if (checkExternalStorage()) {
// isExternalStorageAvailable = true;
// dir = Environment.getExternalStorageDirectory().getAbsolutePath();
// } else {
// dir = getFilesDir().getAbsolutePath();
// }
//
// ArrayList<String> paths = new ArrayList<>();
// paths.add(getProjectDir());
// paths.add(getApkDir());
// paths.add(getSavedDir());
// paths.add(getUnZipDir());
//
// for (String path : paths) {
// File f = new File(path);
// if (!f.isDirectory()) {
// f.mkdirs();
// }
// }
// }
//
// /**
// * @return folder file
// * @brief Returns external storage directory.
// */
// public File getDir() {
// return Environment.getExternalStorageDirectory();
// }
//
// /**
// * @return folder path
// * @brief Returns directory for BuildmLearn toolkit manually created files.
// */
// public String getProjectDir() {
// return dir + Constants.BUILD_M_LEARN_PATH;
//
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for saved projects
// */
// public String getSavedDir() {
// return dir + Constants.SAVED_DIR;
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for saved projects
// */
// public String getDraftDir() {
// return dir + Constants.DRAFT_DIR;
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for storing generated apks
// */
// public String getApkDir() {
// return dir + Constants.APK_DIR;
// }
//
// /**
// * @return true if external storage is present, else false
// * @brief Checks if external storage is present for storing data
// */
// public boolean checkExternalStorage() {
//
// boolean result = false;
// File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/BuildmLearn123/");
// if (!f.isDirectory()) {
// result = f.mkdirs();
// f.delete();
// }
// return result;
// }
//
// public boolean isExternalStorageAvailable() {
// return isExternalStorageAvailable;
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for Download directory
// */
// public String getDownloadDirectory() {
// return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
// }
// }
| import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.ToolkitApplication;
import org.buildmlearn.toolkit.adapter.SavedApiAdapter;
import org.buildmlearn.toolkit.model.SavedApi;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator; | package org.buildmlearn.toolkit.fragment;
/**
* Created by opticod (Anupam Das) on 29/2/16.
*
* @brief Fragment used for loading existing APKs into a list.
*/
public class LoadApkFragment extends Fragment implements AbsListView.OnItemClickListener {
private static final String TAG = "Load API Fragment";
private AbsListView mListView;
private boolean showTemplateSelectedMenu;
private SavedApiAdapter mAdapter; | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/ToolkitApplication.java
// public class ToolkitApplication extends Application {
//
// private static String dir;
//
// private static boolean isExternalStorageAvailable = false;
//
// /**
// * @return Folder path
// * @brief Returns folder path for unzipped apks
// */
// public static String getUnZipDir() {
// return dir + Constants.UNZIP;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// storagePathsValidate();
// }
//
// public void storagePathsValidate() {
// if (checkExternalStorage()) {
// isExternalStorageAvailable = true;
// dir = Environment.getExternalStorageDirectory().getAbsolutePath();
// } else {
// dir = getFilesDir().getAbsolutePath();
// }
//
// ArrayList<String> paths = new ArrayList<>();
// paths.add(getProjectDir());
// paths.add(getApkDir());
// paths.add(getSavedDir());
// paths.add(getUnZipDir());
//
// for (String path : paths) {
// File f = new File(path);
// if (!f.isDirectory()) {
// f.mkdirs();
// }
// }
// }
//
// /**
// * @return folder file
// * @brief Returns external storage directory.
// */
// public File getDir() {
// return Environment.getExternalStorageDirectory();
// }
//
// /**
// * @return folder path
// * @brief Returns directory for BuildmLearn toolkit manually created files.
// */
// public String getProjectDir() {
// return dir + Constants.BUILD_M_LEARN_PATH;
//
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for saved projects
// */
// public String getSavedDir() {
// return dir + Constants.SAVED_DIR;
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for saved projects
// */
// public String getDraftDir() {
// return dir + Constants.DRAFT_DIR;
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for storing generated apks
// */
// public String getApkDir() {
// return dir + Constants.APK_DIR;
// }
//
// /**
// * @return true if external storage is present, else false
// * @brief Checks if external storage is present for storing data
// */
// public boolean checkExternalStorage() {
//
// boolean result = false;
// File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/BuildmLearn123/");
// if (!f.isDirectory()) {
// result = f.mkdirs();
// f.delete();
// }
// return result;
// }
//
// public boolean isExternalStorageAvailable() {
// return isExternalStorageAvailable;
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for Download directory
// */
// public String getDownloadDirectory() {
// return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
// }
// }
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/fragment/LoadApkFragment.java
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.ToolkitApplication;
import org.buildmlearn.toolkit.adapter.SavedApiAdapter;
import org.buildmlearn.toolkit.model.SavedApi;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
package org.buildmlearn.toolkit.fragment;
/**
* Created by opticod (Anupam Das) on 29/2/16.
*
* @brief Fragment used for loading existing APKs into a list.
*/
public class LoadApkFragment extends Fragment implements AbsListView.OnItemClickListener {
private static final String TAG = "Load API Fragment";
private AbsListView mListView;
private boolean showTemplateSelectedMenu;
private SavedApiAdapter mAdapter; | private ToolkitApplication mToolkit; |
BuildmLearn/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/activity/SettingsLinkerActivity.java | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/constant/Constants.java
// public class
// Constants {
//
// public final static String BUILD_M_LEARN_PATH = "/BuildmLearn/";
// public final static String UNZIP = BUILD_M_LEARN_PATH + "unzipped/";
// public final static String APK_DIR = BUILD_M_LEARN_PATH + "apk/";
// public final static String SAVED_DIR = BUILD_M_LEARN_PATH + "saved/";
// public final static String DRAFT_DIR = BUILD_M_LEARN_PATH + "draft/";
// public final static String TEMPLATE_ID = "TEMPLATE_ID";
// public final static String TEMPLATE_OBJECT = "TEMPLATE_OBJECT";
// public final static String SIMULATOR_FILE_PATH = "SIMULATOR_FILE_PATH";
// public final static String PROJECT_FILE_PATH = "PROJECT_FILE_PATH";
// public final static String START_ACTIVITY = "START_ACTIVITY";
// public final static String START_FRAGMENT = "START_FRAGMENT";
//
//
// }
| import android.os.Bundle;
import org.buildmlearn.toolkit.constant.Constants;
import android.app.Activity;
import android.content.Intent; | package org.buildmlearn.toolkit.activity;
/**
* Created by Anupam (Opticod) on 7/4/16.
*/
/**
* @brief Activity responsible for changing settings from android settings menu
* <p/>
* This activity is started whenever users clicks App Settings under App notifications in android settings menu.
*/
public class SettingsLinkerActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, HomeActivity.class); | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/constant/Constants.java
// public class
// Constants {
//
// public final static String BUILD_M_LEARN_PATH = "/BuildmLearn/";
// public final static String UNZIP = BUILD_M_LEARN_PATH + "unzipped/";
// public final static String APK_DIR = BUILD_M_LEARN_PATH + "apk/";
// public final static String SAVED_DIR = BUILD_M_LEARN_PATH + "saved/";
// public final static String DRAFT_DIR = BUILD_M_LEARN_PATH + "draft/";
// public final static String TEMPLATE_ID = "TEMPLATE_ID";
// public final static String TEMPLATE_OBJECT = "TEMPLATE_OBJECT";
// public final static String SIMULATOR_FILE_PATH = "SIMULATOR_FILE_PATH";
// public final static String PROJECT_FILE_PATH = "PROJECT_FILE_PATH";
// public final static String START_ACTIVITY = "START_ACTIVITY";
// public final static String START_FRAGMENT = "START_FRAGMENT";
//
//
// }
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/activity/SettingsLinkerActivity.java
import android.os.Bundle;
import org.buildmlearn.toolkit.constant.Constants;
import android.app.Activity;
import android.content.Intent;
package org.buildmlearn.toolkit.activity;
/**
* Created by Anupam (Opticod) on 7/4/16.
*/
/**
* @brief Activity responsible for changing settings from android settings menu
* <p/>
* This activity is started whenever users clicks App Settings under App notifications in android settings menu.
*/
public class SettingsLinkerActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, HomeActivity.class); | intent.putExtra(Constants.START_FRAGMENT, 3); |
BuildmLearn/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/matchtemplate/fragment/MainFragment.java | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/matchtemplate/data/MatchModel.java
// public class MatchModel implements Parcelable {
// public final static Creator<MatchModel> CREATOR = new Creator<MatchModel>() {
// @Override
// public MatchModel createFromParcel(Parcel parcel) {
// return new MatchModel(parcel);
// }
//
// @Override
// public MatchModel[] newArray(int size) {
// return new MatchModel[size];
// }
// };
//
// private String matchA;
// private String matchB;
// private int correct;
//
// public MatchModel() {
//
// }
//
// private MatchModel(Parcel in) {
// this.matchA = in.readString();
// this.matchB = in.readString();
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(matchA);
// dest.writeString(matchB);
// }
//
// public int getCorrect() {
// return correct;
// }
//
// public void setCorrect(int correct) {
// this.correct = correct;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// public String getMatchA() {
// return matchA;
// }
//
// public void setMatchA(String matchA) {
// this.matchA = matchA;
// }
//
// public String getMatchB() {
// return matchB;
// }
//
// public void setMatchB(String matchB) {
// this.matchB = matchB;
// }
//
// }
| import android.app.FragmentManager;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.matchtemplate.Constants;
import org.buildmlearn.toolkit.matchtemplate.adapter.MatchArrayAdapter_A;
import org.buildmlearn.toolkit.matchtemplate.adapter.MatchArrayAdapter_B;
import org.buildmlearn.toolkit.matchtemplate.data.MatchDb;
import org.buildmlearn.toolkit.matchtemplate.data.MatchModel;
import java.util.ArrayList;
import java.util.Collections; | package org.buildmlearn.toolkit.matchtemplate.fragment;
/**
* Created by Anupam (opticod) on 24/7/16.
*/
/**
* @brief Fragment for the users to match column A with column B in match template's simulator.
*/
public class MainFragment extends Fragment {
private static final String SELECTED_KEY_A = "selected_position_a";
private static final String SELECTED_KEY_B = "selected_position_b";
private MatchArrayAdapter_A matchListAdapterA;
private MatchArrayAdapter_B matchListAdapterB;
private int mPositionA = ListView.INVALID_POSITION;
private int mPositionB = ListView.INVALID_POSITION;
private ListView listViewA;
private ListView listViewB;
| // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/matchtemplate/data/MatchModel.java
// public class MatchModel implements Parcelable {
// public final static Creator<MatchModel> CREATOR = new Creator<MatchModel>() {
// @Override
// public MatchModel createFromParcel(Parcel parcel) {
// return new MatchModel(parcel);
// }
//
// @Override
// public MatchModel[] newArray(int size) {
// return new MatchModel[size];
// }
// };
//
// private String matchA;
// private String matchB;
// private int correct;
//
// public MatchModel() {
//
// }
//
// private MatchModel(Parcel in) {
// this.matchA = in.readString();
// this.matchB = in.readString();
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(matchA);
// dest.writeString(matchB);
// }
//
// public int getCorrect() {
// return correct;
// }
//
// public void setCorrect(int correct) {
// this.correct = correct;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// public String getMatchA() {
// return matchA;
// }
//
// public void setMatchA(String matchA) {
// this.matchA = matchA;
// }
//
// public String getMatchB() {
// return matchB;
// }
//
// public void setMatchB(String matchB) {
// this.matchB = matchB;
// }
//
// }
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/matchtemplate/fragment/MainFragment.java
import android.app.FragmentManager;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.matchtemplate.Constants;
import org.buildmlearn.toolkit.matchtemplate.adapter.MatchArrayAdapter_A;
import org.buildmlearn.toolkit.matchtemplate.adapter.MatchArrayAdapter_B;
import org.buildmlearn.toolkit.matchtemplate.data.MatchDb;
import org.buildmlearn.toolkit.matchtemplate.data.MatchModel;
import java.util.ArrayList;
import java.util.Collections;
package org.buildmlearn.toolkit.matchtemplate.fragment;
/**
* Created by Anupam (opticod) on 24/7/16.
*/
/**
* @brief Fragment for the users to match column A with column B in match template's simulator.
*/
public class MainFragment extends Fragment {
private static final String SELECTED_KEY_A = "selected_position_a";
private static final String SELECTED_KEY_B = "selected_position_b";
private MatchArrayAdapter_A matchListAdapterA;
private MatchArrayAdapter_B matchListAdapterB;
private int mPositionA = ListView.INVALID_POSITION;
private int mPositionB = ListView.INVALID_POSITION;
private ListView listViewA;
private ListView listViewB;
| private ArrayList<MatchModel> matchListA; |
BuildmLearn/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/VideoDBHelper.java | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/VideoContract.java
// public static final class Videos implements BaseColumns {
//
// public static final String TABLE_NAME = "videos";
//
// public static final String TITLE = "title";
// public static final String DESCRIPTION = "description";
// public static final String LINK = "link";
// public static final String THUMBNAIL_URL = "thumbnail_url";
//
// }
| import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import org.buildmlearn.toolkit.videocollectiontemplate.data.VideoContract.Videos; | package org.buildmlearn.toolkit.videocollectiontemplate.data;
/**
* @brief DatabaseHelper for video collection template's simulator.
* <p/>
* Created by Anupam (opticod) on 13/5/16.
*/
class VideoDBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "video.db";
private static final int DATABASE_VERSION = 1;
public VideoDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) { | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/VideoContract.java
// public static final class Videos implements BaseColumns {
//
// public static final String TABLE_NAME = "videos";
//
// public static final String TITLE = "title";
// public static final String DESCRIPTION = "description";
// public static final String LINK = "link";
// public static final String THUMBNAIL_URL = "thumbnail_url";
//
// }
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/VideoDBHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import org.buildmlearn.toolkit.videocollectiontemplate.data.VideoContract.Videos;
package org.buildmlearn.toolkit.videocollectiontemplate.data;
/**
* @brief DatabaseHelper for video collection template's simulator.
* <p/>
* Created by Anupam (opticod) on 13/5/16.
*/
class VideoDBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "video.db";
private static final int DATABASE_VERSION = 1;
public VideoDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) { | final String SQL_CREATE__TABLE = "CREATE TABLE " + Videos.TABLE_NAME + " (" + |
BuildmLearn/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/fragment/DetailActivityFragment.java | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/Constants.java
// public class Constants {
// public static final String[] VIDEO_COLUMNS = {
// VideoContract.Videos.TABLE_NAME + "." + VideoContract.Videos._ID,
// VideoContract.Videos.TITLE,
// VideoContract.Videos.DESCRIPTION,
// VideoContract.Videos.LINK,
// VideoContract.Videos.THUMBNAIL_URL
// };
// public static final int COL_TITLE = 1;
// public static final int COL_DESCRIPTION = 2;
// public static final int COL_LINK = 3;
// public static final int COL_THUMBNAIL_URL = 4;
// public static String XMLFileName = "video_content.xml";
// }
| import android.app.FragmentManager;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.videocollectiontemplate.Constants;
import org.buildmlearn.toolkit.videocollectiontemplate.data.VideoDb; | AlertDialog welcomeAlert = builder.create();
welcomeAlert.show();
assert welcomeAlert.findViewById(android.R.id.message) != null;
assert welcomeAlert.findViewById(android.R.id.message) != null;
assert ((TextView) welcomeAlert.findViewById(android.R.id.message)) != null;
((TextView) welcomeAlert.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
break;
default: //do nothing
break;
}
return true;
}
});
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(DETAIL_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if (null != video_Id) {
switch (id) {
case DETAIL_LOADER:
| // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/Constants.java
// public class Constants {
// public static final String[] VIDEO_COLUMNS = {
// VideoContract.Videos.TABLE_NAME + "." + VideoContract.Videos._ID,
// VideoContract.Videos.TITLE,
// VideoContract.Videos.DESCRIPTION,
// VideoContract.Videos.LINK,
// VideoContract.Videos.THUMBNAIL_URL
// };
// public static final int COL_TITLE = 1;
// public static final int COL_DESCRIPTION = 2;
// public static final int COL_LINK = 3;
// public static final int COL_THUMBNAIL_URL = 4;
// public static String XMLFileName = "video_content.xml";
// }
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/fragment/DetailActivityFragment.java
import android.app.FragmentManager;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.videocollectiontemplate.Constants;
import org.buildmlearn.toolkit.videocollectiontemplate.data.VideoDb;
AlertDialog welcomeAlert = builder.create();
welcomeAlert.show();
assert welcomeAlert.findViewById(android.R.id.message) != null;
assert welcomeAlert.findViewById(android.R.id.message) != null;
assert ((TextView) welcomeAlert.findViewById(android.R.id.message)) != null;
((TextView) welcomeAlert.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
break;
default: //do nothing
break;
}
return true;
}
});
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(DETAIL_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if (null != video_Id) {
switch (id) {
case DETAIL_LOADER:
| return new CursorLoader(getActivity(), null, Constants.VIDEO_COLUMNS, null, null, null) { |
BuildmLearn/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/utilities/RestoreThread.java | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/ToolkitApplication.java
// public class ToolkitApplication extends Application {
//
// private static String dir;
//
// private static boolean isExternalStorageAvailable = false;
//
// /**
// * @return Folder path
// * @brief Returns folder path for unzipped apks
// */
// public static String getUnZipDir() {
// return dir + Constants.UNZIP;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// storagePathsValidate();
// }
//
// public void storagePathsValidate() {
// if (checkExternalStorage()) {
// isExternalStorageAvailable = true;
// dir = Environment.getExternalStorageDirectory().getAbsolutePath();
// } else {
// dir = getFilesDir().getAbsolutePath();
// }
//
// ArrayList<String> paths = new ArrayList<>();
// paths.add(getProjectDir());
// paths.add(getApkDir());
// paths.add(getSavedDir());
// paths.add(getUnZipDir());
//
// for (String path : paths) {
// File f = new File(path);
// if (!f.isDirectory()) {
// f.mkdirs();
// }
// }
// }
//
// /**
// * @return folder file
// * @brief Returns external storage directory.
// */
// public File getDir() {
// return Environment.getExternalStorageDirectory();
// }
//
// /**
// * @return folder path
// * @brief Returns directory for BuildmLearn toolkit manually created files.
// */
// public String getProjectDir() {
// return dir + Constants.BUILD_M_LEARN_PATH;
//
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for saved projects
// */
// public String getSavedDir() {
// return dir + Constants.SAVED_DIR;
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for saved projects
// */
// public String getDraftDir() {
// return dir + Constants.DRAFT_DIR;
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for storing generated apks
// */
// public String getApkDir() {
// return dir + Constants.APK_DIR;
// }
//
// /**
// * @return true if external storage is present, else false
// * @brief Checks if external storage is present for storing data
// */
// public boolean checkExternalStorage() {
//
// boolean result = false;
// File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/BuildmLearn123/");
// if (!f.isDirectory()) {
// result = f.mkdirs();
// f.delete();
// }
// return result;
// }
//
// public boolean isExternalStorageAvailable() {
// return isExternalStorageAvailable;
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for Download directory
// */
// public String getDownloadDirectory() {
// return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
// }
// }
| import android.content.Context;
import org.buildmlearn.toolkit.ToolkitApplication;
import org.buildmlearn.toolkit.model.Template;
import java.io.File;
import java.io.IOException;
import java.io.InputStream; | package org.buildmlearn.toolkit.utilities;
/**
* Created by scopeinfinity on 14/3/16.
*/
/**
* @brief Class for extracting .buildmlearn file from apk.
*/
public class RestoreThread extends Thread {
private static final String TEMP_FOLDER = "rtf";
private final Context context;
private final InputStream zipInputStream;
private OnRestoreComplete listener;
public RestoreThread(Context context, InputStream zipInputStream) {
this.context = context;
this.zipInputStream = zipInputStream;
}
public void setRestoreListener(OnRestoreComplete listener) {
this.listener = listener;
}
@Override
public void run() {
try {
String assetDirectory = "assets"; | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/ToolkitApplication.java
// public class ToolkitApplication extends Application {
//
// private static String dir;
//
// private static boolean isExternalStorageAvailable = false;
//
// /**
// * @return Folder path
// * @brief Returns folder path for unzipped apks
// */
// public static String getUnZipDir() {
// return dir + Constants.UNZIP;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// storagePathsValidate();
// }
//
// public void storagePathsValidate() {
// if (checkExternalStorage()) {
// isExternalStorageAvailable = true;
// dir = Environment.getExternalStorageDirectory().getAbsolutePath();
// } else {
// dir = getFilesDir().getAbsolutePath();
// }
//
// ArrayList<String> paths = new ArrayList<>();
// paths.add(getProjectDir());
// paths.add(getApkDir());
// paths.add(getSavedDir());
// paths.add(getUnZipDir());
//
// for (String path : paths) {
// File f = new File(path);
// if (!f.isDirectory()) {
// f.mkdirs();
// }
// }
// }
//
// /**
// * @return folder file
// * @brief Returns external storage directory.
// */
// public File getDir() {
// return Environment.getExternalStorageDirectory();
// }
//
// /**
// * @return folder path
// * @brief Returns directory for BuildmLearn toolkit manually created files.
// */
// public String getProjectDir() {
// return dir + Constants.BUILD_M_LEARN_PATH;
//
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for saved projects
// */
// public String getSavedDir() {
// return dir + Constants.SAVED_DIR;
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for saved projects
// */
// public String getDraftDir() {
// return dir + Constants.DRAFT_DIR;
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for storing generated apks
// */
// public String getApkDir() {
// return dir + Constants.APK_DIR;
// }
//
// /**
// * @return true if external storage is present, else false
// * @brief Checks if external storage is present for storing data
// */
// public boolean checkExternalStorage() {
//
// boolean result = false;
// File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/BuildmLearn123/");
// if (!f.isDirectory()) {
// result = f.mkdirs();
// f.delete();
// }
// return result;
// }
//
// public boolean isExternalStorageAvailable() {
// return isExternalStorageAvailable;
// }
//
// /**
// * @return Folder path
// * @brief Returns folder path for Download directory
// */
// public String getDownloadDirectory() {
// return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
// }
// }
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/utilities/RestoreThread.java
import android.content.Context;
import org.buildmlearn.toolkit.ToolkitApplication;
import org.buildmlearn.toolkit.model.Template;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
package org.buildmlearn.toolkit.utilities;
/**
* Created by scopeinfinity on 14/3/16.
*/
/**
* @brief Class for extracting .buildmlearn file from apk.
*/
public class RestoreThread extends Thread {
private static final String TEMP_FOLDER = "rtf";
private final Context context;
private final InputStream zipInputStream;
private OnRestoreComplete listener;
public RestoreThread(Context context, InputStream zipInputStream) {
this.context = context;
this.zipInputStream = zipInputStream;
}
public void setRestoreListener(OnRestoreComplete listener) {
this.listener = listener;
}
@Override
public void run() {
try {
String assetDirectory = "assets"; | File assetDir = new File(ToolkitApplication.getUnZipDir() + TEMP_FOLDER + "/" + assetDirectory); |
BuildmLearn/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/FetchXMLTask.java | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/Constants.java
// public class Constants {
// public static final String[] VIDEO_COLUMNS = {
// VideoContract.Videos.TABLE_NAME + "." + VideoContract.Videos._ID,
// VideoContract.Videos.TITLE,
// VideoContract.Videos.DESCRIPTION,
// VideoContract.Videos.LINK,
// VideoContract.Videos.THUMBNAIL_URL
// };
// public static final int COL_TITLE = 1;
// public static final int COL_DESCRIPTION = 2;
// public static final int COL_LINK = 3;
// public static final int COL_THUMBNAIL_URL = 4;
// public static String XMLFileName = "video_content.xml";
// }
| import android.content.ContentValues;
import android.content.Context;
import android.os.AsyncTask;
import org.buildmlearn.toolkit.videocollectiontemplate.Constants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; | videoValues.put(VideoContract.Videos.THUMBNAIL_URL, thumbnail_url);
cVVector.add(videoValues);
}
// add to database
if (cVVector.size() > 0) {
ContentValues[] cvArray = new ContentValues[cVVector.size()];
cVVector.toArray(cvArray);
VideoDb db = new VideoDb(mContext);
db.open();
db.bulkInsert(cvArray);
db.close();
}
}
@Override
protected Void doInBackground(String... params) {
if (params.length == 0) {
return null;
}
ArrayList<VideoModel> mList;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db;
Document doc;
try { | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/Constants.java
// public class Constants {
// public static final String[] VIDEO_COLUMNS = {
// VideoContract.Videos.TABLE_NAME + "." + VideoContract.Videos._ID,
// VideoContract.Videos.TITLE,
// VideoContract.Videos.DESCRIPTION,
// VideoContract.Videos.LINK,
// VideoContract.Videos.THUMBNAIL_URL
// };
// public static final int COL_TITLE = 1;
// public static final int COL_DESCRIPTION = 2;
// public static final int COL_LINK = 3;
// public static final int COL_THUMBNAIL_URL = 4;
// public static String XMLFileName = "video_content.xml";
// }
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/FetchXMLTask.java
import android.content.ContentValues;
import android.content.Context;
import android.os.AsyncTask;
import org.buildmlearn.toolkit.videocollectiontemplate.Constants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
videoValues.put(VideoContract.Videos.THUMBNAIL_URL, thumbnail_url);
cVVector.add(videoValues);
}
// add to database
if (cVVector.size() > 0) {
ContentValues[] cvArray = new ContentValues[cVVector.size()];
cVVector.toArray(cvArray);
VideoDb db = new VideoDb(mContext);
db.open();
db.bulkInsert(cvArray);
db.close();
}
}
@Override
protected Void doInBackground(String... params) {
if (params.length == 0) {
return null;
}
ArrayList<VideoModel> mList;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db;
Document doc;
try { | File fXmlFile = new File(Constants.XMLFileName); |
BuildmLearn/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/activity/TutorialActivity.java | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/adapter/TutorialAdapter.java
// public class TutorialAdapter extends PagerAdapter {
//
// private final Activity mActivity;
// private final Tutorial[] mTutorials;
// private final ListColor[] colors = ListColor.values();
// private final boolean mStartActivity;
//
// public TutorialAdapter(Activity activity, boolean startActivity) {
// mActivity = activity;
// mTutorials = Tutorial.values();
// this.mStartActivity = startActivity;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public int getCount() {
// return mTutorials.length;
// }
//
//
// private Tutorial getItem(int position) {
// return mTutorials[position];
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Object instantiateItem(ViewGroup container, final int position) {
//
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mActivity);
// boolean SkipTutorial = prefs.getBoolean("SkipTutorial",false);
//
// LayoutInflater inflater = (LayoutInflater) container.getContext()
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//
// Tutorial tutorial = getItem(position);
//
//
// View convertView;
// if (tutorial.isLastScreen()) {
// convertView = inflater.inflate(R.layout.tutorial_layout_finish, null);
//
// convertView.findViewById(R.id.finish_tutorial_button).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (mStartActivity) {
// mActivity.startActivity(new Intent(mActivity, HomeActivity.class));
// }
// mActivity.finish();
// }
// });
// } else {
// convertView = inflater.inflate(R.layout.tutorial_layout, null);
// View skip_button = convertView.findViewById(R.id.skip_button);
// skip_button.setVisibility(View.GONE);
// ImageView deviceImage = (ImageView) convertView
// .findViewById(R.id.device_image);
// TextView title = (TextView) convertView
// .findViewById(R.id.tutorial_title);
// TextView description = (TextView) convertView
// .findViewById(R.id.tutorial_desc);
//
// int color = colors[position % colors.length].getColor();
//
// convertView.findViewById(R.id.tutorial_layout).setBackgroundColor(color);
//
// deviceImage.setImageResource(tutorial.getImage());
// title.setText(tutorial.getTitle());
// description.setText(tutorial.getDescription());
// if(!SkipTutorial) {
// skip_button.setVisibility(View.VISIBLE);
// }
// convertView.findViewById(R.id.skip_button).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (mStartActivity) {
// mActivity.startActivity(new Intent(mActivity, HomeActivity.class));
// }
// mActivity.finish();
// }
// });
// }
// container.addView(convertView, 0);
//
// return convertView;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean isViewFromObject(View view, Object object) {
// return view.equals(object);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void destroyItem(ViewGroup container, int position, Object object) {
// container.removeView((ViewGroup) object);
// }
//
// private enum ListColor {
// BLUE("#29A6D4"),
// GREEN("#1C7D6C"),
// ORANGE("#F77400"),
// RED("#F53B3C"),
// GRAYISH("#78909C"),
// PURPLE("#AB47BC"),
// YELLOW("#F9A01E");
//
// private
// @ColorRes
// final
// int color;
//
// ListColor(String colorCode) {
// this.color = Color.parseColor(colorCode);
// }
//
// public int getColor() {
// return color;
// }
// }
//
// }
//
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/constant/Constants.java
// public class
// Constants {
//
// public final static String BUILD_M_LEARN_PATH = "/BuildmLearn/";
// public final static String UNZIP = BUILD_M_LEARN_PATH + "unzipped/";
// public final static String APK_DIR = BUILD_M_LEARN_PATH + "apk/";
// public final static String SAVED_DIR = BUILD_M_LEARN_PATH + "saved/";
// public final static String DRAFT_DIR = BUILD_M_LEARN_PATH + "draft/";
// public final static String TEMPLATE_ID = "TEMPLATE_ID";
// public final static String TEMPLATE_OBJECT = "TEMPLATE_OBJECT";
// public final static String SIMULATOR_FILE_PATH = "SIMULATOR_FILE_PATH";
// public final static String PROJECT_FILE_PATH = "PROJECT_FILE_PATH";
// public final static String START_ACTIVITY = "START_ACTIVITY";
// public final static String START_FRAGMENT = "START_FRAGMENT";
//
//
// }
| import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.util.TypedValue;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.adapter.TutorialAdapter;
import org.buildmlearn.toolkit.constant.Constants;
import org.buildmlearn.toolkit.model.Tutorial; | package org.buildmlearn.toolkit.activity;
/**
* @brief Shows the tutorial related to BuildmLearn toolkit usage.
*/
public class TutorialActivity extends AppCompatActivity {
private LinearLayout indicatingDotsContainer;
/**
* {@inheritDoc}
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutorial);
| // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/adapter/TutorialAdapter.java
// public class TutorialAdapter extends PagerAdapter {
//
// private final Activity mActivity;
// private final Tutorial[] mTutorials;
// private final ListColor[] colors = ListColor.values();
// private final boolean mStartActivity;
//
// public TutorialAdapter(Activity activity, boolean startActivity) {
// mActivity = activity;
// mTutorials = Tutorial.values();
// this.mStartActivity = startActivity;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public int getCount() {
// return mTutorials.length;
// }
//
//
// private Tutorial getItem(int position) {
// return mTutorials[position];
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Object instantiateItem(ViewGroup container, final int position) {
//
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mActivity);
// boolean SkipTutorial = prefs.getBoolean("SkipTutorial",false);
//
// LayoutInflater inflater = (LayoutInflater) container.getContext()
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//
// Tutorial tutorial = getItem(position);
//
//
// View convertView;
// if (tutorial.isLastScreen()) {
// convertView = inflater.inflate(R.layout.tutorial_layout_finish, null);
//
// convertView.findViewById(R.id.finish_tutorial_button).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (mStartActivity) {
// mActivity.startActivity(new Intent(mActivity, HomeActivity.class));
// }
// mActivity.finish();
// }
// });
// } else {
// convertView = inflater.inflate(R.layout.tutorial_layout, null);
// View skip_button = convertView.findViewById(R.id.skip_button);
// skip_button.setVisibility(View.GONE);
// ImageView deviceImage = (ImageView) convertView
// .findViewById(R.id.device_image);
// TextView title = (TextView) convertView
// .findViewById(R.id.tutorial_title);
// TextView description = (TextView) convertView
// .findViewById(R.id.tutorial_desc);
//
// int color = colors[position % colors.length].getColor();
//
// convertView.findViewById(R.id.tutorial_layout).setBackgroundColor(color);
//
// deviceImage.setImageResource(tutorial.getImage());
// title.setText(tutorial.getTitle());
// description.setText(tutorial.getDescription());
// if(!SkipTutorial) {
// skip_button.setVisibility(View.VISIBLE);
// }
// convertView.findViewById(R.id.skip_button).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (mStartActivity) {
// mActivity.startActivity(new Intent(mActivity, HomeActivity.class));
// }
// mActivity.finish();
// }
// });
// }
// container.addView(convertView, 0);
//
// return convertView;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean isViewFromObject(View view, Object object) {
// return view.equals(object);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void destroyItem(ViewGroup container, int position, Object object) {
// container.removeView((ViewGroup) object);
// }
//
// private enum ListColor {
// BLUE("#29A6D4"),
// GREEN("#1C7D6C"),
// ORANGE("#F77400"),
// RED("#F53B3C"),
// GRAYISH("#78909C"),
// PURPLE("#AB47BC"),
// YELLOW("#F9A01E");
//
// private
// @ColorRes
// final
// int color;
//
// ListColor(String colorCode) {
// this.color = Color.parseColor(colorCode);
// }
//
// public int getColor() {
// return color;
// }
// }
//
// }
//
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/constant/Constants.java
// public class
// Constants {
//
// public final static String BUILD_M_LEARN_PATH = "/BuildmLearn/";
// public final static String UNZIP = BUILD_M_LEARN_PATH + "unzipped/";
// public final static String APK_DIR = BUILD_M_LEARN_PATH + "apk/";
// public final static String SAVED_DIR = BUILD_M_LEARN_PATH + "saved/";
// public final static String DRAFT_DIR = BUILD_M_LEARN_PATH + "draft/";
// public final static String TEMPLATE_ID = "TEMPLATE_ID";
// public final static String TEMPLATE_OBJECT = "TEMPLATE_OBJECT";
// public final static String SIMULATOR_FILE_PATH = "SIMULATOR_FILE_PATH";
// public final static String PROJECT_FILE_PATH = "PROJECT_FILE_PATH";
// public final static String START_ACTIVITY = "START_ACTIVITY";
// public final static String START_FRAGMENT = "START_FRAGMENT";
//
//
// }
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/activity/TutorialActivity.java
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.util.TypedValue;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.adapter.TutorialAdapter;
import org.buildmlearn.toolkit.constant.Constants;
import org.buildmlearn.toolkit.model.Tutorial;
package org.buildmlearn.toolkit.activity;
/**
* @brief Shows the tutorial related to BuildmLearn toolkit usage.
*/
public class TutorialActivity extends AppCompatActivity {
private LinearLayout indicatingDotsContainer;
/**
* {@inheritDoc}
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutorial);
| TutorialAdapter mAdapter = new TutorialAdapter(this, getIntent().getBooleanExtra(Constants.START_ACTIVITY, false)); |
BuildmLearn/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/activity/TutorialActivity.java | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/adapter/TutorialAdapter.java
// public class TutorialAdapter extends PagerAdapter {
//
// private final Activity mActivity;
// private final Tutorial[] mTutorials;
// private final ListColor[] colors = ListColor.values();
// private final boolean mStartActivity;
//
// public TutorialAdapter(Activity activity, boolean startActivity) {
// mActivity = activity;
// mTutorials = Tutorial.values();
// this.mStartActivity = startActivity;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public int getCount() {
// return mTutorials.length;
// }
//
//
// private Tutorial getItem(int position) {
// return mTutorials[position];
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Object instantiateItem(ViewGroup container, final int position) {
//
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mActivity);
// boolean SkipTutorial = prefs.getBoolean("SkipTutorial",false);
//
// LayoutInflater inflater = (LayoutInflater) container.getContext()
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//
// Tutorial tutorial = getItem(position);
//
//
// View convertView;
// if (tutorial.isLastScreen()) {
// convertView = inflater.inflate(R.layout.tutorial_layout_finish, null);
//
// convertView.findViewById(R.id.finish_tutorial_button).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (mStartActivity) {
// mActivity.startActivity(new Intent(mActivity, HomeActivity.class));
// }
// mActivity.finish();
// }
// });
// } else {
// convertView = inflater.inflate(R.layout.tutorial_layout, null);
// View skip_button = convertView.findViewById(R.id.skip_button);
// skip_button.setVisibility(View.GONE);
// ImageView deviceImage = (ImageView) convertView
// .findViewById(R.id.device_image);
// TextView title = (TextView) convertView
// .findViewById(R.id.tutorial_title);
// TextView description = (TextView) convertView
// .findViewById(R.id.tutorial_desc);
//
// int color = colors[position % colors.length].getColor();
//
// convertView.findViewById(R.id.tutorial_layout).setBackgroundColor(color);
//
// deviceImage.setImageResource(tutorial.getImage());
// title.setText(tutorial.getTitle());
// description.setText(tutorial.getDescription());
// if(!SkipTutorial) {
// skip_button.setVisibility(View.VISIBLE);
// }
// convertView.findViewById(R.id.skip_button).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (mStartActivity) {
// mActivity.startActivity(new Intent(mActivity, HomeActivity.class));
// }
// mActivity.finish();
// }
// });
// }
// container.addView(convertView, 0);
//
// return convertView;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean isViewFromObject(View view, Object object) {
// return view.equals(object);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void destroyItem(ViewGroup container, int position, Object object) {
// container.removeView((ViewGroup) object);
// }
//
// private enum ListColor {
// BLUE("#29A6D4"),
// GREEN("#1C7D6C"),
// ORANGE("#F77400"),
// RED("#F53B3C"),
// GRAYISH("#78909C"),
// PURPLE("#AB47BC"),
// YELLOW("#F9A01E");
//
// private
// @ColorRes
// final
// int color;
//
// ListColor(String colorCode) {
// this.color = Color.parseColor(colorCode);
// }
//
// public int getColor() {
// return color;
// }
// }
//
// }
//
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/constant/Constants.java
// public class
// Constants {
//
// public final static String BUILD_M_LEARN_PATH = "/BuildmLearn/";
// public final static String UNZIP = BUILD_M_LEARN_PATH + "unzipped/";
// public final static String APK_DIR = BUILD_M_LEARN_PATH + "apk/";
// public final static String SAVED_DIR = BUILD_M_LEARN_PATH + "saved/";
// public final static String DRAFT_DIR = BUILD_M_LEARN_PATH + "draft/";
// public final static String TEMPLATE_ID = "TEMPLATE_ID";
// public final static String TEMPLATE_OBJECT = "TEMPLATE_OBJECT";
// public final static String SIMULATOR_FILE_PATH = "SIMULATOR_FILE_PATH";
// public final static String PROJECT_FILE_PATH = "PROJECT_FILE_PATH";
// public final static String START_ACTIVITY = "START_ACTIVITY";
// public final static String START_FRAGMENT = "START_FRAGMENT";
//
//
// }
| import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.util.TypedValue;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.adapter.TutorialAdapter;
import org.buildmlearn.toolkit.constant.Constants;
import org.buildmlearn.toolkit.model.Tutorial; | package org.buildmlearn.toolkit.activity;
/**
* @brief Shows the tutorial related to BuildmLearn toolkit usage.
*/
public class TutorialActivity extends AppCompatActivity {
private LinearLayout indicatingDotsContainer;
/**
* {@inheritDoc}
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutorial);
| // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/adapter/TutorialAdapter.java
// public class TutorialAdapter extends PagerAdapter {
//
// private final Activity mActivity;
// private final Tutorial[] mTutorials;
// private final ListColor[] colors = ListColor.values();
// private final boolean mStartActivity;
//
// public TutorialAdapter(Activity activity, boolean startActivity) {
// mActivity = activity;
// mTutorials = Tutorial.values();
// this.mStartActivity = startActivity;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public int getCount() {
// return mTutorials.length;
// }
//
//
// private Tutorial getItem(int position) {
// return mTutorials[position];
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Object instantiateItem(ViewGroup container, final int position) {
//
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mActivity);
// boolean SkipTutorial = prefs.getBoolean("SkipTutorial",false);
//
// LayoutInflater inflater = (LayoutInflater) container.getContext()
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//
// Tutorial tutorial = getItem(position);
//
//
// View convertView;
// if (tutorial.isLastScreen()) {
// convertView = inflater.inflate(R.layout.tutorial_layout_finish, null);
//
// convertView.findViewById(R.id.finish_tutorial_button).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (mStartActivity) {
// mActivity.startActivity(new Intent(mActivity, HomeActivity.class));
// }
// mActivity.finish();
// }
// });
// } else {
// convertView = inflater.inflate(R.layout.tutorial_layout, null);
// View skip_button = convertView.findViewById(R.id.skip_button);
// skip_button.setVisibility(View.GONE);
// ImageView deviceImage = (ImageView) convertView
// .findViewById(R.id.device_image);
// TextView title = (TextView) convertView
// .findViewById(R.id.tutorial_title);
// TextView description = (TextView) convertView
// .findViewById(R.id.tutorial_desc);
//
// int color = colors[position % colors.length].getColor();
//
// convertView.findViewById(R.id.tutorial_layout).setBackgroundColor(color);
//
// deviceImage.setImageResource(tutorial.getImage());
// title.setText(tutorial.getTitle());
// description.setText(tutorial.getDescription());
// if(!SkipTutorial) {
// skip_button.setVisibility(View.VISIBLE);
// }
// convertView.findViewById(R.id.skip_button).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (mStartActivity) {
// mActivity.startActivity(new Intent(mActivity, HomeActivity.class));
// }
// mActivity.finish();
// }
// });
// }
// container.addView(convertView, 0);
//
// return convertView;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean isViewFromObject(View view, Object object) {
// return view.equals(object);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void destroyItem(ViewGroup container, int position, Object object) {
// container.removeView((ViewGroup) object);
// }
//
// private enum ListColor {
// BLUE("#29A6D4"),
// GREEN("#1C7D6C"),
// ORANGE("#F77400"),
// RED("#F53B3C"),
// GRAYISH("#78909C"),
// PURPLE("#AB47BC"),
// YELLOW("#F9A01E");
//
// private
// @ColorRes
// final
// int color;
//
// ListColor(String colorCode) {
// this.color = Color.parseColor(colorCode);
// }
//
// public int getColor() {
// return color;
// }
// }
//
// }
//
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/constant/Constants.java
// public class
// Constants {
//
// public final static String BUILD_M_LEARN_PATH = "/BuildmLearn/";
// public final static String UNZIP = BUILD_M_LEARN_PATH + "unzipped/";
// public final static String APK_DIR = BUILD_M_LEARN_PATH + "apk/";
// public final static String SAVED_DIR = BUILD_M_LEARN_PATH + "saved/";
// public final static String DRAFT_DIR = BUILD_M_LEARN_PATH + "draft/";
// public final static String TEMPLATE_ID = "TEMPLATE_ID";
// public final static String TEMPLATE_OBJECT = "TEMPLATE_OBJECT";
// public final static String SIMULATOR_FILE_PATH = "SIMULATOR_FILE_PATH";
// public final static String PROJECT_FILE_PATH = "PROJECT_FILE_PATH";
// public final static String START_ACTIVITY = "START_ACTIVITY";
// public final static String START_FRAGMENT = "START_FRAGMENT";
//
//
// }
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/activity/TutorialActivity.java
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.util.TypedValue;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.adapter.TutorialAdapter;
import org.buildmlearn.toolkit.constant.Constants;
import org.buildmlearn.toolkit.model.Tutorial;
package org.buildmlearn.toolkit.activity;
/**
* @brief Shows the tutorial related to BuildmLearn toolkit usage.
*/
public class TutorialActivity extends AppCompatActivity {
private LinearLayout indicatingDotsContainer;
/**
* {@inheritDoc}
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutorial);
| TutorialAdapter mAdapter = new TutorialAdapter(this, getIntent().getBooleanExtra(Constants.START_ACTIVITY, false)); |
BuildmLearn/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/ToolkitApplication.java | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/constant/Constants.java
// public class
// Constants {
//
// public final static String BUILD_M_LEARN_PATH = "/BuildmLearn/";
// public final static String UNZIP = BUILD_M_LEARN_PATH + "unzipped/";
// public final static String APK_DIR = BUILD_M_LEARN_PATH + "apk/";
// public final static String SAVED_DIR = BUILD_M_LEARN_PATH + "saved/";
// public final static String DRAFT_DIR = BUILD_M_LEARN_PATH + "draft/";
// public final static String TEMPLATE_ID = "TEMPLATE_ID";
// public final static String TEMPLATE_OBJECT = "TEMPLATE_OBJECT";
// public final static String SIMULATOR_FILE_PATH = "SIMULATOR_FILE_PATH";
// public final static String PROJECT_FILE_PATH = "PROJECT_FILE_PATH";
// public final static String START_ACTIVITY = "START_ACTIVITY";
// public final static String START_FRAGMENT = "START_FRAGMENT";
//
//
// }
| import android.app.Application;
import android.os.Environment;
import org.buildmlearn.toolkit.constant.Constants;
import java.io.File;
import java.util.ArrayList; | package org.buildmlearn.toolkit;
/**
* @brief Extended Application class
* <p/>
* <p/>
* Created by Abhishek on 31-05-2015.
*/
public class ToolkitApplication extends Application {
private static String dir;
private static boolean isExternalStorageAvailable = false;
/**
* @return Folder path
* @brief Returns folder path for unzipped apks
*/
public static String getUnZipDir() { | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/constant/Constants.java
// public class
// Constants {
//
// public final static String BUILD_M_LEARN_PATH = "/BuildmLearn/";
// public final static String UNZIP = BUILD_M_LEARN_PATH + "unzipped/";
// public final static String APK_DIR = BUILD_M_LEARN_PATH + "apk/";
// public final static String SAVED_DIR = BUILD_M_LEARN_PATH + "saved/";
// public final static String DRAFT_DIR = BUILD_M_LEARN_PATH + "draft/";
// public final static String TEMPLATE_ID = "TEMPLATE_ID";
// public final static String TEMPLATE_OBJECT = "TEMPLATE_OBJECT";
// public final static String SIMULATOR_FILE_PATH = "SIMULATOR_FILE_PATH";
// public final static String PROJECT_FILE_PATH = "PROJECT_FILE_PATH";
// public final static String START_ACTIVITY = "START_ACTIVITY";
// public final static String START_FRAGMENT = "START_FRAGMENT";
//
//
// }
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/ToolkitApplication.java
import android.app.Application;
import android.os.Environment;
import org.buildmlearn.toolkit.constant.Constants;
import java.io.File;
import java.util.ArrayList;
package org.buildmlearn.toolkit;
/**
* @brief Extended Application class
* <p/>
* <p/>
* Created by Abhishek on 31-05-2015.
*/
public class ToolkitApplication extends Application {
private static String dir;
private static boolean isExternalStorageAvailable = false;
/**
* @return Folder path
* @brief Returns folder path for unzipped apks
*/
public static String getUnZipDir() { | return dir + Constants.UNZIP; |
BuildmLearn/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/activity/FirstRunActivity.java | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/constant/Constants.java
// public class
// Constants {
//
// public final static String BUILD_M_LEARN_PATH = "/BuildmLearn/";
// public final static String UNZIP = BUILD_M_LEARN_PATH + "unzipped/";
// public final static String APK_DIR = BUILD_M_LEARN_PATH + "apk/";
// public final static String SAVED_DIR = BUILD_M_LEARN_PATH + "saved/";
// public final static String DRAFT_DIR = BUILD_M_LEARN_PATH + "draft/";
// public final static String TEMPLATE_ID = "TEMPLATE_ID";
// public final static String TEMPLATE_OBJECT = "TEMPLATE_OBJECT";
// public final static String SIMULATOR_FILE_PATH = "SIMULATOR_FILE_PATH";
// public final static String PROJECT_FILE_PATH = "PROJECT_FILE_PATH";
// public final static String START_ACTIVITY = "START_ACTIVITY";
// public final static String START_FRAGMENT = "START_FRAGMENT";
//
//
// }
| import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import com.crashlytics.android.Crashlytics;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.constant.Constants;
import io.fabric.sdk.android.Fabric; |
findViewById(R.id.focus_thief).clearFocus();
Animation anim_bounceinup=AnimationUtils.loadAnimation(getBaseContext(),R.anim.bounceinup);
name = (EditText) findViewById(R.id.first_name);
name.startAnimation(anim_bounceinup);
name.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
if (name.getText().toString().equals("")) {
name.setError(getApplicationContext().getResources().getString(R.string.enter_name));
return false;
}
else if(!Character.isLetterOrDigit(name.getText().toString().charAt(0)))
{
name.setError(getApplicationContext().getResources().getString(R.string.valid_msg));
return false;
}
SharedPreferences.Editor editor = prefs.edit();
editor.putString(getString(R.string.key_user_name), name.getText().toString());
editor.putBoolean(FIRST_RUN, true);
editor.apply();
Intent intent = new Intent(getApplicationContext(), TutorialActivity.class); | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/constant/Constants.java
// public class
// Constants {
//
// public final static String BUILD_M_LEARN_PATH = "/BuildmLearn/";
// public final static String UNZIP = BUILD_M_LEARN_PATH + "unzipped/";
// public final static String APK_DIR = BUILD_M_LEARN_PATH + "apk/";
// public final static String SAVED_DIR = BUILD_M_LEARN_PATH + "saved/";
// public final static String DRAFT_DIR = BUILD_M_LEARN_PATH + "draft/";
// public final static String TEMPLATE_ID = "TEMPLATE_ID";
// public final static String TEMPLATE_OBJECT = "TEMPLATE_OBJECT";
// public final static String SIMULATOR_FILE_PATH = "SIMULATOR_FILE_PATH";
// public final static String PROJECT_FILE_PATH = "PROJECT_FILE_PATH";
// public final static String START_ACTIVITY = "START_ACTIVITY";
// public final static String START_FRAGMENT = "START_FRAGMENT";
//
//
// }
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/activity/FirstRunActivity.java
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import com.crashlytics.android.Crashlytics;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.constant.Constants;
import io.fabric.sdk.android.Fabric;
findViewById(R.id.focus_thief).clearFocus();
Animation anim_bounceinup=AnimationUtils.loadAnimation(getBaseContext(),R.anim.bounceinup);
name = (EditText) findViewById(R.id.first_name);
name.startAnimation(anim_bounceinup);
name.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
if (name.getText().toString().equals("")) {
name.setError(getApplicationContext().getResources().getString(R.string.enter_name));
return false;
}
else if(!Character.isLetterOrDigit(name.getText().toString().charAt(0)))
{
name.setError(getApplicationContext().getResources().getString(R.string.valid_msg));
return false;
}
SharedPreferences.Editor editor = prefs.edit();
editor.putString(getString(R.string.key_user_name), name.getText().toString());
editor.putBoolean(FIRST_RUN, true);
editor.apply();
Intent intent = new Intent(getApplicationContext(), TutorialActivity.class); | intent.putExtra(Constants.START_ACTIVITY, true); |
BuildmLearn/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/fragment/MainActivityFragment.java | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/Constants.java
// public class Constants {
// public static final String[] VIDEO_COLUMNS = {
// VideoContract.Videos.TABLE_NAME + "." + VideoContract.Videos._ID,
// VideoContract.Videos.TITLE,
// VideoContract.Videos.DESCRIPTION,
// VideoContract.Videos.LINK,
// VideoContract.Videos.THUMBNAIL_URL
// };
// public static final int COL_TITLE = 1;
// public static final int COL_DESCRIPTION = 2;
// public static final int COL_LINK = 3;
// public static final int COL_THUMBNAIL_URL = 4;
// public static String XMLFileName = "video_content.xml";
// }
//
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/DataUtils.java
// public class DataUtils {
//
// public static String[] readTitleAuthor() {
// String result[] = new String[2];
// DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//
// dbf.setValidating(false);
//
// DocumentBuilder db;
// Document doc;
// try {
// File fXmlFile = new File(Constants.XMLFileName);
// db = dbf.newDocumentBuilder();
// doc = db.parse(fXmlFile);
// doc.normalize();
//
// result[0] = doc.getElementsByTagName("title").item(0).getChildNodes()
// .item(0).getNodeValue();
//
// result[1] = doc.getElementsByTagName("name").item(0).getChildNodes()
// .item(0).getNodeValue();
//
// } catch (ParserConfigurationException | SAXException | IOException e) {
// e.printStackTrace();
// }
// return result;
// }
// }
//
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/VideoContract.java
// public class VideoContract {
//
// public static final class Videos implements BaseColumns {
//
// public static final String TABLE_NAME = "videos";
//
// public static final String TITLE = "title";
// public static final String DESCRIPTION = "description";
// public static final String LINK = "link";
// public static final String THUMBNAIL_URL = "thumbnail_url";
//
// }
// }
//
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/VideoModel.java
// public class VideoModel implements Parcelable {
// public final static Parcelable.Creator<VideoModel> CREATOR = new Parcelable.Creator<VideoModel>() {
// @Override
// public VideoModel createFromParcel(Parcel parcel) {
// return new VideoModel(parcel);
// }
//
// @Override
// public VideoModel[] newArray(int size) {
// return new VideoModel[size];
// }
// };
//
// private String title;
// private String description;
// private String link;
// private String thumbnail_url;
//
// public VideoModel() {
// }
//
// private VideoModel(Parcel in) {
// this.title = in.readString();
// this.description = in.readString();
// this.link = in.readString();
// this.thumbnail_url = in.readString();
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(title);
// dest.writeString(description);
// dest.writeString(link);
// dest.writeString(thumbnail_url);
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getThumbnailUrl() {
// return thumbnail_url;
// }
//
// public void setThumbnailUrl(String thumbnail_url) {
// this.thumbnail_url = thumbnail_url;
// }
//
// public String getLink() {
// return link;
// }
//
// public void setLink(String link) {
// this.link = link;
// }
//
// }
| import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.videocollectiontemplate.Constants;
import org.buildmlearn.toolkit.videocollectiontemplate.adapter.VideoArrayAdapter;
import org.buildmlearn.toolkit.videocollectiontemplate.data.DataUtils;
import org.buildmlearn.toolkit.videocollectiontemplate.data.VideoContract;
import org.buildmlearn.toolkit.videocollectiontemplate.data.VideoDb;
import org.buildmlearn.toolkit.videocollectiontemplate.data.VideoModel;
import java.util.ArrayList; | package org.buildmlearn.toolkit.videocollectiontemplate.fragment;
/**
* @brief Fragment containing list of videos in video collection template's simulator.
* <p/>
* Created by Anupam (opticod) on 20/5/16.
*/
public class MainActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String SELECTED_KEY = "selected_position";
private static final int VIDEO_LOADER = 0;
private VideoArrayAdapter videoListAdapter;
private int mPosition = ListView.INVALID_POSITION;
private ListView listView; | // Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/Constants.java
// public class Constants {
// public static final String[] VIDEO_COLUMNS = {
// VideoContract.Videos.TABLE_NAME + "." + VideoContract.Videos._ID,
// VideoContract.Videos.TITLE,
// VideoContract.Videos.DESCRIPTION,
// VideoContract.Videos.LINK,
// VideoContract.Videos.THUMBNAIL_URL
// };
// public static final int COL_TITLE = 1;
// public static final int COL_DESCRIPTION = 2;
// public static final int COL_LINK = 3;
// public static final int COL_THUMBNAIL_URL = 4;
// public static String XMLFileName = "video_content.xml";
// }
//
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/DataUtils.java
// public class DataUtils {
//
// public static String[] readTitleAuthor() {
// String result[] = new String[2];
// DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//
// dbf.setValidating(false);
//
// DocumentBuilder db;
// Document doc;
// try {
// File fXmlFile = new File(Constants.XMLFileName);
// db = dbf.newDocumentBuilder();
// doc = db.parse(fXmlFile);
// doc.normalize();
//
// result[0] = doc.getElementsByTagName("title").item(0).getChildNodes()
// .item(0).getNodeValue();
//
// result[1] = doc.getElementsByTagName("name").item(0).getChildNodes()
// .item(0).getNodeValue();
//
// } catch (ParserConfigurationException | SAXException | IOException e) {
// e.printStackTrace();
// }
// return result;
// }
// }
//
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/VideoContract.java
// public class VideoContract {
//
// public static final class Videos implements BaseColumns {
//
// public static final String TABLE_NAME = "videos";
//
// public static final String TITLE = "title";
// public static final String DESCRIPTION = "description";
// public static final String LINK = "link";
// public static final String THUMBNAIL_URL = "thumbnail_url";
//
// }
// }
//
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/data/VideoModel.java
// public class VideoModel implements Parcelable {
// public final static Parcelable.Creator<VideoModel> CREATOR = new Parcelable.Creator<VideoModel>() {
// @Override
// public VideoModel createFromParcel(Parcel parcel) {
// return new VideoModel(parcel);
// }
//
// @Override
// public VideoModel[] newArray(int size) {
// return new VideoModel[size];
// }
// };
//
// private String title;
// private String description;
// private String link;
// private String thumbnail_url;
//
// public VideoModel() {
// }
//
// private VideoModel(Parcel in) {
// this.title = in.readString();
// this.description = in.readString();
// this.link = in.readString();
// this.thumbnail_url = in.readString();
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(title);
// dest.writeString(description);
// dest.writeString(link);
// dest.writeString(thumbnail_url);
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getThumbnailUrl() {
// return thumbnail_url;
// }
//
// public void setThumbnailUrl(String thumbnail_url) {
// this.thumbnail_url = thumbnail_url;
// }
//
// public String getLink() {
// return link;
// }
//
// public void setLink(String link) {
// this.link = link;
// }
//
// }
// Path: source-code/app/src/main/java/org/buildmlearn/toolkit/videocollectiontemplate/fragment/MainActivityFragment.java
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.buildmlearn.toolkit.R;
import org.buildmlearn.toolkit.videocollectiontemplate.Constants;
import org.buildmlearn.toolkit.videocollectiontemplate.adapter.VideoArrayAdapter;
import org.buildmlearn.toolkit.videocollectiontemplate.data.DataUtils;
import org.buildmlearn.toolkit.videocollectiontemplate.data.VideoContract;
import org.buildmlearn.toolkit.videocollectiontemplate.data.VideoDb;
import org.buildmlearn.toolkit.videocollectiontemplate.data.VideoModel;
import java.util.ArrayList;
package org.buildmlearn.toolkit.videocollectiontemplate.fragment;
/**
* @brief Fragment containing list of videos in video collection template's simulator.
* <p/>
* Created by Anupam (opticod) on 20/5/16.
*/
public class MainActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String SELECTED_KEY = "selected_position";
private static final int VIDEO_LOADER = 0;
private VideoArrayAdapter videoListAdapter;
private int mPosition = ListView.INVALID_POSITION;
private ListView listView; | private ArrayList<VideoModel> videoList; |
vonZeppelin/planning-poker | src/main/java/org/lbogdanov/poker/core/User.java | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EMAIL_MAX_LENGTH = 254;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EXTERNAL_ID_MAX_LENGTH = 64;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_FIRST_NAME_MAX_LENGTH = 128;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_LAST_NAME_MAX_LENGTH = 128;
| import static org.lbogdanov.poker.core.Constants.USER_EMAIL_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_EXTERNAL_ID_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_FIRST_NAME_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_LAST_NAME_MAX_LENGTH;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.google.common.base.Objects; | /**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a User.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "USERS")
public class User extends AbstractEntity {
| // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EMAIL_MAX_LENGTH = 254;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EXTERNAL_ID_MAX_LENGTH = 64;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_FIRST_NAME_MAX_LENGTH = 128;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_LAST_NAME_MAX_LENGTH = 128;
// Path: src/main/java/org/lbogdanov/poker/core/User.java
import static org.lbogdanov.poker.core.Constants.USER_EMAIL_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_EXTERNAL_ID_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_FIRST_NAME_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_LAST_NAME_MAX_LENGTH;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.google.common.base.Objects;
/**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a User.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "USERS")
public class User extends AbstractEntity {
| @Column(name = "FIRST_NAME", length = USER_FIRST_NAME_MAX_LENGTH, nullable = false) |
vonZeppelin/planning-poker | src/main/java/org/lbogdanov/poker/core/User.java | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EMAIL_MAX_LENGTH = 254;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EXTERNAL_ID_MAX_LENGTH = 64;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_FIRST_NAME_MAX_LENGTH = 128;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_LAST_NAME_MAX_LENGTH = 128;
| import static org.lbogdanov.poker.core.Constants.USER_EMAIL_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_EXTERNAL_ID_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_FIRST_NAME_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_LAST_NAME_MAX_LENGTH;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.google.common.base.Objects; | /**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a User.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "USERS")
public class User extends AbstractEntity {
@Column(name = "FIRST_NAME", length = USER_FIRST_NAME_MAX_LENGTH, nullable = false)
private String firstName = ""; | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EMAIL_MAX_LENGTH = 254;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EXTERNAL_ID_MAX_LENGTH = 64;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_FIRST_NAME_MAX_LENGTH = 128;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_LAST_NAME_MAX_LENGTH = 128;
// Path: src/main/java/org/lbogdanov/poker/core/User.java
import static org.lbogdanov.poker.core.Constants.USER_EMAIL_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_EXTERNAL_ID_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_FIRST_NAME_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_LAST_NAME_MAX_LENGTH;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.google.common.base.Objects;
/**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a User.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "USERS")
public class User extends AbstractEntity {
@Column(name = "FIRST_NAME", length = USER_FIRST_NAME_MAX_LENGTH, nullable = false)
private String firstName = ""; | @Column(name = "LAST_NAME", length = USER_LAST_NAME_MAX_LENGTH, nullable = true) |
vonZeppelin/planning-poker | src/main/java/org/lbogdanov/poker/core/User.java | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EMAIL_MAX_LENGTH = 254;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EXTERNAL_ID_MAX_LENGTH = 64;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_FIRST_NAME_MAX_LENGTH = 128;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_LAST_NAME_MAX_LENGTH = 128;
| import static org.lbogdanov.poker.core.Constants.USER_EMAIL_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_EXTERNAL_ID_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_FIRST_NAME_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_LAST_NAME_MAX_LENGTH;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.google.common.base.Objects; | /**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a User.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "USERS")
public class User extends AbstractEntity {
@Column(name = "FIRST_NAME", length = USER_FIRST_NAME_MAX_LENGTH, nullable = false)
private String firstName = "";
@Column(name = "LAST_NAME", length = USER_LAST_NAME_MAX_LENGTH, nullable = true)
private String lastName = ""; | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EMAIL_MAX_LENGTH = 254;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EXTERNAL_ID_MAX_LENGTH = 64;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_FIRST_NAME_MAX_LENGTH = 128;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_LAST_NAME_MAX_LENGTH = 128;
// Path: src/main/java/org/lbogdanov/poker/core/User.java
import static org.lbogdanov.poker.core.Constants.USER_EMAIL_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_EXTERNAL_ID_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_FIRST_NAME_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_LAST_NAME_MAX_LENGTH;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.google.common.base.Objects;
/**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a User.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "USERS")
public class User extends AbstractEntity {
@Column(name = "FIRST_NAME", length = USER_FIRST_NAME_MAX_LENGTH, nullable = false)
private String firstName = "";
@Column(name = "LAST_NAME", length = USER_LAST_NAME_MAX_LENGTH, nullable = true)
private String lastName = ""; | @Column(name = "EMAIL", length = USER_EMAIL_MAX_LENGTH, nullable = true) |
vonZeppelin/planning-poker | src/main/java/org/lbogdanov/poker/core/User.java | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EMAIL_MAX_LENGTH = 254;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EXTERNAL_ID_MAX_LENGTH = 64;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_FIRST_NAME_MAX_LENGTH = 128;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_LAST_NAME_MAX_LENGTH = 128;
| import static org.lbogdanov.poker.core.Constants.USER_EMAIL_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_EXTERNAL_ID_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_FIRST_NAME_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_LAST_NAME_MAX_LENGTH;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.google.common.base.Objects; | /**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a User.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "USERS")
public class User extends AbstractEntity {
@Column(name = "FIRST_NAME", length = USER_FIRST_NAME_MAX_LENGTH, nullable = false)
private String firstName = "";
@Column(name = "LAST_NAME", length = USER_LAST_NAME_MAX_LENGTH, nullable = true)
private String lastName = "";
@Column(name = "EMAIL", length = USER_EMAIL_MAX_LENGTH, nullable = true)
private String email = ""; | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EMAIL_MAX_LENGTH = 254;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_EXTERNAL_ID_MAX_LENGTH = 64;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_FIRST_NAME_MAX_LENGTH = 128;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int USER_LAST_NAME_MAX_LENGTH = 128;
// Path: src/main/java/org/lbogdanov/poker/core/User.java
import static org.lbogdanov.poker.core.Constants.USER_EMAIL_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_EXTERNAL_ID_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_FIRST_NAME_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.USER_LAST_NAME_MAX_LENGTH;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.google.common.base.Objects;
/**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a User.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "USERS")
public class User extends AbstractEntity {
@Column(name = "FIRST_NAME", length = USER_FIRST_NAME_MAX_LENGTH, nullable = false)
private String firstName = "";
@Column(name = "LAST_NAME", length = USER_LAST_NAME_MAX_LENGTH, nullable = true)
private String lastName = "";
@Column(name = "EMAIL", length = USER_EMAIL_MAX_LENGTH, nullable = true)
private String email = ""; | @Column(name = "EXTERNAL_ID", length = USER_EXTERNAL_ID_MAX_LENGTH, nullable = false, unique = true) |
vonZeppelin/planning-poker | src/main/java/org/lbogdanov/poker/core/Session.java | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_CODE_MAX_LENGTH = 32;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_DESCRIPTION_MAX_LENGTH = 4096;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_ESTIMATES_MAX_LENGTH = 1024;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_NAME_MAX_LENGTH = 128;
| import static org.lbogdanov.poker.core.Constants.SESSION_CODE_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_DESCRIPTION_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_ESTIMATES_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_NAME_MAX_LENGTH;
import java.util.Date;
import javax.persistence.*;
import com.google.common.base.Objects; | /**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a Planning Poker session.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "SESSIONS")
public class Session extends AbstractEntity {
| // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_CODE_MAX_LENGTH = 32;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_DESCRIPTION_MAX_LENGTH = 4096;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_ESTIMATES_MAX_LENGTH = 1024;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_NAME_MAX_LENGTH = 128;
// Path: src/main/java/org/lbogdanov/poker/core/Session.java
import static org.lbogdanov.poker.core.Constants.SESSION_CODE_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_DESCRIPTION_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_ESTIMATES_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_NAME_MAX_LENGTH;
import java.util.Date;
import javax.persistence.*;
import com.google.common.base.Objects;
/**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a Planning Poker session.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "SESSIONS")
public class Session extends AbstractEntity {
| @Column(name = "NAME", length = SESSION_NAME_MAX_LENGTH, nullable = false) |
vonZeppelin/planning-poker | src/main/java/org/lbogdanov/poker/core/Session.java | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_CODE_MAX_LENGTH = 32;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_DESCRIPTION_MAX_LENGTH = 4096;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_ESTIMATES_MAX_LENGTH = 1024;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_NAME_MAX_LENGTH = 128;
| import static org.lbogdanov.poker.core.Constants.SESSION_CODE_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_DESCRIPTION_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_ESTIMATES_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_NAME_MAX_LENGTH;
import java.util.Date;
import javax.persistence.*;
import com.google.common.base.Objects; | /**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a Planning Poker session.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "SESSIONS")
public class Session extends AbstractEntity {
@Column(name = "NAME", length = SESSION_NAME_MAX_LENGTH, nullable = false)
private String name = ""; | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_CODE_MAX_LENGTH = 32;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_DESCRIPTION_MAX_LENGTH = 4096;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_ESTIMATES_MAX_LENGTH = 1024;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_NAME_MAX_LENGTH = 128;
// Path: src/main/java/org/lbogdanov/poker/core/Session.java
import static org.lbogdanov.poker.core.Constants.SESSION_CODE_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_DESCRIPTION_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_ESTIMATES_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_NAME_MAX_LENGTH;
import java.util.Date;
import javax.persistence.*;
import com.google.common.base.Objects;
/**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a Planning Poker session.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "SESSIONS")
public class Session extends AbstractEntity {
@Column(name = "NAME", length = SESSION_NAME_MAX_LENGTH, nullable = false)
private String name = ""; | @Column(name = "CODE", length = SESSION_CODE_MAX_LENGTH, nullable = false, unique = true) |
vonZeppelin/planning-poker | src/main/java/org/lbogdanov/poker/core/Session.java | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_CODE_MAX_LENGTH = 32;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_DESCRIPTION_MAX_LENGTH = 4096;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_ESTIMATES_MAX_LENGTH = 1024;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_NAME_MAX_LENGTH = 128;
| import static org.lbogdanov.poker.core.Constants.SESSION_CODE_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_DESCRIPTION_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_ESTIMATES_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_NAME_MAX_LENGTH;
import java.util.Date;
import javax.persistence.*;
import com.google.common.base.Objects; | /**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a Planning Poker session.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "SESSIONS")
public class Session extends AbstractEntity {
@Column(name = "NAME", length = SESSION_NAME_MAX_LENGTH, nullable = false)
private String name = "";
@Column(name = "CODE", length = SESSION_CODE_MAX_LENGTH, nullable = false, unique = true)
private String code = "";
@Column(name = "CREATED", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date created = new Date(); | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_CODE_MAX_LENGTH = 32;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_DESCRIPTION_MAX_LENGTH = 4096;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_ESTIMATES_MAX_LENGTH = 1024;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_NAME_MAX_LENGTH = 128;
// Path: src/main/java/org/lbogdanov/poker/core/Session.java
import static org.lbogdanov.poker.core.Constants.SESSION_CODE_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_DESCRIPTION_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_ESTIMATES_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_NAME_MAX_LENGTH;
import java.util.Date;
import javax.persistence.*;
import com.google.common.base.Objects;
/**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a Planning Poker session.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "SESSIONS")
public class Session extends AbstractEntity {
@Column(name = "NAME", length = SESSION_NAME_MAX_LENGTH, nullable = false)
private String name = "";
@Column(name = "CODE", length = SESSION_CODE_MAX_LENGTH, nullable = false, unique = true)
private String code = "";
@Column(name = "CREATED", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date created = new Date(); | @Column(name = "DESCRIPTION", length = SESSION_DESCRIPTION_MAX_LENGTH, nullable = true) |
vonZeppelin/planning-poker | src/main/java/org/lbogdanov/poker/core/Session.java | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_CODE_MAX_LENGTH = 32;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_DESCRIPTION_MAX_LENGTH = 4096;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_ESTIMATES_MAX_LENGTH = 1024;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_NAME_MAX_LENGTH = 128;
| import static org.lbogdanov.poker.core.Constants.SESSION_CODE_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_DESCRIPTION_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_ESTIMATES_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_NAME_MAX_LENGTH;
import java.util.Date;
import javax.persistence.*;
import com.google.common.base.Objects; | /**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a Planning Poker session.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "SESSIONS")
public class Session extends AbstractEntity {
@Column(name = "NAME", length = SESSION_NAME_MAX_LENGTH, nullable = false)
private String name = "";
@Column(name = "CODE", length = SESSION_CODE_MAX_LENGTH, nullable = false, unique = true)
private String code = "";
@Column(name = "CREATED", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date created = new Date();
@Column(name = "DESCRIPTION", length = SESSION_DESCRIPTION_MAX_LENGTH, nullable = true)
private String description = "";
@ManyToOne(optional = false)
@JoinColumn(name = "AUTHOR_ID", nullable = false)
private User author; | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_CODE_MAX_LENGTH = 32;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_DESCRIPTION_MAX_LENGTH = 4096;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_ESTIMATES_MAX_LENGTH = 1024;
//
// Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_NAME_MAX_LENGTH = 128;
// Path: src/main/java/org/lbogdanov/poker/core/Session.java
import static org.lbogdanov.poker.core.Constants.SESSION_CODE_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_DESCRIPTION_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_ESTIMATES_MAX_LENGTH;
import static org.lbogdanov.poker.core.Constants.SESSION_NAME_MAX_LENGTH;
import java.util.Date;
import javax.persistence.*;
import com.google.common.base.Objects;
/**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.core;
/**
* Represents a Planning Poker session.
*
* @author Leonid Bogdanov
*/
@Entity
@Table(name = "SESSIONS")
public class Session extends AbstractEntity {
@Column(name = "NAME", length = SESSION_NAME_MAX_LENGTH, nullable = false)
private String name = "";
@Column(name = "CODE", length = SESSION_CODE_MAX_LENGTH, nullable = false, unique = true)
private String code = "";
@Column(name = "CREATED", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date created = new Date();
@Column(name = "DESCRIPTION", length = SESSION_DESCRIPTION_MAX_LENGTH, nullable = true)
private String description = "";
@ManyToOne(optional = false)
@JoinColumn(name = "AUTHOR_ID", nullable = false)
private User author; | @Column(name = "ESTIMATES", length = SESSION_ESTIMATES_MAX_LENGTH, nullable = false) |
vonZeppelin/planning-poker | src/main/java/org/lbogdanov/poker/core/impl/SessionServiceImpl.java | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_CODE_DEFAULT_LENGTH = 10;
| import com.google.common.base.Strings;
import static org.lbogdanov.poker.core.Constants.SESSION_CODE_DEFAULT_LENGTH;
import static org.lbogdanov.poker.util.Settings.SESSION_CODE_LENGTH;
import java.security.SecureRandom;
import java.util.Random;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.lbogdanov.poker.core.*;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.Query;
import com.avaje.ebean.annotation.Transactional; | .where().eq("code", code)
.findUnique();
}
/**
* {@inheritDoc}
*/
@Override
@Transactional(readOnly = true)
public PagingList<Session> find(User user, String name, String orderBy, boolean ascending, int pageSize) {
// TODO union with sessions where the user has participated
Query<Session> query = ebean.find(Session.class);
ExpressionList<Session> expr = query.where().eq("author", user);
if (!Strings.isNullOrEmpty(name)) {
expr = expr.ilike("name", name);
}
query = ascending ? expr.orderBy().asc(orderBy) : expr.orderBy().desc(orderBy);
return new EbeanPagingList<Session>(query.findPagingList(pageSize));
}
/**
* {@inheritDoc}
*/
@Override
@Transactional
public Session create(String name, String description, String estimations) {
Session session = new Session();
session.setName(name);
session.setDescription(description);
session.setEstimates(estimations); | // Path: src/main/java/org/lbogdanov/poker/core/Constants.java
// public static final int SESSION_CODE_DEFAULT_LENGTH = 10;
// Path: src/main/java/org/lbogdanov/poker/core/impl/SessionServiceImpl.java
import com.google.common.base.Strings;
import static org.lbogdanov.poker.core.Constants.SESSION_CODE_DEFAULT_LENGTH;
import static org.lbogdanov.poker.util.Settings.SESSION_CODE_LENGTH;
import java.security.SecureRandom;
import java.util.Random;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.lbogdanov.poker.core.*;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.Query;
import com.avaje.ebean.annotation.Transactional;
.where().eq("code", code)
.findUnique();
}
/**
* {@inheritDoc}
*/
@Override
@Transactional(readOnly = true)
public PagingList<Session> find(User user, String name, String orderBy, boolean ascending, int pageSize) {
// TODO union with sessions where the user has participated
Query<Session> query = ebean.find(Session.class);
ExpressionList<Session> expr = query.where().eq("author", user);
if (!Strings.isNullOrEmpty(name)) {
expr = expr.ilike("name", name);
}
query = ascending ? expr.orderBy().asc(orderBy) : expr.orderBy().desc(orderBy);
return new EbeanPagingList<Session>(query.findPagingList(pageSize));
}
/**
* {@inheritDoc}
*/
@Override
@Transactional
public Session create(String name, String description, String estimations) {
Session session = new Session();
session.setName(name);
session.setDescription(description);
session.setEstimates(estimations); | session.setCode(newCode(SESSION_CODE_LENGTH.asInt().or(SESSION_CODE_DEFAULT_LENGTH))); |
vonZeppelin/planning-poker | src/main/java/org/lbogdanov/poker/web/util/ChatMessage.java | // Path: src/main/java/org/lbogdanov/poker/core/User.java
// @Entity
// @Table(name = "USERS")
// public class User extends AbstractEntity {
//
// @Column(name = "FIRST_NAME", length = USER_FIRST_NAME_MAX_LENGTH, nullable = false)
// private String firstName = "";
// @Column(name = "LAST_NAME", length = USER_LAST_NAME_MAX_LENGTH, nullable = true)
// private String lastName = "";
// @Column(name = "EMAIL", length = USER_EMAIL_MAX_LENGTH, nullable = true)
// private String email = "";
// @Column(name = "EXTERNAL_ID", length = USER_EXTERNAL_ID_MAX_LENGTH, nullable = false, unique = true)
// private String externalId = "";
//
// /**
// * Returns a user's first name.
// *
// * @return the firstName
// */
// public String getFirstName() {
// return firstName;
// }
//
// /**
// * Sets a user's first name, only the first {@link Constants.USER_FIRST_NAME_MAX_LENGTH} characters are stored.
// *
// * @param firstName the first name to set
// */
// public void setFirstName(String firstName) {
// this.firstName = limitString(firstName, USER_FIRST_NAME_MAX_LENGTH);
// }
//
// /**
// * Returns a user's last name.
// *
// * @return the last name
// */
// public String getLastName() {
// return lastName;
// }
//
// /**
// * Sets a user's last name, only the first {@link Constants.USER_LAST_NAME_MAX_LENGTH} characters are stored.
// *
// * @param lastName the last name to set
// */
// public void setLastName(String lastName) {
// this.lastName = limitString(lastName, USER_LAST_NAME_MAX_LENGTH);
// }
//
// /**
// * Returns a user's e-mail.
// *
// * @return the e-mail
// */
// public String getEmail() {
// return email;
// }
//
// /**
// * Sets a user's e-mail, only the first {@link Constants.USER_EMAIL_MAX_LENGTH} characters are stored.
// *
// * @param email the e-mail to set
// */
// public void setEmail(String email) {
// this.email = limitString(email, USER_EMAIL_MAX_LENGTH);
// }
//
// /**
// * Returns a user's ID in an external system from which the user originates.
// *
// * @return the external ID
// */
// public String getExternalId() {
// return externalId;
// }
//
// /**
// * Sets a user's ID in an external system, only the first {@link Constants.USER_EXTERNAL_ID_MAX_LENGTH} characters are stored.
// *
// * @param externalId the external ID
// */
// public void setExternalId(String externalId) {
// this.externalId = limitString(externalId, USER_EXTERNAL_ID_MAX_LENGTH);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public int hashCode() {
// return Objects.hashCode(getExternalId());
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj instanceof User) {
// User other = (User) obj;
// return Objects.equal(this.getExternalId(), other.getExternalId());
// }
// return false;
// }
//
// }
| import org.lbogdanov.poker.core.User;
import com.fasterxml.jackson.annotation.JsonTypeName; | /**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.web.util;
/**
* Represents a chat message.
*
* @author Leonid Bogdanov
*/
@JsonTypeName("chatMsg")
public final class ChatMessage extends Message<String> {
| // Path: src/main/java/org/lbogdanov/poker/core/User.java
// @Entity
// @Table(name = "USERS")
// public class User extends AbstractEntity {
//
// @Column(name = "FIRST_NAME", length = USER_FIRST_NAME_MAX_LENGTH, nullable = false)
// private String firstName = "";
// @Column(name = "LAST_NAME", length = USER_LAST_NAME_MAX_LENGTH, nullable = true)
// private String lastName = "";
// @Column(name = "EMAIL", length = USER_EMAIL_MAX_LENGTH, nullable = true)
// private String email = "";
// @Column(name = "EXTERNAL_ID", length = USER_EXTERNAL_ID_MAX_LENGTH, nullable = false, unique = true)
// private String externalId = "";
//
// /**
// * Returns a user's first name.
// *
// * @return the firstName
// */
// public String getFirstName() {
// return firstName;
// }
//
// /**
// * Sets a user's first name, only the first {@link Constants.USER_FIRST_NAME_MAX_LENGTH} characters are stored.
// *
// * @param firstName the first name to set
// */
// public void setFirstName(String firstName) {
// this.firstName = limitString(firstName, USER_FIRST_NAME_MAX_LENGTH);
// }
//
// /**
// * Returns a user's last name.
// *
// * @return the last name
// */
// public String getLastName() {
// return lastName;
// }
//
// /**
// * Sets a user's last name, only the first {@link Constants.USER_LAST_NAME_MAX_LENGTH} characters are stored.
// *
// * @param lastName the last name to set
// */
// public void setLastName(String lastName) {
// this.lastName = limitString(lastName, USER_LAST_NAME_MAX_LENGTH);
// }
//
// /**
// * Returns a user's e-mail.
// *
// * @return the e-mail
// */
// public String getEmail() {
// return email;
// }
//
// /**
// * Sets a user's e-mail, only the first {@link Constants.USER_EMAIL_MAX_LENGTH} characters are stored.
// *
// * @param email the e-mail to set
// */
// public void setEmail(String email) {
// this.email = limitString(email, USER_EMAIL_MAX_LENGTH);
// }
//
// /**
// * Returns a user's ID in an external system from which the user originates.
// *
// * @return the external ID
// */
// public String getExternalId() {
// return externalId;
// }
//
// /**
// * Sets a user's ID in an external system, only the first {@link Constants.USER_EXTERNAL_ID_MAX_LENGTH} characters are stored.
// *
// * @param externalId the external ID
// */
// public void setExternalId(String externalId) {
// this.externalId = limitString(externalId, USER_EXTERNAL_ID_MAX_LENGTH);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public int hashCode() {
// return Objects.hashCode(getExternalId());
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj instanceof User) {
// User other = (User) obj;
// return Objects.equal(this.getExternalId(), other.getExternalId());
// }
// return false;
// }
//
// }
// Path: src/main/java/org/lbogdanov/poker/web/util/ChatMessage.java
import org.lbogdanov.poker.core.User;
import com.fasterxml.jackson.annotation.JsonTypeName;
/**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.web.util;
/**
* Represents a chat message.
*
* @author Leonid Bogdanov
*/
@JsonTypeName("chatMsg")
public final class ChatMessage extends Message<String> {
| public final User author; |
vonZeppelin/planning-poker | src/test/java/org/lbogdanov/poker/core/SessionServiceTest.java | // Path: src/main/java/org/lbogdanov/poker/core/impl/SessionServiceImpl.java
// @Singleton
// public class SessionServiceImpl implements SessionService {
//
// @Inject
// private EbeanServer ebean;
// @Inject
// private UserService userService;
//
// /**
// * {@inheritDoc}
// */
// @Override
// @Transactional(readOnly = true)
// public boolean exists(String code) {
// return ebean.find(Session.class)
// .where().eq("code", code)
// .findRowCount() != 0;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// @Transactional(readOnly = true)
// public Session find(Object id) {
// return ebean.find(Session.class, id);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// @Transactional(readOnly = true)
// public Session find(String code) {
// return ebean.find(Session.class)
// .where().eq("code", code)
// .findUnique();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// @Transactional(readOnly = true)
// public PagingList<Session> find(User user, String name, String orderBy, boolean ascending, int pageSize) {
// // TODO union with sessions where the user has participated
// Query<Session> query = ebean.find(Session.class);
// ExpressionList<Session> expr = query.where().eq("author", user);
// if (!Strings.isNullOrEmpty(name)) {
// expr = expr.ilike("name", name);
// }
// query = ascending ? expr.orderBy().asc(orderBy) : expr.orderBy().desc(orderBy);
// return new EbeanPagingList<Session>(query.findPagingList(pageSize));
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// @Transactional
// public Session create(String name, String description, String estimations) {
// Session session = new Session();
// session.setName(name);
// session.setDescription(description);
// session.setEstimates(estimations);
// session.setCode(newCode(SESSION_CODE_LENGTH.asInt().or(SESSION_CODE_DEFAULT_LENGTH)));
// session.setAuthor(userService.getCurrentUser());
// ebean.save(session);
// return session;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// @Transactional
// public void delete(Session session) {
// ebean.delete(session);
// }
//
// /**
// * Generates a new alphanumeric code of a specified length which can be used to uniquely identify a session.
// *
// * @param length the desired code length
// * @return the new code
// */
// private String newCode(int length) {
// Random rnd = new SecureRandom();
// StringBuilder code = new StringBuilder(length);
// do {
// code.setLength(0);
// while (code.length() < length) {
// if (rnd.nextBoolean()) { // append a new letter or digit?
// char letter = (char) ('a' + rnd.nextInt(26));
// code.append(rnd.nextBoolean() ? Character.toUpperCase(letter) : letter);
// } else {
// code.append(rnd.nextInt(10));
// }
// }
// } while (exists(code.toString()));
// return code.toString();
// }
//
// }
| import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.Random;
import javax.inject.Inject;
import org.jukito.JukitoRunner;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.lbogdanov.poker.core.impl.SessionServiceImpl;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.Query;
import com.avaje.ebean.TxCallable; | package org.lbogdanov.poker.core;
/**
* Tests for <code>SessionService</code> implementation.
*/
@Ignore
@RunWith(JukitoRunner.class)
public class SessionServiceTest {
@Inject | // Path: src/main/java/org/lbogdanov/poker/core/impl/SessionServiceImpl.java
// @Singleton
// public class SessionServiceImpl implements SessionService {
//
// @Inject
// private EbeanServer ebean;
// @Inject
// private UserService userService;
//
// /**
// * {@inheritDoc}
// */
// @Override
// @Transactional(readOnly = true)
// public boolean exists(String code) {
// return ebean.find(Session.class)
// .where().eq("code", code)
// .findRowCount() != 0;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// @Transactional(readOnly = true)
// public Session find(Object id) {
// return ebean.find(Session.class, id);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// @Transactional(readOnly = true)
// public Session find(String code) {
// return ebean.find(Session.class)
// .where().eq("code", code)
// .findUnique();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// @Transactional(readOnly = true)
// public PagingList<Session> find(User user, String name, String orderBy, boolean ascending, int pageSize) {
// // TODO union with sessions where the user has participated
// Query<Session> query = ebean.find(Session.class);
// ExpressionList<Session> expr = query.where().eq("author", user);
// if (!Strings.isNullOrEmpty(name)) {
// expr = expr.ilike("name", name);
// }
// query = ascending ? expr.orderBy().asc(orderBy) : expr.orderBy().desc(orderBy);
// return new EbeanPagingList<Session>(query.findPagingList(pageSize));
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// @Transactional
// public Session create(String name, String description, String estimations) {
// Session session = new Session();
// session.setName(name);
// session.setDescription(description);
// session.setEstimates(estimations);
// session.setCode(newCode(SESSION_CODE_LENGTH.asInt().or(SESSION_CODE_DEFAULT_LENGTH)));
// session.setAuthor(userService.getCurrentUser());
// ebean.save(session);
// return session;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// @Transactional
// public void delete(Session session) {
// ebean.delete(session);
// }
//
// /**
// * Generates a new alphanumeric code of a specified length which can be used to uniquely identify a session.
// *
// * @param length the desired code length
// * @return the new code
// */
// private String newCode(int length) {
// Random rnd = new SecureRandom();
// StringBuilder code = new StringBuilder(length);
// do {
// code.setLength(0);
// while (code.length() < length) {
// if (rnd.nextBoolean()) { // append a new letter or digit?
// char letter = (char) ('a' + rnd.nextInt(26));
// code.append(rnd.nextBoolean() ? Character.toUpperCase(letter) : letter);
// } else {
// code.append(rnd.nextInt(10));
// }
// }
// } while (exists(code.toString()));
// return code.toString();
// }
//
// }
// Path: src/test/java/org/lbogdanov/poker/core/SessionServiceTest.java
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.Random;
import javax.inject.Inject;
import org.jukito.JukitoRunner;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.lbogdanov.poker.core.impl.SessionServiceImpl;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.Query;
import com.avaje.ebean.TxCallable;
package org.lbogdanov.poker.core;
/**
* Tests for <code>SessionService</code> implementation.
*/
@Ignore
@RunWith(JukitoRunner.class)
public class SessionServiceTest {
@Inject | private SessionServiceImpl sessionService; |
vonZeppelin/planning-poker | src/main/java/org/lbogdanov/poker/core/impl/UserServiceImpl.java | // Path: src/main/java/org/lbogdanov/poker/core/User.java
// @Entity
// @Table(name = "USERS")
// public class User extends AbstractEntity {
//
// @Column(name = "FIRST_NAME", length = USER_FIRST_NAME_MAX_LENGTH, nullable = false)
// private String firstName = "";
// @Column(name = "LAST_NAME", length = USER_LAST_NAME_MAX_LENGTH, nullable = true)
// private String lastName = "";
// @Column(name = "EMAIL", length = USER_EMAIL_MAX_LENGTH, nullable = true)
// private String email = "";
// @Column(name = "EXTERNAL_ID", length = USER_EXTERNAL_ID_MAX_LENGTH, nullable = false, unique = true)
// private String externalId = "";
//
// /**
// * Returns a user's first name.
// *
// * @return the firstName
// */
// public String getFirstName() {
// return firstName;
// }
//
// /**
// * Sets a user's first name, only the first {@link Constants.USER_FIRST_NAME_MAX_LENGTH} characters are stored.
// *
// * @param firstName the first name to set
// */
// public void setFirstName(String firstName) {
// this.firstName = limitString(firstName, USER_FIRST_NAME_MAX_LENGTH);
// }
//
// /**
// * Returns a user's last name.
// *
// * @return the last name
// */
// public String getLastName() {
// return lastName;
// }
//
// /**
// * Sets a user's last name, only the first {@link Constants.USER_LAST_NAME_MAX_LENGTH} characters are stored.
// *
// * @param lastName the last name to set
// */
// public void setLastName(String lastName) {
// this.lastName = limitString(lastName, USER_LAST_NAME_MAX_LENGTH);
// }
//
// /**
// * Returns a user's e-mail.
// *
// * @return the e-mail
// */
// public String getEmail() {
// return email;
// }
//
// /**
// * Sets a user's e-mail, only the first {@link Constants.USER_EMAIL_MAX_LENGTH} characters are stored.
// *
// * @param email the e-mail to set
// */
// public void setEmail(String email) {
// this.email = limitString(email, USER_EMAIL_MAX_LENGTH);
// }
//
// /**
// * Returns a user's ID in an external system from which the user originates.
// *
// * @return the external ID
// */
// public String getExternalId() {
// return externalId;
// }
//
// /**
// * Sets a user's ID in an external system, only the first {@link Constants.USER_EXTERNAL_ID_MAX_LENGTH} characters are stored.
// *
// * @param externalId the external ID
// */
// public void setExternalId(String externalId) {
// this.externalId = limitString(externalId, USER_EXTERNAL_ID_MAX_LENGTH);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public int hashCode() {
// return Objects.hashCode(getExternalId());
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj instanceof User) {
// User other = (User) obj;
// return Objects.equal(this.getExternalId(), other.getExternalId());
// }
// return false;
// }
//
// }
//
// Path: src/main/java/org/lbogdanov/poker/core/UserService.java
// public interface UserService {
//
// /**
// * Returns currently logged in <code>User</code> instance.
// *
// * @return the <code>User</code> object or <code>null</code> for an anonymous user
// */
// public User getCurrentUser();
//
// /**
// * Performs a login attempt with specified credentials.
// *
// * @param username the user name
// * @param password the password
// * @param rememberme if a user identity should be remembered across sessions
// * @throws <code>RuntimeException</code> if the authentication attempt fails
// */
// public void login(String username, String password, boolean rememberme);
//
// /**
// * Persists current state of a specified <code>User</code> object.
// *
// * @param user the <code>User</code> object
// */
// public void save(User user);
//
// }
| import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.lbogdanov.poker.core.User;
import org.lbogdanov.poker.core.UserService;
import org.scribe.up.profile.google2.Google2Profile;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.annotation.Transactional; | package org.lbogdanov.poker.core.impl;
/**
* Implementation of {@link UserService} interface.
*
* @author Leonid Bogdanov
*/
@Singleton
public class UserServiceImpl implements UserService {
private static final Object USER_KEY = "USER_KEY";
@Inject
private EbeanServer ebean;
/**
* {@inheritDoc}
*/
@Override | // Path: src/main/java/org/lbogdanov/poker/core/User.java
// @Entity
// @Table(name = "USERS")
// public class User extends AbstractEntity {
//
// @Column(name = "FIRST_NAME", length = USER_FIRST_NAME_MAX_LENGTH, nullable = false)
// private String firstName = "";
// @Column(name = "LAST_NAME", length = USER_LAST_NAME_MAX_LENGTH, nullable = true)
// private String lastName = "";
// @Column(name = "EMAIL", length = USER_EMAIL_MAX_LENGTH, nullable = true)
// private String email = "";
// @Column(name = "EXTERNAL_ID", length = USER_EXTERNAL_ID_MAX_LENGTH, nullable = false, unique = true)
// private String externalId = "";
//
// /**
// * Returns a user's first name.
// *
// * @return the firstName
// */
// public String getFirstName() {
// return firstName;
// }
//
// /**
// * Sets a user's first name, only the first {@link Constants.USER_FIRST_NAME_MAX_LENGTH} characters are stored.
// *
// * @param firstName the first name to set
// */
// public void setFirstName(String firstName) {
// this.firstName = limitString(firstName, USER_FIRST_NAME_MAX_LENGTH);
// }
//
// /**
// * Returns a user's last name.
// *
// * @return the last name
// */
// public String getLastName() {
// return lastName;
// }
//
// /**
// * Sets a user's last name, only the first {@link Constants.USER_LAST_NAME_MAX_LENGTH} characters are stored.
// *
// * @param lastName the last name to set
// */
// public void setLastName(String lastName) {
// this.lastName = limitString(lastName, USER_LAST_NAME_MAX_LENGTH);
// }
//
// /**
// * Returns a user's e-mail.
// *
// * @return the e-mail
// */
// public String getEmail() {
// return email;
// }
//
// /**
// * Sets a user's e-mail, only the first {@link Constants.USER_EMAIL_MAX_LENGTH} characters are stored.
// *
// * @param email the e-mail to set
// */
// public void setEmail(String email) {
// this.email = limitString(email, USER_EMAIL_MAX_LENGTH);
// }
//
// /**
// * Returns a user's ID in an external system from which the user originates.
// *
// * @return the external ID
// */
// public String getExternalId() {
// return externalId;
// }
//
// /**
// * Sets a user's ID in an external system, only the first {@link Constants.USER_EXTERNAL_ID_MAX_LENGTH} characters are stored.
// *
// * @param externalId the external ID
// */
// public void setExternalId(String externalId) {
// this.externalId = limitString(externalId, USER_EXTERNAL_ID_MAX_LENGTH);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public int hashCode() {
// return Objects.hashCode(getExternalId());
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj instanceof User) {
// User other = (User) obj;
// return Objects.equal(this.getExternalId(), other.getExternalId());
// }
// return false;
// }
//
// }
//
// Path: src/main/java/org/lbogdanov/poker/core/UserService.java
// public interface UserService {
//
// /**
// * Returns currently logged in <code>User</code> instance.
// *
// * @return the <code>User</code> object or <code>null</code> for an anonymous user
// */
// public User getCurrentUser();
//
// /**
// * Performs a login attempt with specified credentials.
// *
// * @param username the user name
// * @param password the password
// * @param rememberme if a user identity should be remembered across sessions
// * @throws <code>RuntimeException</code> if the authentication attempt fails
// */
// public void login(String username, String password, boolean rememberme);
//
// /**
// * Persists current state of a specified <code>User</code> object.
// *
// * @param user the <code>User</code> object
// */
// public void save(User user);
//
// }
// Path: src/main/java/org/lbogdanov/poker/core/impl/UserServiceImpl.java
import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.lbogdanov.poker.core.User;
import org.lbogdanov.poker.core.UserService;
import org.scribe.up.profile.google2.Google2Profile;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.annotation.Transactional;
package org.lbogdanov.poker.core.impl;
/**
* Implementation of {@link UserService} interface.
*
* @author Leonid Bogdanov
*/
@Singleton
public class UserServiceImpl implements UserService {
private static final Object USER_KEY = "USER_KEY";
@Inject
private EbeanServer ebean;
/**
* {@inheritDoc}
*/
@Override | public User getCurrentUser() { |
vonZeppelin/planning-poker | src/main/java/org/lbogdanov/poker/web/page/AbstractPage.java | // Path: src/main/java/org/lbogdanov/poker/web/markup/NavBar.java
// public class NavBar extends Panel {
//
// @Inject
// private UserService userService;
//
// /**
// * @see Panel#Panel(String)
// */
// public NavBar(String id) {
// super(id);
// Behavior visibilityManager = new Behavior() {
//
// @Override
// public void onConfigure(Component component) {
// component.setVisible(userService.getCurrentUser() != null);
// }
//
// };
// WebMarkupContainer userMenu = new WebMarkupContainer("userMenu");
// WebMarkupContainer navigation = new WebMarkupContainer("navigation");
// Label username = new BodylessLabel("username", new AbstractReadOnlyModel<User>() {
//
// @Override
// public User getObject() {
// return userService.getCurrentUser();
// }
//
// });
// userMenu.add(username, new LogoutLink("logout"));
// navigation.add(new WebMarkupContainer("sessions").add(append("class", new AbstractReadOnlyModel<String>() {
//
// @Override
// public String getObject() {
// return MySessionsPage.class.equals(NavBar.this.getPage().getClass()) ? "active" : null;
// }
//
// })));
// add(userMenu.add(visibilityManager), navigation.add(visibilityManager),
// new BookmarkablePageLink<Void>("home", getApplication().getHomePage()));
// }
//
// }
//
// Path: src/main/java/org/lbogdanov/poker/web/plugin/I18nPlugin.java
// public class I18nPlugin extends JQueryPluginResourceReference {
//
// private static final I18nPlugin INSTANCE = new I18nPlugin();
//
// /**
// * Returns a single instance of jQuery i18n plugin resource reference.
// *
// * @return the single instance
// */
// public static I18nPlugin get() {
// return INSTANCE;
// }
//
// private I18nPlugin() {
// super(I18nPlugin.class, "jquery.i18n.js");
// }
//
// }
| import java.util.Collections;
import org.apache.wicket.bootstrap.Bootstrap;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.HeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.JavaScriptResourceReference;
import org.apache.wicket.request.resource.ResourceReference;
import org.lbogdanov.poker.web.markup.NavBar;
import org.lbogdanov.poker.web.plugin.I18nPlugin; | /**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.web.page;
/**
* Base class for all pages: adds Twitter Bootstrap files, global navbar.
*
* @author Leonid Bogdanov
*/
abstract class AbstractPage extends WebPage {
protected final ResourceReference I18N = new JavaScriptResourceReference(AbstractPage.class, "i18n.js",
getLocale(), null, null) {
@Override
public Iterable<? extends HeaderItem> getDependencies() { | // Path: src/main/java/org/lbogdanov/poker/web/markup/NavBar.java
// public class NavBar extends Panel {
//
// @Inject
// private UserService userService;
//
// /**
// * @see Panel#Panel(String)
// */
// public NavBar(String id) {
// super(id);
// Behavior visibilityManager = new Behavior() {
//
// @Override
// public void onConfigure(Component component) {
// component.setVisible(userService.getCurrentUser() != null);
// }
//
// };
// WebMarkupContainer userMenu = new WebMarkupContainer("userMenu");
// WebMarkupContainer navigation = new WebMarkupContainer("navigation");
// Label username = new BodylessLabel("username", new AbstractReadOnlyModel<User>() {
//
// @Override
// public User getObject() {
// return userService.getCurrentUser();
// }
//
// });
// userMenu.add(username, new LogoutLink("logout"));
// navigation.add(new WebMarkupContainer("sessions").add(append("class", new AbstractReadOnlyModel<String>() {
//
// @Override
// public String getObject() {
// return MySessionsPage.class.equals(NavBar.this.getPage().getClass()) ? "active" : null;
// }
//
// })));
// add(userMenu.add(visibilityManager), navigation.add(visibilityManager),
// new BookmarkablePageLink<Void>("home", getApplication().getHomePage()));
// }
//
// }
//
// Path: src/main/java/org/lbogdanov/poker/web/plugin/I18nPlugin.java
// public class I18nPlugin extends JQueryPluginResourceReference {
//
// private static final I18nPlugin INSTANCE = new I18nPlugin();
//
// /**
// * Returns a single instance of jQuery i18n plugin resource reference.
// *
// * @return the single instance
// */
// public static I18nPlugin get() {
// return INSTANCE;
// }
//
// private I18nPlugin() {
// super(I18nPlugin.class, "jquery.i18n.js");
// }
//
// }
// Path: src/main/java/org/lbogdanov/poker/web/page/AbstractPage.java
import java.util.Collections;
import org.apache.wicket.bootstrap.Bootstrap;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.HeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.JavaScriptResourceReference;
import org.apache.wicket.request.resource.ResourceReference;
import org.lbogdanov.poker.web.markup.NavBar;
import org.lbogdanov.poker.web.plugin.I18nPlugin;
/**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.web.page;
/**
* Base class for all pages: adds Twitter Bootstrap files, global navbar.
*
* @author Leonid Bogdanov
*/
abstract class AbstractPage extends WebPage {
protected final ResourceReference I18N = new JavaScriptResourceReference(AbstractPage.class, "i18n.js",
getLocale(), null, null) {
@Override
public Iterable<? extends HeaderItem> getDependencies() { | return Collections.singletonList(JavaScriptHeaderItem.forReference(I18nPlugin.get())); |
vonZeppelin/planning-poker | src/main/java/org/lbogdanov/poker/web/page/AbstractPage.java | // Path: src/main/java/org/lbogdanov/poker/web/markup/NavBar.java
// public class NavBar extends Panel {
//
// @Inject
// private UserService userService;
//
// /**
// * @see Panel#Panel(String)
// */
// public NavBar(String id) {
// super(id);
// Behavior visibilityManager = new Behavior() {
//
// @Override
// public void onConfigure(Component component) {
// component.setVisible(userService.getCurrentUser() != null);
// }
//
// };
// WebMarkupContainer userMenu = new WebMarkupContainer("userMenu");
// WebMarkupContainer navigation = new WebMarkupContainer("navigation");
// Label username = new BodylessLabel("username", new AbstractReadOnlyModel<User>() {
//
// @Override
// public User getObject() {
// return userService.getCurrentUser();
// }
//
// });
// userMenu.add(username, new LogoutLink("logout"));
// navigation.add(new WebMarkupContainer("sessions").add(append("class", new AbstractReadOnlyModel<String>() {
//
// @Override
// public String getObject() {
// return MySessionsPage.class.equals(NavBar.this.getPage().getClass()) ? "active" : null;
// }
//
// })));
// add(userMenu.add(visibilityManager), navigation.add(visibilityManager),
// new BookmarkablePageLink<Void>("home", getApplication().getHomePage()));
// }
//
// }
//
// Path: src/main/java/org/lbogdanov/poker/web/plugin/I18nPlugin.java
// public class I18nPlugin extends JQueryPluginResourceReference {
//
// private static final I18nPlugin INSTANCE = new I18nPlugin();
//
// /**
// * Returns a single instance of jQuery i18n plugin resource reference.
// *
// * @return the single instance
// */
// public static I18nPlugin get() {
// return INSTANCE;
// }
//
// private I18nPlugin() {
// super(I18nPlugin.class, "jquery.i18n.js");
// }
//
// }
| import java.util.Collections;
import org.apache.wicket.bootstrap.Bootstrap;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.HeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.JavaScriptResourceReference;
import org.apache.wicket.request.resource.ResourceReference;
import org.lbogdanov.poker.web.markup.NavBar;
import org.lbogdanov.poker.web.plugin.I18nPlugin; | /**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.web.page;
/**
* Base class for all pages: adds Twitter Bootstrap files, global navbar.
*
* @author Leonid Bogdanov
*/
abstract class AbstractPage extends WebPage {
protected final ResourceReference I18N = new JavaScriptResourceReference(AbstractPage.class, "i18n.js",
getLocale(), null, null) {
@Override
public Iterable<? extends HeaderItem> getDependencies() {
return Collections.singletonList(JavaScriptHeaderItem.forReference(I18nPlugin.get()));
}
};
| // Path: src/main/java/org/lbogdanov/poker/web/markup/NavBar.java
// public class NavBar extends Panel {
//
// @Inject
// private UserService userService;
//
// /**
// * @see Panel#Panel(String)
// */
// public NavBar(String id) {
// super(id);
// Behavior visibilityManager = new Behavior() {
//
// @Override
// public void onConfigure(Component component) {
// component.setVisible(userService.getCurrentUser() != null);
// }
//
// };
// WebMarkupContainer userMenu = new WebMarkupContainer("userMenu");
// WebMarkupContainer navigation = new WebMarkupContainer("navigation");
// Label username = new BodylessLabel("username", new AbstractReadOnlyModel<User>() {
//
// @Override
// public User getObject() {
// return userService.getCurrentUser();
// }
//
// });
// userMenu.add(username, new LogoutLink("logout"));
// navigation.add(new WebMarkupContainer("sessions").add(append("class", new AbstractReadOnlyModel<String>() {
//
// @Override
// public String getObject() {
// return MySessionsPage.class.equals(NavBar.this.getPage().getClass()) ? "active" : null;
// }
//
// })));
// add(userMenu.add(visibilityManager), navigation.add(visibilityManager),
// new BookmarkablePageLink<Void>("home", getApplication().getHomePage()));
// }
//
// }
//
// Path: src/main/java/org/lbogdanov/poker/web/plugin/I18nPlugin.java
// public class I18nPlugin extends JQueryPluginResourceReference {
//
// private static final I18nPlugin INSTANCE = new I18nPlugin();
//
// /**
// * Returns a single instance of jQuery i18n plugin resource reference.
// *
// * @return the single instance
// */
// public static I18nPlugin get() {
// return INSTANCE;
// }
//
// private I18nPlugin() {
// super(I18nPlugin.class, "jquery.i18n.js");
// }
//
// }
// Path: src/main/java/org/lbogdanov/poker/web/page/AbstractPage.java
import java.util.Collections;
import org.apache.wicket.bootstrap.Bootstrap;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.HeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.JavaScriptResourceReference;
import org.apache.wicket.request.resource.ResourceReference;
import org.lbogdanov.poker.web.markup.NavBar;
import org.lbogdanov.poker.web.plugin.I18nPlugin;
/**
* Copyright 2012 Leonid Bogdanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lbogdanov.poker.web.page;
/**
* Base class for all pages: adds Twitter Bootstrap files, global navbar.
*
* @author Leonid Bogdanov
*/
abstract class AbstractPage extends WebPage {
protected final ResourceReference I18N = new JavaScriptResourceReference(AbstractPage.class, "i18n.js",
getLocale(), null, null) {
@Override
public Iterable<? extends HeaderItem> getDependencies() {
return Collections.singletonList(JavaScriptHeaderItem.forReference(I18nPlugin.get()));
}
};
| private NavBar navBar; |
vonZeppelin/planning-poker | src/test/java/org/lbogdanov/poker/core/DurationTest.java | // Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * 8;
//
// Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_HOUR = 60;
//
// Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_WEEK = MINUTES_PER_DAY * 5;
| import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_DAY;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_HOUR;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_WEEK;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException; | package org.lbogdanov.poker.core;
/**
* Tests for {@link Duration} class.
*
* @author Alexandra Fomina
*
*/
public class DurationTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Test for {@link Duration#Duration(int)} with invalid input.
*/
@Test(expected = IllegalArgumentException.class)
public void testInvalidArgument() {
new Duration(-1);
}
/**
* Test for {@link Duration#parse(String)}.
*/
@Test
public void testParse() { | // Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * 8;
//
// Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_HOUR = 60;
//
// Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_WEEK = MINUTES_PER_DAY * 5;
// Path: src/test/java/org/lbogdanov/poker/core/DurationTest.java
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_DAY;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_HOUR;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_WEEK;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
package org.lbogdanov.poker.core;
/**
* Tests for {@link Duration} class.
*
* @author Alexandra Fomina
*
*/
public class DurationTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Test for {@link Duration#Duration(int)} with invalid input.
*/
@Test(expected = IllegalArgumentException.class)
public void testInvalidArgument() {
new Duration(-1);
}
/**
* Test for {@link Duration#parse(String)}.
*/
@Test
public void testParse() { | Duration[] durations = {new Duration(30), new Duration(MINUTES_PER_HOUR), |
vonZeppelin/planning-poker | src/test/java/org/lbogdanov/poker/core/DurationTest.java | // Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * 8;
//
// Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_HOUR = 60;
//
// Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_WEEK = MINUTES_PER_DAY * 5;
| import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_DAY;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_HOUR;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_WEEK;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException; | package org.lbogdanov.poker.core;
/**
* Tests for {@link Duration} class.
*
* @author Alexandra Fomina
*
*/
public class DurationTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Test for {@link Duration#Duration(int)} with invalid input.
*/
@Test(expected = IllegalArgumentException.class)
public void testInvalidArgument() {
new Duration(-1);
}
/**
* Test for {@link Duration#parse(String)}.
*/
@Test
public void testParse() {
Duration[] durations = {new Duration(30), new Duration(MINUTES_PER_HOUR), | // Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * 8;
//
// Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_HOUR = 60;
//
// Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_WEEK = MINUTES_PER_DAY * 5;
// Path: src/test/java/org/lbogdanov/poker/core/DurationTest.java
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_DAY;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_HOUR;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_WEEK;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
package org.lbogdanov.poker.core;
/**
* Tests for {@link Duration} class.
*
* @author Alexandra Fomina
*
*/
public class DurationTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Test for {@link Duration#Duration(int)} with invalid input.
*/
@Test(expected = IllegalArgumentException.class)
public void testInvalidArgument() {
new Duration(-1);
}
/**
* Test for {@link Duration#parse(String)}.
*/
@Test
public void testParse() {
Duration[] durations = {new Duration(30), new Duration(MINUTES_PER_HOUR), | new Duration(MINUTES_PER_DAY), new Duration(MINUTES_PER_WEEK)}; |
vonZeppelin/planning-poker | src/test/java/org/lbogdanov/poker/core/DurationTest.java | // Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * 8;
//
// Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_HOUR = 60;
//
// Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_WEEK = MINUTES_PER_DAY * 5;
| import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_DAY;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_HOUR;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_WEEK;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException; | package org.lbogdanov.poker.core;
/**
* Tests for {@link Duration} class.
*
* @author Alexandra Fomina
*
*/
public class DurationTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Test for {@link Duration#Duration(int)} with invalid input.
*/
@Test(expected = IllegalArgumentException.class)
public void testInvalidArgument() {
new Duration(-1);
}
/**
* Test for {@link Duration#parse(String)}.
*/
@Test
public void testParse() {
Duration[] durations = {new Duration(30), new Duration(MINUTES_PER_HOUR), | // Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * 8;
//
// Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_HOUR = 60;
//
// Path: src/main/java/org/lbogdanov/poker/core/Duration.java
// static final int MINUTES_PER_WEEK = MINUTES_PER_DAY * 5;
// Path: src/test/java/org/lbogdanov/poker/core/DurationTest.java
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_DAY;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_HOUR;
import static org.lbogdanov.poker.core.Duration.MINUTES_PER_WEEK;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
package org.lbogdanov.poker.core;
/**
* Tests for {@link Duration} class.
*
* @author Alexandra Fomina
*
*/
public class DurationTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Test for {@link Duration#Duration(int)} with invalid input.
*/
@Test(expected = IllegalArgumentException.class)
public void testInvalidArgument() {
new Duration(-1);
}
/**
* Test for {@link Duration#parse(String)}.
*/
@Test
public void testParse() {
Duration[] durations = {new Duration(30), new Duration(MINUTES_PER_HOUR), | new Duration(MINUTES_PER_DAY), new Duration(MINUTES_PER_WEEK)}; |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/data/parse/GoodBarcodeImporter.java | // Path: bst/src/main/java/ru/redsolution/bst/data/table/GoodBarcodeTable.java
// public class GoodBarcodeTable extends BaseBarcodeTable {
//
// private static final String NAME = "good_barcode";
//
// private final static GoodBarcodeTable instance;
//
// static {
// instance = new GoodBarcodeTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static GoodBarcodeTable getInstance() {
// return instance;
// }
//
// private GoodBarcodeTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// }
| import ru.redsolution.bst.data.table.GoodBarcodeTable; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class GoodBarcodeImporter extends BaseBarcodeImporter {
public GoodBarcodeImporter(BarcodeContainerImporter importer) {
super(importer);
}
@Override
protected void save(String id) { | // Path: bst/src/main/java/ru/redsolution/bst/data/table/GoodBarcodeTable.java
// public class GoodBarcodeTable extends BaseBarcodeTable {
//
// private static final String NAME = "good_barcode";
//
// private final static GoodBarcodeTable instance;
//
// static {
// instance = new GoodBarcodeTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static GoodBarcodeTable getInstance() {
// return instance;
// }
//
// private GoodBarcodeTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/data/parse/GoodBarcodeImporter.java
import ru.redsolution.bst.data.table.GoodBarcodeTable;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class GoodBarcodeImporter extends BaseBarcodeImporter {
public GoodBarcodeImporter(BarcodeContainerImporter importer) {
super(importer);
}
@Override
protected void save(String id) { | GoodBarcodeTable.getInstance().add(id, type, value); |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/data/parse/UomImporter.java | // Path: bst/src/main/java/ru/redsolution/bst/data/table/UomTable.java
// public class UomTable extends NamedTable {
//
// private static final String NAME = "uom";
//
// private final static UomTable instance;
//
// static {
// instance = new UomTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static UomTable getInstance() {
// return instance;
// }
//
// private UomTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// }
| import ru.redsolution.bst.data.table.UomTable; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class UomImporter extends NamedImporter {
@Override
protected void save() { | // Path: bst/src/main/java/ru/redsolution/bst/data/table/UomTable.java
// public class UomTable extends NamedTable {
//
// private static final String NAME = "uom";
//
// private final static UomTable instance;
//
// static {
// instance = new UomTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static UomTable getInstance() {
// return instance;
// }
//
// private UomTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/data/parse/UomImporter.java
import ru.redsolution.bst.data.table.UomTable;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class UomImporter extends NamedImporter {
@Override
protected void save() { | UomTable.getInstance().add(id, name); |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/ui/dialog/CursorEmptyChoiceDialogBuilder.java | // Path: bst/src/main/java/ru/redsolution/dialogs/AcceptAndDeclineDialogListener.java
// public interface AcceptAndDeclineDialogListener extends AcceptDialogListener {
//
// /**
// * Request was declined. "No" button was pushed.
// */
// void onDecline(DialogBuilder dialogBuilder);
// }
//
// Path: bst/src/main/java/ru/redsolution/dialogs/CursorChoiceDialogBuilder.java
// public class CursorChoiceDialogBuilder extends DialogBuilder implements
// DialogInterface.OnClickListener, OnCancelListener {
// protected final AcceptAndDeclineDialogListener listener;
// protected final Cursor cursor;
// protected String checkedId;
//
// /**
// * @param activity
// * @param dialogId
// * @param listener
// * @param cursor
// * @param checkedId
// * @param labelColumn
// */
// public CursorChoiceDialogBuilder(Activity activity, int dialogId,
// AcceptAndDeclineDialogListener listener, Cursor cursor,
// String checkedId, String labelColumn) {
// super(activity, dialogId);
// this.listener = listener;
// this.cursor = cursor;
// this.checkedId = null;
// int checkedItem = -1;
// if (cursor.moveToFirst()) {
// int index = 0;
// do {
// if (cursor.getString(cursor.getColumnIndex(BaseColumns._ID))
// .equals(checkedId)) {
// this.checkedId = checkedId;
// checkedItem = index;
// break;
// }
// index++;
// } while (cursor.moveToNext());
// }
// setSingleChoiceItems(cursor, checkedItem, labelColumn, this);
// setOnCancelListener(this);
// }
//
// @Override
// public void onClick(DialogInterface dialog, int id) {
// if (cursor.moveToPosition(id)) {
// checkedId = cursor
// .getString(cursor.getColumnIndex(BaseColumns._ID));
// } else {
// throw new IllegalStateException();
// }
// dialog.dismiss();
// listener.onAccept(this);
// }
//
// /**
// * Возвращает идентификатор в базе для выбранного элемента.
// *
// * @return <code>null</code> если нет выбранного элемента.
// */
// public String getCheckedId() {
// return checkedId;
// }
//
// @Override
// public void onCancel(DialogInterface dialog) {
// dialog.dismiss();
// listener.onDecline(this);
// }
//
// }
| import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import ru.redsolution.bst.R;
import ru.redsolution.dialogs.AcceptAndDeclineDialogListener;
import ru.redsolution.dialogs.CursorChoiceDialogBuilder;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.view.View;
import android.widget.HeaderViewListAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ListView.FixedViewInfo; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.ui.dialog;
/**
* Диалог с возможностью выбрать один из пунктов курсора либо убрать значение.
*
* @author alexander.ivanov
*
*/
public class CursorEmptyChoiceDialogBuilder extends CursorChoiceDialogBuilder {
private HeaderViewListAdapter adapter;
public CursorEmptyChoiceDialogBuilder(Activity activity, int dialogId, | // Path: bst/src/main/java/ru/redsolution/dialogs/AcceptAndDeclineDialogListener.java
// public interface AcceptAndDeclineDialogListener extends AcceptDialogListener {
//
// /**
// * Request was declined. "No" button was pushed.
// */
// void onDecline(DialogBuilder dialogBuilder);
// }
//
// Path: bst/src/main/java/ru/redsolution/dialogs/CursorChoiceDialogBuilder.java
// public class CursorChoiceDialogBuilder extends DialogBuilder implements
// DialogInterface.OnClickListener, OnCancelListener {
// protected final AcceptAndDeclineDialogListener listener;
// protected final Cursor cursor;
// protected String checkedId;
//
// /**
// * @param activity
// * @param dialogId
// * @param listener
// * @param cursor
// * @param checkedId
// * @param labelColumn
// */
// public CursorChoiceDialogBuilder(Activity activity, int dialogId,
// AcceptAndDeclineDialogListener listener, Cursor cursor,
// String checkedId, String labelColumn) {
// super(activity, dialogId);
// this.listener = listener;
// this.cursor = cursor;
// this.checkedId = null;
// int checkedItem = -1;
// if (cursor.moveToFirst()) {
// int index = 0;
// do {
// if (cursor.getString(cursor.getColumnIndex(BaseColumns._ID))
// .equals(checkedId)) {
// this.checkedId = checkedId;
// checkedItem = index;
// break;
// }
// index++;
// } while (cursor.moveToNext());
// }
// setSingleChoiceItems(cursor, checkedItem, labelColumn, this);
// setOnCancelListener(this);
// }
//
// @Override
// public void onClick(DialogInterface dialog, int id) {
// if (cursor.moveToPosition(id)) {
// checkedId = cursor
// .getString(cursor.getColumnIndex(BaseColumns._ID));
// } else {
// throw new IllegalStateException();
// }
// dialog.dismiss();
// listener.onAccept(this);
// }
//
// /**
// * Возвращает идентификатор в базе для выбранного элемента.
// *
// * @return <code>null</code> если нет выбранного элемента.
// */
// public String getCheckedId() {
// return checkedId;
// }
//
// @Override
// public void onCancel(DialogInterface dialog) {
// dialog.dismiss();
// listener.onDecline(this);
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/ui/dialog/CursorEmptyChoiceDialogBuilder.java
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import ru.redsolution.bst.R;
import ru.redsolution.dialogs.AcceptAndDeclineDialogListener;
import ru.redsolution.dialogs.CursorChoiceDialogBuilder;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.view.View;
import android.widget.HeaderViewListAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ListView.FixedViewInfo;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.ui.dialog;
/**
* Диалог с возможностью выбрать один из пунктов курсора либо убрать значение.
*
* @author alexander.ivanov
*
*/
public class CursorEmptyChoiceDialogBuilder extends CursorChoiceDialogBuilder {
private HeaderViewListAdapter adapter;
public CursorEmptyChoiceDialogBuilder(Activity activity, int dialogId, | AcceptAndDeclineDialogListener listener, Cursor cursor, |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/data/parse/PriceTypeImporter.java | // Path: bst/src/main/java/ru/redsolution/bst/data/table/PriceTypeTable.java
// public class PriceTypeTable extends NamedTable {
//
// private static final String NAME = "price_type";
//
// private final static PriceTypeTable instance;
//
// static {
// instance = new PriceTypeTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static PriceTypeTable getInstance() {
// return instance;
// }
//
// private PriceTypeTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// @Override
// public void migrate(SQLiteDatabase db, int toVersion) {
// super.migrate(db, toVersion);
// String sql;
// switch (toVersion) {
// case 5:
// sql = "CREATE TABLE price_type (" + "_id TEXT,"
// + "name TEXT COLLATE UNICODE);";
// DatabaseHelper.execSQL(db, sql);
// break;
// default:
// break;
// }
// }
//
// }
| import ru.redsolution.bst.data.table.PriceTypeTable; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class PriceTypeImporter extends NamedImporter {
@Override
protected void save() { | // Path: bst/src/main/java/ru/redsolution/bst/data/table/PriceTypeTable.java
// public class PriceTypeTable extends NamedTable {
//
// private static final String NAME = "price_type";
//
// private final static PriceTypeTable instance;
//
// static {
// instance = new PriceTypeTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static PriceTypeTable getInstance() {
// return instance;
// }
//
// private PriceTypeTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// @Override
// public void migrate(SQLiteDatabase db, int toVersion) {
// super.migrate(db, toVersion);
// String sql;
// switch (toVersion) {
// case 5:
// sql = "CREATE TABLE price_type (" + "_id TEXT,"
// + "name TEXT COLLATE UNICODE);";
// DatabaseHelper.execSQL(db, sql);
// break;
// default:
// break;
// }
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/data/parse/PriceTypeImporter.java
import ru.redsolution.bst.data.table.PriceTypeTable;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class PriceTypeImporter extends NamedImporter {
@Override
protected void save() { | PriceTypeTable.getInstance().add(id, name); |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/data/parse/ContractImporter.java | // Path: bst/src/main/java/ru/redsolution/bst/data/table/ContractTable.java
// public class ContractTable extends NamedTable {
// public static final class Fields implements NamedTable.Fields {
// private Fields() {
// }
//
// public static final String COMPANY = "company";
// public static final String MY_COMPANY = "my_company";
// }
//
// private static final String NAME = "contract";
//
// private final static ContractTable instance;
//
// static {
// instance = new ContractTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static ContractTable getInstance() {
// return instance;
// }
//
// private ContractTable() {
// }
//
// @Override
// protected String getTableName() {
// return NAME;
// }
//
// @Override
// protected Collection<String> getFields() {
// Collection<String> collection = new ArrayList<String>(super.getFields());
// collection.add(Fields.COMPANY);
// collection.add(Fields.MY_COMPANY);
// return collection;
// }
//
// @Override
// public Cursor list() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * @param company
// * @param myCompany
// * @return Список объетов.
// */
// public Cursor list(String company, String myCompany) {
// return filter(
// Fields.COMPANY + " = ? AND " + Fields.MY_COMPANY + " = ?",
// new String[] { company, myCompany }, null);
// }
//
// /**
// * @param id
// * @param company
// * @param myCompany
// * @return Относится ли контракт к указанному контрагенту и организации.
// */
// public boolean acceptable(String id, String company, String myCompany) {
// ContentValues values;
// try {
// values = getById(id);
// } catch (BaseDatabaseException e) {
// return false;
// }
// return values.getAsString(Fields.COMPANY).equals(company)
// && values.getAsString(Fields.MY_COMPANY).equals(myCompany);
// }
//
// @Override
// public void add(String id, String name) {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Добавить элемент.
// *
// * @param id
// * @param name
// * @param company
// * @param myCompany
// */
// public void add(String id, String name, String company, String myCompany) {
// ContentValues values = getValues(id, name);
// values.put(Fields.COMPANY, company);
// values.put(Fields.MY_COMPANY, myCompany);
// add(values);
// }
// }
| import org.xmlpull.v1.XmlPullParser;
import ru.redsolution.bst.data.table.ContractTable;
import android.util.Log; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class ContractImporter extends NamedImporter {
protected String company = null;
protected String myCompany = null;
@Override
protected void preProcess(XmlPullParser parser) {
super.preProcess(parser);
company = parser.getAttributeValue(null, "agentUuid");
myCompany = parser.getAttributeValue(null, "ownCompanyUuid");
}
@Override
public boolean isValid() {
if (!super.isValid())
return false;
if (company == null) {
Log.w(this.getClass().toString(), "company is null ");
return false;
}
if (myCompany == null) {
Log.w(this.getClass().toString(), "my company is null ");
return false;
}
return true;
}
@Override
protected void save() { | // Path: bst/src/main/java/ru/redsolution/bst/data/table/ContractTable.java
// public class ContractTable extends NamedTable {
// public static final class Fields implements NamedTable.Fields {
// private Fields() {
// }
//
// public static final String COMPANY = "company";
// public static final String MY_COMPANY = "my_company";
// }
//
// private static final String NAME = "contract";
//
// private final static ContractTable instance;
//
// static {
// instance = new ContractTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static ContractTable getInstance() {
// return instance;
// }
//
// private ContractTable() {
// }
//
// @Override
// protected String getTableName() {
// return NAME;
// }
//
// @Override
// protected Collection<String> getFields() {
// Collection<String> collection = new ArrayList<String>(super.getFields());
// collection.add(Fields.COMPANY);
// collection.add(Fields.MY_COMPANY);
// return collection;
// }
//
// @Override
// public Cursor list() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * @param company
// * @param myCompany
// * @return Список объетов.
// */
// public Cursor list(String company, String myCompany) {
// return filter(
// Fields.COMPANY + " = ? AND " + Fields.MY_COMPANY + " = ?",
// new String[] { company, myCompany }, null);
// }
//
// /**
// * @param id
// * @param company
// * @param myCompany
// * @return Относится ли контракт к указанному контрагенту и организации.
// */
// public boolean acceptable(String id, String company, String myCompany) {
// ContentValues values;
// try {
// values = getById(id);
// } catch (BaseDatabaseException e) {
// return false;
// }
// return values.getAsString(Fields.COMPANY).equals(company)
// && values.getAsString(Fields.MY_COMPANY).equals(myCompany);
// }
//
// @Override
// public void add(String id, String name) {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Добавить элемент.
// *
// * @param id
// * @param name
// * @param company
// * @param myCompany
// */
// public void add(String id, String name, String company, String myCompany) {
// ContentValues values = getValues(id, name);
// values.put(Fields.COMPANY, company);
// values.put(Fields.MY_COMPANY, myCompany);
// add(values);
// }
// }
// Path: bst/src/main/java/ru/redsolution/bst/data/parse/ContractImporter.java
import org.xmlpull.v1.XmlPullParser;
import ru.redsolution.bst.data.table.ContractTable;
import android.util.Log;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class ContractImporter extends NamedImporter {
protected String company = null;
protected String myCompany = null;
@Override
protected void preProcess(XmlPullParser parser) {
super.preProcess(parser);
company = parser.getAttributeValue(null, "agentUuid");
myCompany = parser.getAttributeValue(null, "ownCompanyUuid");
}
@Override
public boolean isValid() {
if (!super.isValid())
return false;
if (company == null) {
Log.w(this.getClass().toString(), "company is null ");
return false;
}
if (myCompany == null) {
Log.w(this.getClass().toString(), "my company is null ");
return false;
}
return true;
}
@Override
protected void save() { | ContractTable.getInstance().add(id, name, company, myCompany); |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/ui/dialog/CancelableDialogWrapper.java | // Path: bst/src/main/java/ru/redsolution/dialogs/AcceptAndDeclineDialogListener.java
// public interface AcceptAndDeclineDialogListener extends AcceptDialogListener {
//
// /**
// * Request was declined. "No" button was pushed.
// */
// void onDecline(DialogBuilder dialogBuilder);
// }
//
// Path: bst/src/main/java/ru/redsolution/dialogs/DialogBuilder.java
// public class DialogBuilder extends AlertDialog.Builder implements
// DialogInterface.OnDismissListener {
// protected final Activity activity;
// protected final int dialogId;
//
// /**
// * Create builder.
// *
// * @param activity
// * Parent activity.
// * @param dialogId
// * Dialog ID to be removed.
// */
// public DialogBuilder(Activity activity, int dialogId) {
// super(activity);
// this.activity = activity;
// this.dialogId = dialogId;
// }
//
// @Override
// public AlertDialog create() {
// AlertDialog alertDialog = super.create();
// alertDialog.setOnDismissListener(this);
// return alertDialog;
// }
//
// @Override
// public void onDismiss(DialogInterface dialog) {
// activity.removeDialog(dialogId);
// }
//
// /**
// * Returns dialog ID.
// *
// * @return
// */
// public int getDialogId() {
// return dialogId;
// }
// }
| import ru.redsolution.dialogs.AcceptAndDeclineDialogListener;
import ru.redsolution.dialogs.DialogBuilder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.ui.dialog;
/**
* Обертка для добавления кнопки отмены к {@link DialogBuilder}.
*
* @author alexander.ivanov
*
* @param <T>
*/
public class CancelableDialogWrapper<T extends DialogBuilder> implements
OnClickListener {
| // Path: bst/src/main/java/ru/redsolution/dialogs/AcceptAndDeclineDialogListener.java
// public interface AcceptAndDeclineDialogListener extends AcceptDialogListener {
//
// /**
// * Request was declined. "No" button was pushed.
// */
// void onDecline(DialogBuilder dialogBuilder);
// }
//
// Path: bst/src/main/java/ru/redsolution/dialogs/DialogBuilder.java
// public class DialogBuilder extends AlertDialog.Builder implements
// DialogInterface.OnDismissListener {
// protected final Activity activity;
// protected final int dialogId;
//
// /**
// * Create builder.
// *
// * @param activity
// * Parent activity.
// * @param dialogId
// * Dialog ID to be removed.
// */
// public DialogBuilder(Activity activity, int dialogId) {
// super(activity);
// this.activity = activity;
// this.dialogId = dialogId;
// }
//
// @Override
// public AlertDialog create() {
// AlertDialog alertDialog = super.create();
// alertDialog.setOnDismissListener(this);
// return alertDialog;
// }
//
// @Override
// public void onDismiss(DialogInterface dialog) {
// activity.removeDialog(dialogId);
// }
//
// /**
// * Returns dialog ID.
// *
// * @return
// */
// public int getDialogId() {
// return dialogId;
// }
// }
// Path: bst/src/main/java/ru/redsolution/bst/ui/dialog/CancelableDialogWrapper.java
import ru.redsolution.dialogs.AcceptAndDeclineDialogListener;
import ru.redsolution.dialogs.DialogBuilder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.ui.dialog;
/**
* Обертка для добавления кнопки отмены к {@link DialogBuilder}.
*
* @author alexander.ivanov
*
* @param <T>
*/
public class CancelableDialogWrapper<T extends DialogBuilder> implements
OnClickListener {
| private final AcceptAndDeclineDialogListener listener; |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/data/parse/CompanyImporter.java | // Path: bst/src/main/java/ru/redsolution/bst/data/table/CompanyTable.java
// public class CompanyTable extends NamedTable {
//
// private static final String NAME = "company";
//
// private final static CompanyTable instance;
//
// static {
// instance = new CompanyTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static CompanyTable getInstance() {
// return instance;
// }
//
// private CompanyTable() {
// }
//
// @Override
// protected String getTableName() {
// return NAME;
// }
//
// @Override
// public void migrate(SQLiteDatabase db, int toVersion) {
// super.migrate(db, toVersion);
// String sql;
// switch (toVersion) {
// case 3:
// sql = "ALTER TABLE company RENAME TO company_;";
// DatabaseHelper.execSQL(db, sql);
// sql = "CREATE TABLE company (" + "_id TEXT,"
// + "name TEXT COLLATE UNICODE);";
// DatabaseHelper.execSQL(db, sql);
// sql = "INSERT INTO company (_id, name) "
// + "SELECT _id, name FROM company_;";
// DatabaseHelper.execSQL(db, sql);
// sql = "DROP TABLE company_;";
// DatabaseHelper.execSQL(db, sql);
// break;
// default:
// break;
// }
// }
//
// }
| import ru.redsolution.bst.data.table.CompanyTable; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class CompanyImporter extends NamedImporter {
@Override
protected void save() { | // Path: bst/src/main/java/ru/redsolution/bst/data/table/CompanyTable.java
// public class CompanyTable extends NamedTable {
//
// private static final String NAME = "company";
//
// private final static CompanyTable instance;
//
// static {
// instance = new CompanyTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static CompanyTable getInstance() {
// return instance;
// }
//
// private CompanyTable() {
// }
//
// @Override
// protected String getTableName() {
// return NAME;
// }
//
// @Override
// public void migrate(SQLiteDatabase db, int toVersion) {
// super.migrate(db, toVersion);
// String sql;
// switch (toVersion) {
// case 3:
// sql = "ALTER TABLE company RENAME TO company_;";
// DatabaseHelper.execSQL(db, sql);
// sql = "CREATE TABLE company (" + "_id TEXT,"
// + "name TEXT COLLATE UNICODE);";
// DatabaseHelper.execSQL(db, sql);
// sql = "INSERT INTO company (_id, name) "
// + "SELECT _id, name FROM company_;";
// DatabaseHelper.execSQL(db, sql);
// sql = "DROP TABLE company_;";
// DatabaseHelper.execSQL(db, sql);
// break;
// default:
// break;
// }
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/data/parse/CompanyImporter.java
import ru.redsolution.bst.data.table.CompanyTable;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class CompanyImporter extends NamedImporter {
@Override
protected void save() { | CompanyTable.getInstance().add(id, name); |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/data/parse/GoodFolderImporter.java | // Path: bst/src/main/java/ru/redsolution/bst/data/table/GoodFolderTable.java
// public class GoodFolderTable extends ParentableTable {
//
// private static final String NAME = "good_folder";
//
// private final static GoodFolderTable instance;
//
// static {
// instance = new GoodFolderTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static GoodFolderTable getInstance() {
// return instance;
// }
//
// private GoodFolderTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// @Override
// public Cursor list() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * @param parent
// * @return Список групп товаров.
// */
// public Cursor list(String parent) {
// return filter(Fields.PARENT + " = ?", new String[] { parent },
// Fields.NAME);
// }
//
// }
| import ru.redsolution.bst.data.table.GoodFolderTable; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class GoodFolderImporter extends ParentableImporter {
@Override
protected void save() { | // Path: bst/src/main/java/ru/redsolution/bst/data/table/GoodFolderTable.java
// public class GoodFolderTable extends ParentableTable {
//
// private static final String NAME = "good_folder";
//
// private final static GoodFolderTable instance;
//
// static {
// instance = new GoodFolderTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static GoodFolderTable getInstance() {
// return instance;
// }
//
// private GoodFolderTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// @Override
// public Cursor list() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * @param parent
// * @return Список групп товаров.
// */
// public Cursor list(String parent) {
// return filter(Fields.PARENT + " = ?", new String[] { parent },
// Fields.NAME);
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/data/parse/GoodFolderImporter.java
import ru.redsolution.bst.data.table.GoodFolderTable;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class GoodFolderImporter extends ParentableImporter {
@Override
protected void save() { | GoodFolderTable.getInstance().add(id, name, parent); |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/ui/dialog/ValueDialogBuilder.java | // Path: bst/src/main/java/ru/redsolution/dialogs/AcceptAndDeclineDialogListener.java
// public interface AcceptAndDeclineDialogListener extends AcceptDialogListener {
//
// /**
// * Request was declined. "No" button was pushed.
// */
// void onDecline(DialogBuilder dialogBuilder);
// }
//
// Path: bst/src/main/java/ru/redsolution/dialogs/ConfirmDialogBuilder.java
// public class ConfirmDialogBuilder extends DialogBuilder implements
// DialogInterface.OnClickListener, OnCancelListener {
// private final AcceptAndDeclineDialogListener listener;
//
// /**
// * Yes / No dialog builder.
// *
// * @param activity
// * Parent activity.
// * @param dialogId
// * Dialog ID to be removed.
// * @param listener
// * Action listener.
// */
// public ConfirmDialogBuilder(Activity activity, int dialogId,
// AcceptAndDeclineDialogListener listener) {
// super(activity, dialogId);
// this.listener = listener;
// setPositiveButton(activity.getString(android.R.string.yes), this);
// setNegativeButton(activity.getString(android.R.string.no), this);
// setOnCancelListener(this);
// }
//
// @Override
// public void onClick(DialogInterface dialog, int id) {
// switch (id) {
// case DialogInterface.BUTTON_POSITIVE:
// dialog.dismiss();
// listener.onAccept(this);
// break;
// case DialogInterface.BUTTON_NEGATIVE:
// dialog.dismiss();
// listener.onDecline(this);
// break;
// }
// }
//
// @Override
// public void onCancel(DialogInterface dialog) {
// dialog.dismiss();
// listener.onDecline(this);
// }
//
// }
| import ru.redsolution.bst.R;
import ru.redsolution.dialogs.AcceptAndDeclineDialogListener;
import ru.redsolution.dialogs.ConfirmDialogBuilder;
import android.app.Activity;
import android.view.View;
import android.widget.EditText; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.ui.dialog;
/**
* Диалог ввода значения.
*
* @author alexander.ivanov
*
*/
public class ValueDialogBuilder extends ConfirmDialogBuilder {
private final EditText valueView;
public ValueDialogBuilder(Activity activity, int dialogId, | // Path: bst/src/main/java/ru/redsolution/dialogs/AcceptAndDeclineDialogListener.java
// public interface AcceptAndDeclineDialogListener extends AcceptDialogListener {
//
// /**
// * Request was declined. "No" button was pushed.
// */
// void onDecline(DialogBuilder dialogBuilder);
// }
//
// Path: bst/src/main/java/ru/redsolution/dialogs/ConfirmDialogBuilder.java
// public class ConfirmDialogBuilder extends DialogBuilder implements
// DialogInterface.OnClickListener, OnCancelListener {
// private final AcceptAndDeclineDialogListener listener;
//
// /**
// * Yes / No dialog builder.
// *
// * @param activity
// * Parent activity.
// * @param dialogId
// * Dialog ID to be removed.
// * @param listener
// * Action listener.
// */
// public ConfirmDialogBuilder(Activity activity, int dialogId,
// AcceptAndDeclineDialogListener listener) {
// super(activity, dialogId);
// this.listener = listener;
// setPositiveButton(activity.getString(android.R.string.yes), this);
// setNegativeButton(activity.getString(android.R.string.no), this);
// setOnCancelListener(this);
// }
//
// @Override
// public void onClick(DialogInterface dialog, int id) {
// switch (id) {
// case DialogInterface.BUTTON_POSITIVE:
// dialog.dismiss();
// listener.onAccept(this);
// break;
// case DialogInterface.BUTTON_NEGATIVE:
// dialog.dismiss();
// listener.onDecline(this);
// break;
// }
// }
//
// @Override
// public void onCancel(DialogInterface dialog) {
// dialog.dismiss();
// listener.onDecline(this);
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/ui/dialog/ValueDialogBuilder.java
import ru.redsolution.bst.R;
import ru.redsolution.dialogs.AcceptAndDeclineDialogListener;
import ru.redsolution.dialogs.ConfirmDialogBuilder;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.ui.dialog;
/**
* Диалог ввода значения.
*
* @author alexander.ivanov
*
*/
public class ValueDialogBuilder extends ConfirmDialogBuilder {
private final EditText valueView;
public ValueDialogBuilder(Activity activity, int dialogId, | final AcceptAndDeclineDialogListener listener) { |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/ui/AboutActivity.java | // Path: bst/src/main/java/ru/redsolution/bst/data/Debugger.java
// public class Debugger {
//
// public static final boolean ENABLED;
//
// private static Method _getApplicationInfo = null;
//
// static {
// initCompatibility();
// ENABLED = (getApplicationInfo(BST.getInstance()).flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
// };
//
// private static void initCompatibility() {
// try {
// _getApplicationInfo = Context.class.getMethod("getApplicationInfo",
// new Class[] {});
// } catch (NoSuchMethodException nsme) {
// }
// }
//
// private static ApplicationInfo getApplicationInfo(Context context) {
// ApplicationInfo applicationInfo;
// if (_getApplicationInfo != null) {
// try {
// applicationInfo = (ApplicationInfo) _getApplicationInfo
// .invoke(context);
// } catch (InvocationTargetException e) {
// Throwable cause = e.getCause();
// if (cause instanceof RuntimeException) {
// throw (RuntimeException) cause;
// } else if (cause instanceof Error) {
// throw (Error) cause;
// } else {
// throw new RuntimeException(e);
// }
// } catch (IllegalAccessException ie) {
// throw new RuntimeException(ie);
// }
// } else {
// try {
// applicationInfo = context.getPackageManager()
// .getApplicationInfo(context.getPackageName(), 0);
// } catch (NameNotFoundException e) {
// applicationInfo = new ApplicationInfo();
// applicationInfo.flags = 0; // Disabled
// }
// }
// return applicationInfo;
// }
//
// private Debugger() {
// }
//
// }
| import ru.redsolution.bst.R;
import ru.redsolution.bst.data.Debugger;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.ui;
/**
* О программе.
*
* @author alexander.ivanov
*
*/
public class AboutActivity extends Activity implements OnClickListener {
private static final long HIDER_DELAY = 3000;
public static final String ACTION_WELLCOME_SCREEN = "WELLCOME_SCREEN";
private static final String REDSOLUTION_URL = "http://www.redsolution.ru/nashi-proekty/moj-sklad";
private final Runnable hider = new Runnable() {
@Override
public void run() {
finish();
}
};
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
handler = new Handler();
findViewById(R.id.root).setOnClickListener(this);
findViewById(R.id.redsolution).setOnClickListener(this);
findViewById(R.id.debug_enabled).setVisibility( | // Path: bst/src/main/java/ru/redsolution/bst/data/Debugger.java
// public class Debugger {
//
// public static final boolean ENABLED;
//
// private static Method _getApplicationInfo = null;
//
// static {
// initCompatibility();
// ENABLED = (getApplicationInfo(BST.getInstance()).flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
// };
//
// private static void initCompatibility() {
// try {
// _getApplicationInfo = Context.class.getMethod("getApplicationInfo",
// new Class[] {});
// } catch (NoSuchMethodException nsme) {
// }
// }
//
// private static ApplicationInfo getApplicationInfo(Context context) {
// ApplicationInfo applicationInfo;
// if (_getApplicationInfo != null) {
// try {
// applicationInfo = (ApplicationInfo) _getApplicationInfo
// .invoke(context);
// } catch (InvocationTargetException e) {
// Throwable cause = e.getCause();
// if (cause instanceof RuntimeException) {
// throw (RuntimeException) cause;
// } else if (cause instanceof Error) {
// throw (Error) cause;
// } else {
// throw new RuntimeException(e);
// }
// } catch (IllegalAccessException ie) {
// throw new RuntimeException(ie);
// }
// } else {
// try {
// applicationInfo = context.getPackageManager()
// .getApplicationInfo(context.getPackageName(), 0);
// } catch (NameNotFoundException e) {
// applicationInfo = new ApplicationInfo();
// applicationInfo.flags = 0; // Disabled
// }
// }
// return applicationInfo;
// }
//
// private Debugger() {
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/ui/AboutActivity.java
import ru.redsolution.bst.R;
import ru.redsolution.bst.data.Debugger;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.ui;
/**
* О программе.
*
* @author alexander.ivanov
*
*/
public class AboutActivity extends Activity implements OnClickListener {
private static final long HIDER_DELAY = 3000;
public static final String ACTION_WELLCOME_SCREEN = "WELLCOME_SCREEN";
private static final String REDSOLUTION_URL = "http://www.redsolution.ru/nashi-proekty/moj-sklad";
private final Runnable hider = new Runnable() {
@Override
public void run() {
finish();
}
};
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
handler = new Handler();
findViewById(R.id.root).setOnClickListener(this);
findViewById(R.id.redsolution).setOnClickListener(this);
findViewById(R.id.debug_enabled).setVisibility( | Debugger.ENABLED ? View.VISIBLE : View.GONE); |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/data/parse/MyCompanyImporter.java | // Path: bst/src/main/java/ru/redsolution/bst/data/table/MyCompanyTable.java
// public class MyCompanyTable extends ParentableTable {
//
// private static final String NAME = "my_company";
//
// private final static MyCompanyTable instance;
//
// static {
// instance = new MyCompanyTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static MyCompanyTable getInstance() {
// return instance;
// }
//
// private MyCompanyTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// }
| import ru.redsolution.bst.data.table.MyCompanyTable; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class MyCompanyImporter extends ParentableImporter {
@Override
protected void save() { | // Path: bst/src/main/java/ru/redsolution/bst/data/table/MyCompanyTable.java
// public class MyCompanyTable extends ParentableTable {
//
// private static final String NAME = "my_company";
//
// private final static MyCompanyTable instance;
//
// static {
// instance = new MyCompanyTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static MyCompanyTable getInstance() {
// return instance;
// }
//
// private MyCompanyTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/data/parse/MyCompanyImporter.java
import ru.redsolution.bst.data.table.MyCompanyTable;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class MyCompanyImporter extends ParentableImporter {
@Override
protected void save() { | MyCompanyTable.getInstance().add(id, name, parent); |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/data/parse/BaseImporter.java | // Path: bst/src/main/java/ru/redsolution/bst/data/table/DatabaseHelper.java
// public class DatabaseHelper extends SQLiteOpenHelper {
//
// private static final String DATABASE_NAME = "sqlite-q.db";
// private static final int DATABASE_VERSION = 7;
//
// private static final DatabaseHelper instance;
//
// static {
// instance = new DatabaseHelper(BST.getInstance());
// }
//
// public static DatabaseHelper getInstance() {
// return instance;
// }
//
// private final ArrayList<DatabaseTable> tables;
//
// private DatabaseHelper(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// tables = new ArrayList<DatabaseTable>();
// }
//
// public void addTable(DatabaseTable table) {
// tables.add(table);
// }
//
// @Override
// public void onCreate(SQLiteDatabase paramSQLiteDatabase) {
// for (DatabaseTable table : tables)
// table.create(paramSQLiteDatabase);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if (oldVersion > newVersion) {
// throw new IllegalStateException();
// } else {
// while (oldVersion < newVersion) {
// oldVersion += 1;
// for (DatabaseTable table : tables)
// table.migrate(db, oldVersion);
// }
// }
// }
//
// /**
// * Удалить все данные.
// */
// public void clear() {
// for (DatabaseTable table : tables)
// table.clear();
// }
//
// public static void execSQL(SQLiteDatabase db, String sql) {
// if (Debugger.ENABLED)
// Log.i("SQL", sql);
// db.execSQL(sql);
// }
//
// }
| import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import ru.redsolution.bst.data.table.DatabaseHelper;
import android.database.sqlite.SQLiteDatabase; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
/**
* Реализует базовый парсинг данных.
*
* @author alexander.ivanov
*
*/
public abstract class BaseImporter implements Importer {
/**
* Парсинг вложенного элемента.
*
* @param parser
* @return Истину, если элемент был обработан.
* @throws XmlPullParserException
* @throws IOException
*/
protected boolean parseInnerElement(XmlPullParser parser)
throws XmlPullParserException, IOException {
return false;
}
/**
* Подготовка к парсингу вложенных элементов.
*
* @param parser
*/
protected void preProcess(XmlPullParser parser) {
}
/**
* Разбор вложенных тегов.
*
* @param parser
* @throws XmlPullParserException
* @throws IOException
*/
protected void parseInner(XmlPullParser parser)
throws XmlPullParserException, IOException {
int inner = 1;
while (inner > 0) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
if (inner == 1)
if (parseInnerElement(parser))
continue;
inner += 1;
} else if (eventType == XmlPullParser.END_TAG) {
inner -= 1;
} else if (eventType == XmlPullParser.END_DOCUMENT)
break;
}
}
@Override
public void parse(XmlPullParser parser) throws XmlPullParserException,
IOException { | // Path: bst/src/main/java/ru/redsolution/bst/data/table/DatabaseHelper.java
// public class DatabaseHelper extends SQLiteOpenHelper {
//
// private static final String DATABASE_NAME = "sqlite-q.db";
// private static final int DATABASE_VERSION = 7;
//
// private static final DatabaseHelper instance;
//
// static {
// instance = new DatabaseHelper(BST.getInstance());
// }
//
// public static DatabaseHelper getInstance() {
// return instance;
// }
//
// private final ArrayList<DatabaseTable> tables;
//
// private DatabaseHelper(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// tables = new ArrayList<DatabaseTable>();
// }
//
// public void addTable(DatabaseTable table) {
// tables.add(table);
// }
//
// @Override
// public void onCreate(SQLiteDatabase paramSQLiteDatabase) {
// for (DatabaseTable table : tables)
// table.create(paramSQLiteDatabase);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if (oldVersion > newVersion) {
// throw new IllegalStateException();
// } else {
// while (oldVersion < newVersion) {
// oldVersion += 1;
// for (DatabaseTable table : tables)
// table.migrate(db, oldVersion);
// }
// }
// }
//
// /**
// * Удалить все данные.
// */
// public void clear() {
// for (DatabaseTable table : tables)
// table.clear();
// }
//
// public static void execSQL(SQLiteDatabase db, String sql) {
// if (Debugger.ENABLED)
// Log.i("SQL", sql);
// db.execSQL(sql);
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/data/parse/BaseImporter.java
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import ru.redsolution.bst.data.table.DatabaseHelper;
import android.database.sqlite.SQLiteDatabase;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
/**
* Реализует базовый парсинг данных.
*
* @author alexander.ivanov
*
*/
public abstract class BaseImporter implements Importer {
/**
* Парсинг вложенного элемента.
*
* @param parser
* @return Истину, если элемент был обработан.
* @throws XmlPullParserException
* @throws IOException
*/
protected boolean parseInnerElement(XmlPullParser parser)
throws XmlPullParserException, IOException {
return false;
}
/**
* Подготовка к парсингу вложенных элементов.
*
* @param parser
*/
protected void preProcess(XmlPullParser parser) {
}
/**
* Разбор вложенных тегов.
*
* @param parser
* @throws XmlPullParserException
* @throws IOException
*/
protected void parseInner(XmlPullParser parser)
throws XmlPullParserException, IOException {
int inner = 1;
while (inner > 0) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
if (inner == 1)
if (parseInnerElement(parser))
continue;
inner += 1;
} else if (eventType == XmlPullParser.END_TAG) {
inner -= 1;
} else if (eventType == XmlPullParser.END_DOCUMENT)
break;
}
}
@Override
public void parse(XmlPullParser parser) throws XmlPullParserException,
IOException { | SQLiteDatabase db = DatabaseHelper.getInstance().getWritableDatabase(); |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/data/parse/WarehouseImporter.java | // Path: bst/src/main/java/ru/redsolution/bst/data/table/WarehouseTable.java
// public class WarehouseTable extends ParentableTable {
//
// private static final String NAME = "warehouse";
//
// private final static WarehouseTable instance;
//
// static {
// instance = new WarehouseTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static WarehouseTable getInstance() {
// return instance;
// }
//
// private WarehouseTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// }
| import ru.redsolution.bst.data.table.WarehouseTable; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class WarehouseImporter extends ParentableImporter {
@Override
protected void save() { | // Path: bst/src/main/java/ru/redsolution/bst/data/table/WarehouseTable.java
// public class WarehouseTable extends ParentableTable {
//
// private static final String NAME = "warehouse";
//
// private final static WarehouseTable instance;
//
// static {
// instance = new WarehouseTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static WarehouseTable getInstance() {
// return instance;
// }
//
// private WarehouseTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/data/parse/WarehouseImporter.java
import ru.redsolution.bst.data.table.WarehouseTable;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class WarehouseImporter extends ParentableImporter {
@Override
protected void save() { | WarehouseTable.getInstance().add(id, name, parent); |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/data/parse/GoodImporter.java | // Path: bst/src/main/java/ru/redsolution/bst/data/table/GoodTable.java
// public class GoodTable extends BaseGoodTable {
//
// private static final String NAME = "good";
//
// private final static GoodTable instance;
//
// static {
// instance = new GoodTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static GoodTable getInstance() {
// return instance;
// }
//
// private GoodTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// /**
// * @param productCode
// * @return Товар.
// * @throws ObjectDoesNotExistException
// * @throws MultipleObjectsReturnedException
// */
// public ContentValues getByProductCode(String productCode)
// throws ObjectDoesNotExistException,
// MultipleObjectsReturnedException {
// return get(Fields.PRODUCT_CODE + " = ?", new String[] { productCode });
// }
//
// /**
// * Добавить объект.
// *
// * @param id
// * @param name
// * @param buyPrice
// * @param salePrice
// * @param uom
// * @param folder
// * @param productCode
// * @param code
// */
// public void add(String id, String name, String buyPrice, String uom,
// String folder, String productCode, String code) {
// ContentValues values = getValues(id, name);
// values.put(Fields.BUY_PRICE, buyPrice);
// values.put(Fields.UOM, uom);
// values.put(Fields.GOOD_FOLDER, folder);
// values.put(Fields.PRODUCT_CODE, productCode);
// values.put(Fields.CODE, code);
// add(values);
// }
//
// /**
// * @param folder
// * @return Товары в указанной папке.
// */
// public Cursor list(String folder) {
// return filter(Fields.GOOD_FOLDER + " = ?", new String[] { folder },
// Fields.NAME);
// }
//
// @Override
// public void migrate(SQLiteDatabase db, int toVersion) {
// super.migrate(db, toVersion);
// String sql;
// switch (toVersion) {
// case 7:
// sql = "ALTER TABLE good RENAME TO good_;";
// DatabaseHelper.execSQL(db, sql);
// sql = "CREATE TABLE good (" + "_id TEXT,"
// + "name TEXT COLLATE UNICODE, " + "buy_price TEXT,"
// + "uom TEXT," + "good_folder TEXT," + "product_code TEXT,"
// + "code TEXT," + "lower_cased_name TEXT);";
// DatabaseHelper.execSQL(db, sql);
// sql = "INSERT INTO good ("
// + "_id, name, buy_price, uom, good_folder, "
// + "product_code, code, lower_cased_name) "
// + "SELECT _id, name, buy_price, uom, good_folder, "
// + "product_code, code, lower_cased_name FROM good_;";
// DatabaseHelper.execSQL(db, sql);
// sql = "DROP TABLE good_;";
// DatabaseHelper.execSQL(db, sql);
// break;
// default:
// break;
// }
// }
//
// }
| import java.io.IOException;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import ru.redsolution.bst.data.table.GoodTable; | if (super.parseInnerElement(parser))
return true;
if (parser.getName().equals("code")) {
code = parseText(parser);
return true;
}
if (parser.getName().equals("salePrices")) {
new PricesImporter(this).parse(parser);
return true;
}
return false;
}
@Override
public boolean isValid() {
if (buyPrice == null)
buyPrice = "";
if (uom == null)
uom = "";
if (folder == null)
folder = "";
if (productCode == null)
productCode = "";
if (code == null)
code = "";
return super.isValid();
}
@Override
protected void saveInsatce() { | // Path: bst/src/main/java/ru/redsolution/bst/data/table/GoodTable.java
// public class GoodTable extends BaseGoodTable {
//
// private static final String NAME = "good";
//
// private final static GoodTable instance;
//
// static {
// instance = new GoodTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static GoodTable getInstance() {
// return instance;
// }
//
// private GoodTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// /**
// * @param productCode
// * @return Товар.
// * @throws ObjectDoesNotExistException
// * @throws MultipleObjectsReturnedException
// */
// public ContentValues getByProductCode(String productCode)
// throws ObjectDoesNotExistException,
// MultipleObjectsReturnedException {
// return get(Fields.PRODUCT_CODE + " = ?", new String[] { productCode });
// }
//
// /**
// * Добавить объект.
// *
// * @param id
// * @param name
// * @param buyPrice
// * @param salePrice
// * @param uom
// * @param folder
// * @param productCode
// * @param code
// */
// public void add(String id, String name, String buyPrice, String uom,
// String folder, String productCode, String code) {
// ContentValues values = getValues(id, name);
// values.put(Fields.BUY_PRICE, buyPrice);
// values.put(Fields.UOM, uom);
// values.put(Fields.GOOD_FOLDER, folder);
// values.put(Fields.PRODUCT_CODE, productCode);
// values.put(Fields.CODE, code);
// add(values);
// }
//
// /**
// * @param folder
// * @return Товары в указанной папке.
// */
// public Cursor list(String folder) {
// return filter(Fields.GOOD_FOLDER + " = ?", new String[] { folder },
// Fields.NAME);
// }
//
// @Override
// public void migrate(SQLiteDatabase db, int toVersion) {
// super.migrate(db, toVersion);
// String sql;
// switch (toVersion) {
// case 7:
// sql = "ALTER TABLE good RENAME TO good_;";
// DatabaseHelper.execSQL(db, sql);
// sql = "CREATE TABLE good (" + "_id TEXT,"
// + "name TEXT COLLATE UNICODE, " + "buy_price TEXT,"
// + "uom TEXT," + "good_folder TEXT," + "product_code TEXT,"
// + "code TEXT," + "lower_cased_name TEXT);";
// DatabaseHelper.execSQL(db, sql);
// sql = "INSERT INTO good ("
// + "_id, name, buy_price, uom, good_folder, "
// + "product_code, code, lower_cased_name) "
// + "SELECT _id, name, buy_price, uom, good_folder, "
// + "product_code, code, lower_cased_name FROM good_;";
// DatabaseHelper.execSQL(db, sql);
// sql = "DROP TABLE good_;";
// DatabaseHelper.execSQL(db, sql);
// break;
// default:
// break;
// }
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/data/parse/GoodImporter.java
import java.io.IOException;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import ru.redsolution.bst.data.table.GoodTable;
if (super.parseInnerElement(parser))
return true;
if (parser.getName().equals("code")) {
code = parseText(parser);
return true;
}
if (parser.getName().equals("salePrices")) {
new PricesImporter(this).parse(parser);
return true;
}
return false;
}
@Override
public boolean isValid() {
if (buyPrice == null)
buyPrice = "";
if (uom == null)
uom = "";
if (folder == null)
folder = "";
if (productCode == null)
productCode = "";
if (code == null)
code = "";
return super.isValid();
}
@Override
protected void saveInsatce() { | GoodTable.getInstance().add(id, name, buyPrice, uom, folder, |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/data/parse/PriceImporter.java | // Path: bst/src/main/java/ru/redsolution/bst/data/table/PriceTable.java
// public class PriceTable extends BaseTable {
// public static interface Fields extends BaseTable.Fields {
// public static final String PRICE_TYPE = "price_type";
// public static final String VALUE = "value";
// }
//
// private static final String NAME = "price";
//
// private final static PriceTable instance;
//
// static {
// instance = new PriceTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static PriceTable getInstance() {
// return instance;
// }
//
// private PriceTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// @Override
// protected Collection<String> getFields() {
// Collection<String> collection = new ArrayList<String>(super.getFields());
// collection.add(Fields.PRICE_TYPE);
// collection.add(Fields.VALUE);
// return collection;
// }
//
// @Override
// public ContentValues getById(String id) throws ObjectDoesNotExistException,
// MultipleObjectsReturnedException {
// throw new UnsupportedOperationException();
// }
//
// /**
// * @param good
// * @param priceType
// * @return Цену товара или пустую стоку, если цена не известна.
// */
// public String getPrice(String good, String priceType) {
// ContentValues values;
// try {
// values = get(Fields._ID + " = ? AND " + Fields.PRICE_TYPE + " = ?",
// new String[] { good, priceType });
// } catch (BaseDatabaseException e) {
// return "";
// }
// return values.getAsString(Fields.VALUE);
// }
//
// public void add(String good, String priceType, String value) {
// ContentValues values = new ContentValues();
// values.put(Fields._ID, good);
// values.put(Fields.PRICE_TYPE, priceType);
// values.put(Fields.VALUE, value);
// add(values);
// }
//
// @Override
// public void migrate(SQLiteDatabase db, int toVersion) {
// super.migrate(db, toVersion);
// String sql;
// switch (toVersion) {
// case 6:
// sql = "CREATE TABLE price (" + "_id TEXT," + "price_type TEXT,"
// + "value TEXT);";
// DatabaseHelper.execSQL(db, sql);
// sql = "INSERT INTO price_type (_id, name) VALUES ('sale', 'sale');";
// DatabaseHelper.execSQL(db, sql);
// sql = "INSERT INTO price (_id, price_type, value) "
// + "SELECT _id, 'sale', sale_price FROM good;";
// DatabaseHelper.execSQL(db, sql);
// break;
// default:
// break;
// }
// }
//
// }
| import org.xmlpull.v1.XmlPullParser;
import ru.redsolution.bst.data.table.PriceTable;
import android.util.Log; | value = parser.getAttributeValue(null, "value");
}
@Override
protected void postProcess() {
super.postProcess();
if (isValid())
importer.addPrice(this);
}
@Override
public boolean isValid() {
if (priceType == null) {
Log.w(this.getClass().toString(), "price type is null");
return false;
}
if (value == null) {
Log.w(this.getClass().toString(), "value is null");
return false;
}
return true;
}
/**
* Сохраняет полученную цену.
*
* @param id
* Идентификатор родительского объекта в базе данных.
*/
protected void save(String id) { | // Path: bst/src/main/java/ru/redsolution/bst/data/table/PriceTable.java
// public class PriceTable extends BaseTable {
// public static interface Fields extends BaseTable.Fields {
// public static final String PRICE_TYPE = "price_type";
// public static final String VALUE = "value";
// }
//
// private static final String NAME = "price";
//
// private final static PriceTable instance;
//
// static {
// instance = new PriceTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static PriceTable getInstance() {
// return instance;
// }
//
// private PriceTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// @Override
// protected Collection<String> getFields() {
// Collection<String> collection = new ArrayList<String>(super.getFields());
// collection.add(Fields.PRICE_TYPE);
// collection.add(Fields.VALUE);
// return collection;
// }
//
// @Override
// public ContentValues getById(String id) throws ObjectDoesNotExistException,
// MultipleObjectsReturnedException {
// throw new UnsupportedOperationException();
// }
//
// /**
// * @param good
// * @param priceType
// * @return Цену товара или пустую стоку, если цена не известна.
// */
// public String getPrice(String good, String priceType) {
// ContentValues values;
// try {
// values = get(Fields._ID + " = ? AND " + Fields.PRICE_TYPE + " = ?",
// new String[] { good, priceType });
// } catch (BaseDatabaseException e) {
// return "";
// }
// return values.getAsString(Fields.VALUE);
// }
//
// public void add(String good, String priceType, String value) {
// ContentValues values = new ContentValues();
// values.put(Fields._ID, good);
// values.put(Fields.PRICE_TYPE, priceType);
// values.put(Fields.VALUE, value);
// add(values);
// }
//
// @Override
// public void migrate(SQLiteDatabase db, int toVersion) {
// super.migrate(db, toVersion);
// String sql;
// switch (toVersion) {
// case 6:
// sql = "CREATE TABLE price (" + "_id TEXT," + "price_type TEXT,"
// + "value TEXT);";
// DatabaseHelper.execSQL(db, sql);
// sql = "INSERT INTO price_type (_id, name) VALUES ('sale', 'sale');";
// DatabaseHelper.execSQL(db, sql);
// sql = "INSERT INTO price (_id, price_type, value) "
// + "SELECT _id, 'sale', sale_price FROM good;";
// DatabaseHelper.execSQL(db, sql);
// break;
// default:
// break;
// }
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/data/parse/PriceImporter.java
import org.xmlpull.v1.XmlPullParser;
import ru.redsolution.bst.data.table.PriceTable;
import android.util.Log;
value = parser.getAttributeValue(null, "value");
}
@Override
protected void postProcess() {
super.postProcess();
if (isValid())
importer.addPrice(this);
}
@Override
public boolean isValid() {
if (priceType == null) {
Log.w(this.getClass().toString(), "price type is null");
return false;
}
if (value == null) {
Log.w(this.getClass().toString(), "value is null");
return false;
}
return true;
}
/**
* Сохраняет полученную цену.
*
* @param id
* Идентификатор родительского объекта в базе данных.
*/
protected void save(String id) { | PriceTable.getInstance().add(id, priceType, value); |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/data/parse/ProjectImporter.java | // Path: bst/src/main/java/ru/redsolution/bst/data/table/ProjectTable.java
// public class ProjectTable extends NamedTable {
//
// private static final String NAME = "project";
//
// private final static ProjectTable instance;
//
// static {
// instance = new ProjectTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static ProjectTable getInstance() {
// return instance;
// }
//
// private ProjectTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// }
| import ru.redsolution.bst.data.table.ProjectTable; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class ProjectImporter extends NamedImporter {
@Override
protected void save() { | // Path: bst/src/main/java/ru/redsolution/bst/data/table/ProjectTable.java
// public class ProjectTable extends NamedTable {
//
// private static final String NAME = "project";
//
// private final static ProjectTable instance;
//
// static {
// instance = new ProjectTable();
// DatabaseHelper.getInstance().addTable(instance);
// }
//
// public static ProjectTable getInstance() {
// return instance;
// }
//
// private ProjectTable() {
// }
//
// @Override
// public String getTableName() {
// return NAME;
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/data/parse/ProjectImporter.java
import ru.redsolution.bst.data.table.ProjectTable;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.data.parse;
public class ProjectImporter extends NamedImporter {
@Override
protected void save() { | ProjectTable.getInstance().add(id, name); |
redsolution/bst | bst/src/main/java/ru/redsolution/bst/ui/dialog/ActionChoiceDialogBuilder.java | // Path: bst/src/main/java/ru/redsolution/dialogs/AcceptAndDeclineDialogListener.java
// public interface AcceptAndDeclineDialogListener extends AcceptDialogListener {
//
// /**
// * Request was declined. "No" button was pushed.
// */
// void onDecline(DialogBuilder dialogBuilder);
// }
//
// Path: bst/src/main/java/ru/redsolution/dialogs/SingleChoiceDialogBuilder.java
// public class SingleChoiceDialogBuilder<T> extends DialogBuilder implements
// DialogInterface.OnClickListener, OnCancelListener {
// private final AcceptAndDeclineDialogListener listener;
// private final List<T> items;
// private T checkedItem;
//
// public SingleChoiceDialogBuilder(Activity activity, int dialogId,
// AcceptAndDeclineDialogListener listener, List<T> items,
// List<String> labels, T checkedItem) {
// super(activity, dialogId);
// this.listener = listener;
// this.items = items;
// int index = items.indexOf(checkedItem);
// setCheckedItem(index);
// String[] array = labels.toArray(new String[labels.size()]);
// setSingleChoiceItems(array, index, this);
// setOnCancelListener(this);
// }
//
// private void setCheckedItem(int index) {
// if (index == -1)
// checkedItem = null;
// else
// checkedItem = items.get(index);
// }
//
// @Override
// public void onClick(DialogInterface dialog, int id) {
// setCheckedItem(id);
// dialog.dismiss();
// listener.onAccept(this);
// }
//
// /**
// * Returns selected item.
// *
// * @return <code>null</code> if there is no selected item.
// */
// public T getCheckedItem() {
// return checkedItem;
// }
//
// @Override
// public void onCancel(DialogInterface dialog) {
// dialog.dismiss();
// listener.onDecline(this);
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import ru.redsolution.dialogs.AcceptAndDeclineDialogListener;
import ru.redsolution.dialogs.SingleChoiceDialogBuilder;
import android.app.Activity;
import android.content.Context; | /**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.ui.dialog;
/**
* Диалог выбора операции.
*
* @author alexander.ivanov
*
*/
public class ActionChoiceDialogBuilder extends
SingleChoiceDialogBuilder<Integer> {
public ActionChoiceDialogBuilder(Activity activity, int dialogId, | // Path: bst/src/main/java/ru/redsolution/dialogs/AcceptAndDeclineDialogListener.java
// public interface AcceptAndDeclineDialogListener extends AcceptDialogListener {
//
// /**
// * Request was declined. "No" button was pushed.
// */
// void onDecline(DialogBuilder dialogBuilder);
// }
//
// Path: bst/src/main/java/ru/redsolution/dialogs/SingleChoiceDialogBuilder.java
// public class SingleChoiceDialogBuilder<T> extends DialogBuilder implements
// DialogInterface.OnClickListener, OnCancelListener {
// private final AcceptAndDeclineDialogListener listener;
// private final List<T> items;
// private T checkedItem;
//
// public SingleChoiceDialogBuilder(Activity activity, int dialogId,
// AcceptAndDeclineDialogListener listener, List<T> items,
// List<String> labels, T checkedItem) {
// super(activity, dialogId);
// this.listener = listener;
// this.items = items;
// int index = items.indexOf(checkedItem);
// setCheckedItem(index);
// String[] array = labels.toArray(new String[labels.size()]);
// setSingleChoiceItems(array, index, this);
// setOnCancelListener(this);
// }
//
// private void setCheckedItem(int index) {
// if (index == -1)
// checkedItem = null;
// else
// checkedItem = items.get(index);
// }
//
// @Override
// public void onClick(DialogInterface dialog, int id) {
// setCheckedItem(id);
// dialog.dismiss();
// listener.onAccept(this);
// }
//
// /**
// * Returns selected item.
// *
// * @return <code>null</code> if there is no selected item.
// */
// public T getCheckedItem() {
// return checkedItem;
// }
//
// @Override
// public void onCancel(DialogInterface dialog) {
// dialog.dismiss();
// listener.onDecline(this);
// }
//
// }
// Path: bst/src/main/java/ru/redsolution/bst/ui/dialog/ActionChoiceDialogBuilder.java
import java.util.ArrayList;
import java.util.List;
import ru.redsolution.dialogs.AcceptAndDeclineDialogListener;
import ru.redsolution.dialogs.SingleChoiceDialogBuilder;
import android.app.Activity;
import android.content.Context;
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Barcode Scanner Terminal project;
* you can redistribute it and/or modify it under the terms of
*
* Barcode Scanner Terminal 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package ru.redsolution.bst.ui.dialog;
/**
* Диалог выбора операции.
*
* @author alexander.ivanov
*
*/
public class ActionChoiceDialogBuilder extends
SingleChoiceDialogBuilder<Integer> {
public ActionChoiceDialogBuilder(Activity activity, int dialogId, | AcceptAndDeclineDialogListener listener, int[] resourceIds, |
gustavkarlsson/rocketchat-jira-trigger | src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/JiraConfigurationTest.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/JiraConfiguration.java
// @Singleton
// public class JiraConfiguration {
// private static final String KEY_PREFIX = "jira.";
// static final String URI_KEY = KEY_PREFIX + "uri";
// static final String USER_KEY = KEY_PREFIX + "username";
// static final String PASSWORD_KEY = KEY_PREFIX + "password";
//
// private final URI uri;
// private final String username;
// private final String password;
//
// @Inject
// JiraConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// uri = URI.create(notNull(configMap.getString(URI_KEY), String.format("%s must be provided", URI_KEY)));
// username = configMap.getString(USER_KEY);
// password = configMap.getString(PASSWORD_KEY);
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public URI getUri() {
// return uri;
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getPassword() {
// return password;
// }
// }
| import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static se.gustavkarlsson.rocketchat.jira_trigger.configuration.JiraConfiguration.*; | package se.gustavkarlsson.rocketchat.jira_trigger.configuration;
@RunWith(MockitoJUnitRunner.class)
public class JiraConfigurationTest {
private static final String URI = "https://restapp.com/api";
private static final String USERNAME = "johndoe";
private static final String PASSWORD = "monkey";
@Mock
private ConfigMap mockConfigMap;
| // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/JiraConfiguration.java
// @Singleton
// public class JiraConfiguration {
// private static final String KEY_PREFIX = "jira.";
// static final String URI_KEY = KEY_PREFIX + "uri";
// static final String USER_KEY = KEY_PREFIX + "username";
// static final String PASSWORD_KEY = KEY_PREFIX + "password";
//
// private final URI uri;
// private final String username;
// private final String password;
//
// @Inject
// JiraConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// uri = URI.create(notNull(configMap.getString(URI_KEY), String.format("%s must be provided", URI_KEY)));
// username = configMap.getString(USER_KEY);
// password = configMap.getString(PASSWORD_KEY);
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public URI getUri() {
// return uri;
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getPassword() {
// return password;
// }
// }
// Path: src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/JiraConfigurationTest.java
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static se.gustavkarlsson.rocketchat.jira_trigger.configuration.JiraConfiguration.*;
package se.gustavkarlsson.rocketchat.jira_trigger.configuration;
@RunWith(MockitoJUnitRunner.class)
public class JiraConfigurationTest {
private static final String URI = "https://restapp.com/api";
private static final String USERNAME = "johndoe";
private static final String PASSWORD = "monkey";
@Mock
private ConfigMap mockConfigMap;
| private JiraConfiguration jiraConfig; |
gustavkarlsson/rocketchat-jira-trigger | src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/FieldCreatorMapperTest.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/FieldCreator.java
// public interface FieldCreator {
// Field create(Issue issue);
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/StatusFieldCreator.java
// public class StatusFieldCreator extends AbstractFieldCreator {
// @Override
// protected String getTitle() {
// return "Status";
// }
//
// @Override
// protected String getValue(Issue issue) {
// Status status = issue.getStatus();
// return status == null ? "-" : status.getName();
// }
//
// @Override
// protected boolean isShortValue() {
// return true;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/FieldCreatorMapper.java
// static final String STATUS_KEY = "status";
| import org.joda.time.format.DateTimeFormat;
import org.junit.Test;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.FieldCreator;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.StatusFieldCreator;
import java.util.List;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static se.gustavkarlsson.rocketchat.jira_trigger.messages.FieldCreatorMapper.STATUS_KEY; | package se.gustavkarlsson.rocketchat.jira_trigger.messages;
public class FieldCreatorMapperTest {
@Test(expected = NullPointerException.class)
public void createWithNullDateTimeFormatterThrowsNpe() throws Exception {
new FieldCreatorMapper(false, null);
}
@Test
public void getSingleCreator() throws Exception {
FieldCreatorMapper mapper = new FieldCreatorMapper(false, DateTimeFormat.forPattern("yyyy"));
| // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/FieldCreator.java
// public interface FieldCreator {
// Field create(Issue issue);
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/StatusFieldCreator.java
// public class StatusFieldCreator extends AbstractFieldCreator {
// @Override
// protected String getTitle() {
// return "Status";
// }
//
// @Override
// protected String getValue(Issue issue) {
// Status status = issue.getStatus();
// return status == null ? "-" : status.getName();
// }
//
// @Override
// protected boolean isShortValue() {
// return true;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/FieldCreatorMapper.java
// static final String STATUS_KEY = "status";
// Path: src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/FieldCreatorMapperTest.java
import org.joda.time.format.DateTimeFormat;
import org.junit.Test;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.FieldCreator;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.StatusFieldCreator;
import java.util.List;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static se.gustavkarlsson.rocketchat.jira_trigger.messages.FieldCreatorMapper.STATUS_KEY;
package se.gustavkarlsson.rocketchat.jira_trigger.messages;
public class FieldCreatorMapperTest {
@Test(expected = NullPointerException.class)
public void createWithNullDateTimeFormatterThrowsNpe() throws Exception {
new FieldCreatorMapper(false, null);
}
@Test
public void getSingleCreator() throws Exception {
FieldCreatorMapper mapper = new FieldCreatorMapper(false, DateTimeFormat.forPattern("yyyy"));
| List<FieldCreator> creators = mapper.getCreators(singletonList(STATUS_KEY)); |
gustavkarlsson/rocketchat-jira-trigger | src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/FieldCreatorMapperTest.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/FieldCreator.java
// public interface FieldCreator {
// Field create(Issue issue);
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/StatusFieldCreator.java
// public class StatusFieldCreator extends AbstractFieldCreator {
// @Override
// protected String getTitle() {
// return "Status";
// }
//
// @Override
// protected String getValue(Issue issue) {
// Status status = issue.getStatus();
// return status == null ? "-" : status.getName();
// }
//
// @Override
// protected boolean isShortValue() {
// return true;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/FieldCreatorMapper.java
// static final String STATUS_KEY = "status";
| import org.joda.time.format.DateTimeFormat;
import org.junit.Test;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.FieldCreator;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.StatusFieldCreator;
import java.util.List;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static se.gustavkarlsson.rocketchat.jira_trigger.messages.FieldCreatorMapper.STATUS_KEY; | package se.gustavkarlsson.rocketchat.jira_trigger.messages;
public class FieldCreatorMapperTest {
@Test(expected = NullPointerException.class)
public void createWithNullDateTimeFormatterThrowsNpe() throws Exception {
new FieldCreatorMapper(false, null);
}
@Test
public void getSingleCreator() throws Exception {
FieldCreatorMapper mapper = new FieldCreatorMapper(false, DateTimeFormat.forPattern("yyyy"));
| // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/FieldCreator.java
// public interface FieldCreator {
// Field create(Issue issue);
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/StatusFieldCreator.java
// public class StatusFieldCreator extends AbstractFieldCreator {
// @Override
// protected String getTitle() {
// return "Status";
// }
//
// @Override
// protected String getValue(Issue issue) {
// Status status = issue.getStatus();
// return status == null ? "-" : status.getName();
// }
//
// @Override
// protected boolean isShortValue() {
// return true;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/FieldCreatorMapper.java
// static final String STATUS_KEY = "status";
// Path: src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/FieldCreatorMapperTest.java
import org.joda.time.format.DateTimeFormat;
import org.junit.Test;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.FieldCreator;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.StatusFieldCreator;
import java.util.List;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static se.gustavkarlsson.rocketchat.jira_trigger.messages.FieldCreatorMapper.STATUS_KEY;
package se.gustavkarlsson.rocketchat.jira_trigger.messages;
public class FieldCreatorMapperTest {
@Test(expected = NullPointerException.class)
public void createWithNullDateTimeFormatterThrowsNpe() throws Exception {
new FieldCreatorMapper(false, null);
}
@Test
public void getSingleCreator() throws Exception {
FieldCreatorMapper mapper = new FieldCreatorMapper(false, DateTimeFormat.forPattern("yyyy"));
| List<FieldCreator> creators = mapper.getCreators(singletonList(STATUS_KEY)); |
gustavkarlsson/rocketchat-jira-trigger | src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/FieldCreatorMapperTest.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/FieldCreator.java
// public interface FieldCreator {
// Field create(Issue issue);
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/StatusFieldCreator.java
// public class StatusFieldCreator extends AbstractFieldCreator {
// @Override
// protected String getTitle() {
// return "Status";
// }
//
// @Override
// protected String getValue(Issue issue) {
// Status status = issue.getStatus();
// return status == null ? "-" : status.getName();
// }
//
// @Override
// protected boolean isShortValue() {
// return true;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/FieldCreatorMapper.java
// static final String STATUS_KEY = "status";
| import org.joda.time.format.DateTimeFormat;
import org.junit.Test;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.FieldCreator;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.StatusFieldCreator;
import java.util.List;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static se.gustavkarlsson.rocketchat.jira_trigger.messages.FieldCreatorMapper.STATUS_KEY; | package se.gustavkarlsson.rocketchat.jira_trigger.messages;
public class FieldCreatorMapperTest {
@Test(expected = NullPointerException.class)
public void createWithNullDateTimeFormatterThrowsNpe() throws Exception {
new FieldCreatorMapper(false, null);
}
@Test
public void getSingleCreator() throws Exception {
FieldCreatorMapper mapper = new FieldCreatorMapper(false, DateTimeFormat.forPattern("yyyy"));
List<FieldCreator> creators = mapper.getCreators(singletonList(STATUS_KEY));
assertThat(creators).hasSize(1); | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/FieldCreator.java
// public interface FieldCreator {
// Field create(Issue issue);
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/StatusFieldCreator.java
// public class StatusFieldCreator extends AbstractFieldCreator {
// @Override
// protected String getTitle() {
// return "Status";
// }
//
// @Override
// protected String getValue(Issue issue) {
// Status status = issue.getStatus();
// return status == null ? "-" : status.getName();
// }
//
// @Override
// protected boolean isShortValue() {
// return true;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/FieldCreatorMapper.java
// static final String STATUS_KEY = "status";
// Path: src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/FieldCreatorMapperTest.java
import org.joda.time.format.DateTimeFormat;
import org.junit.Test;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.FieldCreator;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.StatusFieldCreator;
import java.util.List;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static se.gustavkarlsson.rocketchat.jira_trigger.messages.FieldCreatorMapper.STATUS_KEY;
package se.gustavkarlsson.rocketchat.jira_trigger.messages;
public class FieldCreatorMapperTest {
@Test(expected = NullPointerException.class)
public void createWithNullDateTimeFormatterThrowsNpe() throws Exception {
new FieldCreatorMapper(false, null);
}
@Test
public void getSingleCreator() throws Exception {
FieldCreatorMapper mapper = new FieldCreatorMapper(false, DateTimeFormat.forPattern("yyyy"));
List<FieldCreator> creators = mapper.getCreators(singletonList(STATUS_KEY));
assertThat(creators).hasSize(1); | assertThat(creators.get(0)).isExactlyInstanceOf(StatusFieldCreator.class); |
gustavkarlsson/rocketchat-jira-trigger | src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/AppConfigurationTest.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/server/Server.java
// public class Server {
// private static final Logger log = getLogger(Server.class);
//
// public static final long MAX_PORT_NUMBER = 65535;
// private static final String APPLICATION_JSON = "application/json";
//
// private final int maxThreads;
// private final String ipAddress;
// private final int port;
// private final DetectIssueRoute detectIssueRoute;
// private final JiraServerInfoLogger jiraServerInfoLogger;
//
// private Service service;
//
// Server(int maxThreads, String ipAddress, int port, DetectIssueRoute detectIssueRoute, JiraServerInfoLogger jiraServerInfoLogger) {
// this.maxThreads = maxThreads;
// inclusiveBetween(1, Integer.MAX_VALUE, maxThreads);
// this.ipAddress = notBlank(ipAddress);
// this.port = port;
// inclusiveBetween(1, MAX_PORT_NUMBER, port);
// this.detectIssueRoute = notNull(detectIssueRoute);
// this.jiraServerInfoLogger = notNull(jiraServerInfoLogger);
// }
//
// private static void logRequest(Request request) {
// log.info("Incoming request: {} {} {} {}",
// request.raw().getRemoteAddr(), request.requestMethod(), request.contentType(), request.pathInfo());
// }
//
// private static void logResponse(Response response) {
// String responseContent = response.body() == null ? "<empty>" : "Rocket.Chat message";
// log.info("Outgoing response: {}", responseContent);
// }
//
// public synchronized void start() {
// jiraServerInfoLogger.logInfo();
// log.info("Starting server...");
// if (service != null) {
// throw new IllegalStateException("Already started");
// }
// Service service = ignite();
// service.threadPool(maxThreads);
// service.port(port);
// service.ipAddress(ipAddress);
// service.before((request, response) -> logRequest(request));
// service.post("/", APPLICATION_JSON, detectIssueRoute);
// service.after((request, response) -> logResponse(response));
// service.exception(Exception.class, new UuidGeneratingExceptionHandler());
// this.service = service;
// }
//
// public synchronized void stop() {
// if (service == null) {
// throw new IllegalStateException("Already stopped");
// }
// service.stop();
// service = null;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/AppConfiguration.java
// @Singleton
// public class AppConfiguration {
// private static final String KEY_PREFIX = "app.";
// static final String IP_ADDRESS_KEY = KEY_PREFIX + "ip_address";
// static final String PORT_KEY = KEY_PREFIX + "port";
// static final String MAX_THREADS_KEY = KEY_PREFIX + "max_threads";
//
// private final String ipAddress;
// private final int port;
// private final int maxThreads;
//
// @Inject
// AppConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// ipAddress = notBlank(configMap.getString(IP_ADDRESS_KEY), String.format("Non-blank %s must be provided", IP_ADDRESS_KEY));
// port = notNull(configMap.getLong(PORT_KEY), String.format("%s must be provided", PORT_KEY)).intValue();
// inclusiveBetween(1, Server.MAX_PORT_NUMBER, port, String.format("%s must be within %d and %d. Was: %d", PORT_KEY, 1, Server.MAX_PORT_NUMBER, port));
// maxThreads = notNull(configMap.getLong(MAX_THREADS_KEY), String.format("%s must be provided", MAX_THREADS_KEY)).intValue();
// inclusiveBetween(1, Integer.MAX_VALUE, maxThreads, String.format("%s must be within %d and %d. Was: %d", MAX_THREADS_KEY, 1, Integer.MAX_VALUE, maxThreads));
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getMaxThreads() {
// return maxThreads;
// }
// }
| import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import se.gustavkarlsson.rocketchat.jira_trigger.server.Server;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static se.gustavkarlsson.rocketchat.jira_trigger.configuration.AppConfiguration.*; | package se.gustavkarlsson.rocketchat.jira_trigger.configuration;
@RunWith(MockitoJUnitRunner.class)
public class AppConfigurationTest {
private static final int PORT = 2000;
private static final int MAX_THREADS = 10;
@Mock
private ConfigMap mockConfigMap;
| // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/server/Server.java
// public class Server {
// private static final Logger log = getLogger(Server.class);
//
// public static final long MAX_PORT_NUMBER = 65535;
// private static final String APPLICATION_JSON = "application/json";
//
// private final int maxThreads;
// private final String ipAddress;
// private final int port;
// private final DetectIssueRoute detectIssueRoute;
// private final JiraServerInfoLogger jiraServerInfoLogger;
//
// private Service service;
//
// Server(int maxThreads, String ipAddress, int port, DetectIssueRoute detectIssueRoute, JiraServerInfoLogger jiraServerInfoLogger) {
// this.maxThreads = maxThreads;
// inclusiveBetween(1, Integer.MAX_VALUE, maxThreads);
// this.ipAddress = notBlank(ipAddress);
// this.port = port;
// inclusiveBetween(1, MAX_PORT_NUMBER, port);
// this.detectIssueRoute = notNull(detectIssueRoute);
// this.jiraServerInfoLogger = notNull(jiraServerInfoLogger);
// }
//
// private static void logRequest(Request request) {
// log.info("Incoming request: {} {} {} {}",
// request.raw().getRemoteAddr(), request.requestMethod(), request.contentType(), request.pathInfo());
// }
//
// private static void logResponse(Response response) {
// String responseContent = response.body() == null ? "<empty>" : "Rocket.Chat message";
// log.info("Outgoing response: {}", responseContent);
// }
//
// public synchronized void start() {
// jiraServerInfoLogger.logInfo();
// log.info("Starting server...");
// if (service != null) {
// throw new IllegalStateException("Already started");
// }
// Service service = ignite();
// service.threadPool(maxThreads);
// service.port(port);
// service.ipAddress(ipAddress);
// service.before((request, response) -> logRequest(request));
// service.post("/", APPLICATION_JSON, detectIssueRoute);
// service.after((request, response) -> logResponse(response));
// service.exception(Exception.class, new UuidGeneratingExceptionHandler());
// this.service = service;
// }
//
// public synchronized void stop() {
// if (service == null) {
// throw new IllegalStateException("Already stopped");
// }
// service.stop();
// service = null;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/AppConfiguration.java
// @Singleton
// public class AppConfiguration {
// private static final String KEY_PREFIX = "app.";
// static final String IP_ADDRESS_KEY = KEY_PREFIX + "ip_address";
// static final String PORT_KEY = KEY_PREFIX + "port";
// static final String MAX_THREADS_KEY = KEY_PREFIX + "max_threads";
//
// private final String ipAddress;
// private final int port;
// private final int maxThreads;
//
// @Inject
// AppConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// ipAddress = notBlank(configMap.getString(IP_ADDRESS_KEY), String.format("Non-blank %s must be provided", IP_ADDRESS_KEY));
// port = notNull(configMap.getLong(PORT_KEY), String.format("%s must be provided", PORT_KEY)).intValue();
// inclusiveBetween(1, Server.MAX_PORT_NUMBER, port, String.format("%s must be within %d and %d. Was: %d", PORT_KEY, 1, Server.MAX_PORT_NUMBER, port));
// maxThreads = notNull(configMap.getLong(MAX_THREADS_KEY), String.format("%s must be provided", MAX_THREADS_KEY)).intValue();
// inclusiveBetween(1, Integer.MAX_VALUE, maxThreads, String.format("%s must be within %d and %d. Was: %d", MAX_THREADS_KEY, 1, Integer.MAX_VALUE, maxThreads));
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getMaxThreads() {
// return maxThreads;
// }
// }
// Path: src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/AppConfigurationTest.java
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import se.gustavkarlsson.rocketchat.jira_trigger.server.Server;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static se.gustavkarlsson.rocketchat.jira_trigger.configuration.AppConfiguration.*;
package se.gustavkarlsson.rocketchat.jira_trigger.configuration;
@RunWith(MockitoJUnitRunner.class)
public class AppConfigurationTest {
private static final int PORT = 2000;
private static final int MAX_THREADS = 10;
@Mock
private ConfigMap mockConfigMap;
| private AppConfiguration appConfig; |
gustavkarlsson/rocketchat-jira-trigger | src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/AppConfigurationTest.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/server/Server.java
// public class Server {
// private static final Logger log = getLogger(Server.class);
//
// public static final long MAX_PORT_NUMBER = 65535;
// private static final String APPLICATION_JSON = "application/json";
//
// private final int maxThreads;
// private final String ipAddress;
// private final int port;
// private final DetectIssueRoute detectIssueRoute;
// private final JiraServerInfoLogger jiraServerInfoLogger;
//
// private Service service;
//
// Server(int maxThreads, String ipAddress, int port, DetectIssueRoute detectIssueRoute, JiraServerInfoLogger jiraServerInfoLogger) {
// this.maxThreads = maxThreads;
// inclusiveBetween(1, Integer.MAX_VALUE, maxThreads);
// this.ipAddress = notBlank(ipAddress);
// this.port = port;
// inclusiveBetween(1, MAX_PORT_NUMBER, port);
// this.detectIssueRoute = notNull(detectIssueRoute);
// this.jiraServerInfoLogger = notNull(jiraServerInfoLogger);
// }
//
// private static void logRequest(Request request) {
// log.info("Incoming request: {} {} {} {}",
// request.raw().getRemoteAddr(), request.requestMethod(), request.contentType(), request.pathInfo());
// }
//
// private static void logResponse(Response response) {
// String responseContent = response.body() == null ? "<empty>" : "Rocket.Chat message";
// log.info("Outgoing response: {}", responseContent);
// }
//
// public synchronized void start() {
// jiraServerInfoLogger.logInfo();
// log.info("Starting server...");
// if (service != null) {
// throw new IllegalStateException("Already started");
// }
// Service service = ignite();
// service.threadPool(maxThreads);
// service.port(port);
// service.ipAddress(ipAddress);
// service.before((request, response) -> logRequest(request));
// service.post("/", APPLICATION_JSON, detectIssueRoute);
// service.after((request, response) -> logResponse(response));
// service.exception(Exception.class, new UuidGeneratingExceptionHandler());
// this.service = service;
// }
//
// public synchronized void stop() {
// if (service == null) {
// throw new IllegalStateException("Already stopped");
// }
// service.stop();
// service = null;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/AppConfiguration.java
// @Singleton
// public class AppConfiguration {
// private static final String KEY_PREFIX = "app.";
// static final String IP_ADDRESS_KEY = KEY_PREFIX + "ip_address";
// static final String PORT_KEY = KEY_PREFIX + "port";
// static final String MAX_THREADS_KEY = KEY_PREFIX + "max_threads";
//
// private final String ipAddress;
// private final int port;
// private final int maxThreads;
//
// @Inject
// AppConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// ipAddress = notBlank(configMap.getString(IP_ADDRESS_KEY), String.format("Non-blank %s must be provided", IP_ADDRESS_KEY));
// port = notNull(configMap.getLong(PORT_KEY), String.format("%s must be provided", PORT_KEY)).intValue();
// inclusiveBetween(1, Server.MAX_PORT_NUMBER, port, String.format("%s must be within %d and %d. Was: %d", PORT_KEY, 1, Server.MAX_PORT_NUMBER, port));
// maxThreads = notNull(configMap.getLong(MAX_THREADS_KEY), String.format("%s must be provided", MAX_THREADS_KEY)).intValue();
// inclusiveBetween(1, Integer.MAX_VALUE, maxThreads, String.format("%s must be within %d and %d. Was: %d", MAX_THREADS_KEY, 1, Integer.MAX_VALUE, maxThreads));
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getMaxThreads() {
// return maxThreads;
// }
// }
| import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import se.gustavkarlsson.rocketchat.jira_trigger.server.Server;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static se.gustavkarlsson.rocketchat.jira_trigger.configuration.AppConfiguration.*; |
@Before
public void setUp() throws Exception {
when(mockConfigMap.getLong(PORT_KEY)).thenReturn((long) PORT);
when(mockConfigMap.getLong(MAX_THREADS_KEY)).thenReturn((long) MAX_THREADS);
when(mockConfigMap.getString(IP_ADDRESS_KEY)).thenReturn("1.2.3.4");
this.appConfig = new AppConfiguration(mockConfigMap);
}
@Test(expected = NullPointerException.class)
public void createWithNullConfigMapThrowsNPE() throws Exception {
new AppConfiguration(null);
}
@Test(expected = ValidationException.class)
public void createWithNullIpThrowsValidationException() throws Exception {
when(mockConfigMap.getString(IP_ADDRESS_KEY)).thenReturn(null);
new AppConfiguration(mockConfigMap);
}
@Test(expected = ValidationException.class)
public void createBlankIpThrowsValidationException() throws Exception {
when(mockConfigMap.getString(IP_ADDRESS_KEY)).thenReturn(" \t\n");
new AppConfiguration(mockConfigMap);
}
@Test(expected = ValidationException.class)
public void createWithTooHighPortThrowsValidationException() throws Exception { | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/server/Server.java
// public class Server {
// private static final Logger log = getLogger(Server.class);
//
// public static final long MAX_PORT_NUMBER = 65535;
// private static final String APPLICATION_JSON = "application/json";
//
// private final int maxThreads;
// private final String ipAddress;
// private final int port;
// private final DetectIssueRoute detectIssueRoute;
// private final JiraServerInfoLogger jiraServerInfoLogger;
//
// private Service service;
//
// Server(int maxThreads, String ipAddress, int port, DetectIssueRoute detectIssueRoute, JiraServerInfoLogger jiraServerInfoLogger) {
// this.maxThreads = maxThreads;
// inclusiveBetween(1, Integer.MAX_VALUE, maxThreads);
// this.ipAddress = notBlank(ipAddress);
// this.port = port;
// inclusiveBetween(1, MAX_PORT_NUMBER, port);
// this.detectIssueRoute = notNull(detectIssueRoute);
// this.jiraServerInfoLogger = notNull(jiraServerInfoLogger);
// }
//
// private static void logRequest(Request request) {
// log.info("Incoming request: {} {} {} {}",
// request.raw().getRemoteAddr(), request.requestMethod(), request.contentType(), request.pathInfo());
// }
//
// private static void logResponse(Response response) {
// String responseContent = response.body() == null ? "<empty>" : "Rocket.Chat message";
// log.info("Outgoing response: {}", responseContent);
// }
//
// public synchronized void start() {
// jiraServerInfoLogger.logInfo();
// log.info("Starting server...");
// if (service != null) {
// throw new IllegalStateException("Already started");
// }
// Service service = ignite();
// service.threadPool(maxThreads);
// service.port(port);
// service.ipAddress(ipAddress);
// service.before((request, response) -> logRequest(request));
// service.post("/", APPLICATION_JSON, detectIssueRoute);
// service.after((request, response) -> logResponse(response));
// service.exception(Exception.class, new UuidGeneratingExceptionHandler());
// this.service = service;
// }
//
// public synchronized void stop() {
// if (service == null) {
// throw new IllegalStateException("Already stopped");
// }
// service.stop();
// service = null;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/AppConfiguration.java
// @Singleton
// public class AppConfiguration {
// private static final String KEY_PREFIX = "app.";
// static final String IP_ADDRESS_KEY = KEY_PREFIX + "ip_address";
// static final String PORT_KEY = KEY_PREFIX + "port";
// static final String MAX_THREADS_KEY = KEY_PREFIX + "max_threads";
//
// private final String ipAddress;
// private final int port;
// private final int maxThreads;
//
// @Inject
// AppConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// ipAddress = notBlank(configMap.getString(IP_ADDRESS_KEY), String.format("Non-blank %s must be provided", IP_ADDRESS_KEY));
// port = notNull(configMap.getLong(PORT_KEY), String.format("%s must be provided", PORT_KEY)).intValue();
// inclusiveBetween(1, Server.MAX_PORT_NUMBER, port, String.format("%s must be within %d and %d. Was: %d", PORT_KEY, 1, Server.MAX_PORT_NUMBER, port));
// maxThreads = notNull(configMap.getLong(MAX_THREADS_KEY), String.format("%s must be provided", MAX_THREADS_KEY)).intValue();
// inclusiveBetween(1, Integer.MAX_VALUE, maxThreads, String.format("%s must be within %d and %d. Was: %d", MAX_THREADS_KEY, 1, Integer.MAX_VALUE, maxThreads));
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getMaxThreads() {
// return maxThreads;
// }
// }
// Path: src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/AppConfigurationTest.java
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import se.gustavkarlsson.rocketchat.jira_trigger.server.Server;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static se.gustavkarlsson.rocketchat.jira_trigger.configuration.AppConfiguration.*;
@Before
public void setUp() throws Exception {
when(mockConfigMap.getLong(PORT_KEY)).thenReturn((long) PORT);
when(mockConfigMap.getLong(MAX_THREADS_KEY)).thenReturn((long) MAX_THREADS);
when(mockConfigMap.getString(IP_ADDRESS_KEY)).thenReturn("1.2.3.4");
this.appConfig = new AppConfiguration(mockConfigMap);
}
@Test(expected = NullPointerException.class)
public void createWithNullConfigMapThrowsNPE() throws Exception {
new AppConfiguration(null);
}
@Test(expected = ValidationException.class)
public void createWithNullIpThrowsValidationException() throws Exception {
when(mockConfigMap.getString(IP_ADDRESS_KEY)).thenReturn(null);
new AppConfiguration(mockConfigMap);
}
@Test(expected = ValidationException.class)
public void createBlankIpThrowsValidationException() throws Exception {
when(mockConfigMap.getString(IP_ADDRESS_KEY)).thenReturn(" \t\n");
new AppConfiguration(mockConfigMap);
}
@Test(expected = ValidationException.class)
public void createWithTooHighPortThrowsValidationException() throws Exception { | when(mockConfigMap.getLong(PORT_KEY)).thenReturn(Server.MAX_PORT_NUMBER + 1); |
gustavkarlsson/rocketchat-jira-trigger | src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/AppConfiguration.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/server/Server.java
// public class Server {
// private static final Logger log = getLogger(Server.class);
//
// public static final long MAX_PORT_NUMBER = 65535;
// private static final String APPLICATION_JSON = "application/json";
//
// private final int maxThreads;
// private final String ipAddress;
// private final int port;
// private final DetectIssueRoute detectIssueRoute;
// private final JiraServerInfoLogger jiraServerInfoLogger;
//
// private Service service;
//
// Server(int maxThreads, String ipAddress, int port, DetectIssueRoute detectIssueRoute, JiraServerInfoLogger jiraServerInfoLogger) {
// this.maxThreads = maxThreads;
// inclusiveBetween(1, Integer.MAX_VALUE, maxThreads);
// this.ipAddress = notBlank(ipAddress);
// this.port = port;
// inclusiveBetween(1, MAX_PORT_NUMBER, port);
// this.detectIssueRoute = notNull(detectIssueRoute);
// this.jiraServerInfoLogger = notNull(jiraServerInfoLogger);
// }
//
// private static void logRequest(Request request) {
// log.info("Incoming request: {} {} {} {}",
// request.raw().getRemoteAddr(), request.requestMethod(), request.contentType(), request.pathInfo());
// }
//
// private static void logResponse(Response response) {
// String responseContent = response.body() == null ? "<empty>" : "Rocket.Chat message";
// log.info("Outgoing response: {}", responseContent);
// }
//
// public synchronized void start() {
// jiraServerInfoLogger.logInfo();
// log.info("Starting server...");
// if (service != null) {
// throw new IllegalStateException("Already started");
// }
// Service service = ignite();
// service.threadPool(maxThreads);
// service.port(port);
// service.ipAddress(ipAddress);
// service.before((request, response) -> logRequest(request));
// service.post("/", APPLICATION_JSON, detectIssueRoute);
// service.after((request, response) -> logResponse(response));
// service.exception(Exception.class, new UuidGeneratingExceptionHandler());
// this.service = service;
// }
//
// public synchronized void stop() {
// if (service == null) {
// throw new IllegalStateException("Already stopped");
// }
// service.stop();
// service = null;
// }
// }
| import com.google.inject.Singleton;
import se.gustavkarlsson.rocketchat.jira_trigger.server.Server;
import javax.inject.Inject;
import static org.apache.commons.lang3.Validate.*; | package se.gustavkarlsson.rocketchat.jira_trigger.configuration;
@Singleton
public class AppConfiguration {
private static final String KEY_PREFIX = "app.";
static final String IP_ADDRESS_KEY = KEY_PREFIX + "ip_address";
static final String PORT_KEY = KEY_PREFIX + "port";
static final String MAX_THREADS_KEY = KEY_PREFIX + "max_threads";
private final String ipAddress;
private final int port;
private final int maxThreads;
@Inject
AppConfiguration(ConfigMap configMap) throws ValidationException {
notNull(configMap);
try {
ipAddress = notBlank(configMap.getString(IP_ADDRESS_KEY), String.format("Non-blank %s must be provided", IP_ADDRESS_KEY));
port = notNull(configMap.getLong(PORT_KEY), String.format("%s must be provided", PORT_KEY)).intValue(); | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/server/Server.java
// public class Server {
// private static final Logger log = getLogger(Server.class);
//
// public static final long MAX_PORT_NUMBER = 65535;
// private static final String APPLICATION_JSON = "application/json";
//
// private final int maxThreads;
// private final String ipAddress;
// private final int port;
// private final DetectIssueRoute detectIssueRoute;
// private final JiraServerInfoLogger jiraServerInfoLogger;
//
// private Service service;
//
// Server(int maxThreads, String ipAddress, int port, DetectIssueRoute detectIssueRoute, JiraServerInfoLogger jiraServerInfoLogger) {
// this.maxThreads = maxThreads;
// inclusiveBetween(1, Integer.MAX_VALUE, maxThreads);
// this.ipAddress = notBlank(ipAddress);
// this.port = port;
// inclusiveBetween(1, MAX_PORT_NUMBER, port);
// this.detectIssueRoute = notNull(detectIssueRoute);
// this.jiraServerInfoLogger = notNull(jiraServerInfoLogger);
// }
//
// private static void logRequest(Request request) {
// log.info("Incoming request: {} {} {} {}",
// request.raw().getRemoteAddr(), request.requestMethod(), request.contentType(), request.pathInfo());
// }
//
// private static void logResponse(Response response) {
// String responseContent = response.body() == null ? "<empty>" : "Rocket.Chat message";
// log.info("Outgoing response: {}", responseContent);
// }
//
// public synchronized void start() {
// jiraServerInfoLogger.logInfo();
// log.info("Starting server...");
// if (service != null) {
// throw new IllegalStateException("Already started");
// }
// Service service = ignite();
// service.threadPool(maxThreads);
// service.port(port);
// service.ipAddress(ipAddress);
// service.before((request, response) -> logRequest(request));
// service.post("/", APPLICATION_JSON, detectIssueRoute);
// service.after((request, response) -> logResponse(response));
// service.exception(Exception.class, new UuidGeneratingExceptionHandler());
// this.service = service;
// }
//
// public synchronized void stop() {
// if (service == null) {
// throw new IllegalStateException("Already stopped");
// }
// service.stop();
// service = null;
// }
// }
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/AppConfiguration.java
import com.google.inject.Singleton;
import se.gustavkarlsson.rocketchat.jira_trigger.server.Server;
import javax.inject.Inject;
import static org.apache.commons.lang3.Validate.*;
package se.gustavkarlsson.rocketchat.jira_trigger.configuration;
@Singleton
public class AppConfiguration {
private static final String KEY_PREFIX = "app.";
static final String IP_ADDRESS_KEY = KEY_PREFIX + "ip_address";
static final String PORT_KEY = KEY_PREFIX + "port";
static final String MAX_THREADS_KEY = KEY_PREFIX + "max_threads";
private final String ipAddress;
private final int port;
private final int maxThreads;
@Inject
AppConfiguration(ConfigMap configMap) throws ValidationException {
notNull(configMap);
try {
ipAddress = notBlank(configMap.getString(IP_ADDRESS_KEY), String.format("Non-blank %s must be provided", IP_ADDRESS_KEY));
port = notNull(configMap.getLong(PORT_KEY), String.format("%s must be provided", PORT_KEY)).intValue(); | inclusiveBetween(1, Server.MAX_PORT_NUMBER, port, String.format("%s must be within %d and %d. Was: %d", PORT_KEY, 1, Server.MAX_PORT_NUMBER, port)); |
gustavkarlsson/rocketchat-jira-trigger | src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/jira/AuthHandlerProviderTest.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/JiraConfiguration.java
// @Singleton
// public class JiraConfiguration {
// private static final String KEY_PREFIX = "jira.";
// static final String URI_KEY = KEY_PREFIX + "uri";
// static final String USER_KEY = KEY_PREFIX + "username";
// static final String PASSWORD_KEY = KEY_PREFIX + "password";
//
// private final URI uri;
// private final String username;
// private final String password;
//
// @Inject
// JiraConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// uri = URI.create(notNull(configMap.getString(URI_KEY), String.format("%s must be provided", URI_KEY)));
// username = configMap.getString(USER_KEY);
// password = configMap.getString(PASSWORD_KEY);
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public URI getUri() {
// return uri;
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getPassword() {
// return password;
// }
// }
| import com.atlassian.jira.rest.client.api.AuthenticationHandler;
import com.atlassian.jira.rest.client.auth.AnonymousAuthenticationHandler;
import com.atlassian.jira.rest.client.auth.BasicHttpAuthenticationHandler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.JiraConfiguration;
import java.io.Console;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package se.gustavkarlsson.rocketchat.jira_trigger.jira;
@RunWith(MockitoJUnitRunner.class)
public class AuthHandlerProviderTest {
@Mock | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/JiraConfiguration.java
// @Singleton
// public class JiraConfiguration {
// private static final String KEY_PREFIX = "jira.";
// static final String URI_KEY = KEY_PREFIX + "uri";
// static final String USER_KEY = KEY_PREFIX + "username";
// static final String PASSWORD_KEY = KEY_PREFIX + "password";
//
// private final URI uri;
// private final String username;
// private final String password;
//
// @Inject
// JiraConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// uri = URI.create(notNull(configMap.getString(URI_KEY), String.format("%s must be provided", URI_KEY)));
// username = configMap.getString(USER_KEY);
// password = configMap.getString(PASSWORD_KEY);
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public URI getUri() {
// return uri;
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getPassword() {
// return password;
// }
// }
// Path: src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/jira/AuthHandlerProviderTest.java
import com.atlassian.jira.rest.client.api.AuthenticationHandler;
import com.atlassian.jira.rest.client.auth.AnonymousAuthenticationHandler;
import com.atlassian.jira.rest.client.auth.BasicHttpAuthenticationHandler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.JiraConfiguration;
import java.io.Console;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package se.gustavkarlsson.rocketchat.jira_trigger.jira;
@RunWith(MockitoJUnitRunner.class)
public class AuthHandlerProviderTest {
@Mock | JiraConfiguration mockJiraConfig; |
gustavkarlsson/rocketchat-jira-trigger | src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/server/ServerModule.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/AppConfiguration.java
// @Singleton
// public class AppConfiguration {
// private static final String KEY_PREFIX = "app.";
// static final String IP_ADDRESS_KEY = KEY_PREFIX + "ip_address";
// static final String PORT_KEY = KEY_PREFIX + "port";
// static final String MAX_THREADS_KEY = KEY_PREFIX + "max_threads";
//
// private final String ipAddress;
// private final int port;
// private final int maxThreads;
//
// @Inject
// AppConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// ipAddress = notBlank(configMap.getString(IP_ADDRESS_KEY), String.format("Non-blank %s must be provided", IP_ADDRESS_KEY));
// port = notNull(configMap.getLong(PORT_KEY), String.format("%s must be provided", PORT_KEY)).intValue();
// inclusiveBetween(1, Server.MAX_PORT_NUMBER, port, String.format("%s must be within %d and %d. Was: %d", PORT_KEY, 1, Server.MAX_PORT_NUMBER, port));
// maxThreads = notNull(configMap.getLong(MAX_THREADS_KEY), String.format("%s must be provided", MAX_THREADS_KEY)).intValue();
// inclusiveBetween(1, Integer.MAX_VALUE, maxThreads, String.format("%s must be within %d and %d. Was: %d", MAX_THREADS_KEY, 1, Integer.MAX_VALUE, maxThreads));
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getMaxThreads() {
// return maxThreads;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/routes/DetectIssueRoute.java
// @Singleton
// public class DetectIssueRoute extends RocketChatMessageRoute {
// private static final Logger log = getLogger(DetectIssueRoute.class);
//
// private final List<Validator> validators;
// private final JiraKeyParser jiraKeyParser;
// private final IssueRestClient issueClient;
// private final ToRocketChatMessageFactory messageFactory;
// private final AttachmentCreator attachmentCreator;
//
// @Inject
// DetectIssueRoute(List<Validator> validators, JiraKeyParser jiraKeyParser, IssueRestClient issueClient,
// ToRocketChatMessageFactory messageFactory, AttachmentCreator attachmentCreator) {
// this.validators = noNullElements(validators);
// this.jiraKeyParser = notNull(jiraKeyParser);
// this.issueClient = notNull(issueClient);
// this.messageFactory = notNull(messageFactory);
// this.attachmentCreator = notNull(attachmentCreator);
// }
//
// @Override
// protected ToRocketChatMessage handle(Request request, Response response, FromRocketChatMessage fromRocketChatMessage) {
// log.debug("Validating message");
// if (!isValid(fromRocketChatMessage)) {
// log.info("Validation failed. Ignoring");
// return null;
// }
//
// log.debug("Parsing keys from text: '{}'", fromRocketChatMessage.getText());
// Set<String> jiraKeys = jiraKeyParser.parse(fromRocketChatMessage.getText());
// if (jiraKeys.isEmpty()) {
// log.info("No keys found. Ignoring");
// return null;
// }
// log.info("Identified {} keys", jiraKeys.size());
// log.debug("Keys: {}", jiraKeys);
//
// log.debug("Fetching issues...");
// Set<Issue> issues = getIssues(jiraKeys);
// log.info("Found {} issues", issues.size());
// if (issues.isEmpty()) {
// log.info("No issues found. Ignoring");
// return null;
// }
// log.debug("Issues: {}", issues.stream().map(Issue::getId).collect(toList()));
// log.debug("Creating message");
// ToRocketChatMessage message = messageFactory.create();
// message.setText(issues.size() == 1 ? "Found 1 issue" : String.format("Found %d issues", issues.size()));
// List<ToRocketChatAttachment> attachments = createAttachments(issues);
// message.setAttachments(attachments);
// return message;
// }
//
// private boolean isValid(FromRocketChatMessage fromRocketChatMessage) {
// return validators.stream().allMatch(validator -> validator.isValid(fromRocketChatMessage));
// }
//
// private Set<Issue> getIssues(Set<String> jiraKeys) {
// return jiraKeys.parallelStream()
// .map(this::getIssue)
// .filter(Objects::nonNull)
// .collect(Collectors.toSet());
// }
//
// private Issue getIssue(String jiraKey) {
// try {
// return issueClient.getIssue(jiraKey).claim();
// } catch (RestClientException e) {
// if (e.getStatusCode().or(0) != NOT_FOUND_404) {
// log.error("Jira client error", e);
// }
// return null;
// }
// }
//
// private List<ToRocketChatAttachment> createAttachments(Set<Issue> issues) {
// return issues.stream()
// .map(attachmentCreator::create)
// .collect(toList());
// }
// }
| import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.AppConfiguration;
import se.gustavkarlsson.rocketchat.jira_trigger.routes.DetectIssueRoute; | package se.gustavkarlsson.rocketchat.jira_trigger.server;
public class ServerModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/AppConfiguration.java
// @Singleton
// public class AppConfiguration {
// private static final String KEY_PREFIX = "app.";
// static final String IP_ADDRESS_KEY = KEY_PREFIX + "ip_address";
// static final String PORT_KEY = KEY_PREFIX + "port";
// static final String MAX_THREADS_KEY = KEY_PREFIX + "max_threads";
//
// private final String ipAddress;
// private final int port;
// private final int maxThreads;
//
// @Inject
// AppConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// ipAddress = notBlank(configMap.getString(IP_ADDRESS_KEY), String.format("Non-blank %s must be provided", IP_ADDRESS_KEY));
// port = notNull(configMap.getLong(PORT_KEY), String.format("%s must be provided", PORT_KEY)).intValue();
// inclusiveBetween(1, Server.MAX_PORT_NUMBER, port, String.format("%s must be within %d and %d. Was: %d", PORT_KEY, 1, Server.MAX_PORT_NUMBER, port));
// maxThreads = notNull(configMap.getLong(MAX_THREADS_KEY), String.format("%s must be provided", MAX_THREADS_KEY)).intValue();
// inclusiveBetween(1, Integer.MAX_VALUE, maxThreads, String.format("%s must be within %d and %d. Was: %d", MAX_THREADS_KEY, 1, Integer.MAX_VALUE, maxThreads));
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getMaxThreads() {
// return maxThreads;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/routes/DetectIssueRoute.java
// @Singleton
// public class DetectIssueRoute extends RocketChatMessageRoute {
// private static final Logger log = getLogger(DetectIssueRoute.class);
//
// private final List<Validator> validators;
// private final JiraKeyParser jiraKeyParser;
// private final IssueRestClient issueClient;
// private final ToRocketChatMessageFactory messageFactory;
// private final AttachmentCreator attachmentCreator;
//
// @Inject
// DetectIssueRoute(List<Validator> validators, JiraKeyParser jiraKeyParser, IssueRestClient issueClient,
// ToRocketChatMessageFactory messageFactory, AttachmentCreator attachmentCreator) {
// this.validators = noNullElements(validators);
// this.jiraKeyParser = notNull(jiraKeyParser);
// this.issueClient = notNull(issueClient);
// this.messageFactory = notNull(messageFactory);
// this.attachmentCreator = notNull(attachmentCreator);
// }
//
// @Override
// protected ToRocketChatMessage handle(Request request, Response response, FromRocketChatMessage fromRocketChatMessage) {
// log.debug("Validating message");
// if (!isValid(fromRocketChatMessage)) {
// log.info("Validation failed. Ignoring");
// return null;
// }
//
// log.debug("Parsing keys from text: '{}'", fromRocketChatMessage.getText());
// Set<String> jiraKeys = jiraKeyParser.parse(fromRocketChatMessage.getText());
// if (jiraKeys.isEmpty()) {
// log.info("No keys found. Ignoring");
// return null;
// }
// log.info("Identified {} keys", jiraKeys.size());
// log.debug("Keys: {}", jiraKeys);
//
// log.debug("Fetching issues...");
// Set<Issue> issues = getIssues(jiraKeys);
// log.info("Found {} issues", issues.size());
// if (issues.isEmpty()) {
// log.info("No issues found. Ignoring");
// return null;
// }
// log.debug("Issues: {}", issues.stream().map(Issue::getId).collect(toList()));
// log.debug("Creating message");
// ToRocketChatMessage message = messageFactory.create();
// message.setText(issues.size() == 1 ? "Found 1 issue" : String.format("Found %d issues", issues.size()));
// List<ToRocketChatAttachment> attachments = createAttachments(issues);
// message.setAttachments(attachments);
// return message;
// }
//
// private boolean isValid(FromRocketChatMessage fromRocketChatMessage) {
// return validators.stream().allMatch(validator -> validator.isValid(fromRocketChatMessage));
// }
//
// private Set<Issue> getIssues(Set<String> jiraKeys) {
// return jiraKeys.parallelStream()
// .map(this::getIssue)
// .filter(Objects::nonNull)
// .collect(Collectors.toSet());
// }
//
// private Issue getIssue(String jiraKey) {
// try {
// return issueClient.getIssue(jiraKey).claim();
// } catch (RestClientException e) {
// if (e.getStatusCode().or(0) != NOT_FOUND_404) {
// log.error("Jira client error", e);
// }
// return null;
// }
// }
//
// private List<ToRocketChatAttachment> createAttachments(Set<Issue> issues) {
// return issues.stream()
// .map(attachmentCreator::create)
// .collect(toList());
// }
// }
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/server/ServerModule.java
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.AppConfiguration;
import se.gustavkarlsson.rocketchat.jira_trigger.routes.DetectIssueRoute;
package se.gustavkarlsson.rocketchat.jira_trigger.server;
public class ServerModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton | Server provideServer(AppConfiguration appConfig, DetectIssueRoute detectIssueRoute, JiraServerInfoLogger jiraServerInfoLogger) { |
gustavkarlsson/rocketchat-jira-trigger | src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/server/ServerModule.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/AppConfiguration.java
// @Singleton
// public class AppConfiguration {
// private static final String KEY_PREFIX = "app.";
// static final String IP_ADDRESS_KEY = KEY_PREFIX + "ip_address";
// static final String PORT_KEY = KEY_PREFIX + "port";
// static final String MAX_THREADS_KEY = KEY_PREFIX + "max_threads";
//
// private final String ipAddress;
// private final int port;
// private final int maxThreads;
//
// @Inject
// AppConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// ipAddress = notBlank(configMap.getString(IP_ADDRESS_KEY), String.format("Non-blank %s must be provided", IP_ADDRESS_KEY));
// port = notNull(configMap.getLong(PORT_KEY), String.format("%s must be provided", PORT_KEY)).intValue();
// inclusiveBetween(1, Server.MAX_PORT_NUMBER, port, String.format("%s must be within %d and %d. Was: %d", PORT_KEY, 1, Server.MAX_PORT_NUMBER, port));
// maxThreads = notNull(configMap.getLong(MAX_THREADS_KEY), String.format("%s must be provided", MAX_THREADS_KEY)).intValue();
// inclusiveBetween(1, Integer.MAX_VALUE, maxThreads, String.format("%s must be within %d and %d. Was: %d", MAX_THREADS_KEY, 1, Integer.MAX_VALUE, maxThreads));
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getMaxThreads() {
// return maxThreads;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/routes/DetectIssueRoute.java
// @Singleton
// public class DetectIssueRoute extends RocketChatMessageRoute {
// private static final Logger log = getLogger(DetectIssueRoute.class);
//
// private final List<Validator> validators;
// private final JiraKeyParser jiraKeyParser;
// private final IssueRestClient issueClient;
// private final ToRocketChatMessageFactory messageFactory;
// private final AttachmentCreator attachmentCreator;
//
// @Inject
// DetectIssueRoute(List<Validator> validators, JiraKeyParser jiraKeyParser, IssueRestClient issueClient,
// ToRocketChatMessageFactory messageFactory, AttachmentCreator attachmentCreator) {
// this.validators = noNullElements(validators);
// this.jiraKeyParser = notNull(jiraKeyParser);
// this.issueClient = notNull(issueClient);
// this.messageFactory = notNull(messageFactory);
// this.attachmentCreator = notNull(attachmentCreator);
// }
//
// @Override
// protected ToRocketChatMessage handle(Request request, Response response, FromRocketChatMessage fromRocketChatMessage) {
// log.debug("Validating message");
// if (!isValid(fromRocketChatMessage)) {
// log.info("Validation failed. Ignoring");
// return null;
// }
//
// log.debug("Parsing keys from text: '{}'", fromRocketChatMessage.getText());
// Set<String> jiraKeys = jiraKeyParser.parse(fromRocketChatMessage.getText());
// if (jiraKeys.isEmpty()) {
// log.info("No keys found. Ignoring");
// return null;
// }
// log.info("Identified {} keys", jiraKeys.size());
// log.debug("Keys: {}", jiraKeys);
//
// log.debug("Fetching issues...");
// Set<Issue> issues = getIssues(jiraKeys);
// log.info("Found {} issues", issues.size());
// if (issues.isEmpty()) {
// log.info("No issues found. Ignoring");
// return null;
// }
// log.debug("Issues: {}", issues.stream().map(Issue::getId).collect(toList()));
// log.debug("Creating message");
// ToRocketChatMessage message = messageFactory.create();
// message.setText(issues.size() == 1 ? "Found 1 issue" : String.format("Found %d issues", issues.size()));
// List<ToRocketChatAttachment> attachments = createAttachments(issues);
// message.setAttachments(attachments);
// return message;
// }
//
// private boolean isValid(FromRocketChatMessage fromRocketChatMessage) {
// return validators.stream().allMatch(validator -> validator.isValid(fromRocketChatMessage));
// }
//
// private Set<Issue> getIssues(Set<String> jiraKeys) {
// return jiraKeys.parallelStream()
// .map(this::getIssue)
// .filter(Objects::nonNull)
// .collect(Collectors.toSet());
// }
//
// private Issue getIssue(String jiraKey) {
// try {
// return issueClient.getIssue(jiraKey).claim();
// } catch (RestClientException e) {
// if (e.getStatusCode().or(0) != NOT_FOUND_404) {
// log.error("Jira client error", e);
// }
// return null;
// }
// }
//
// private List<ToRocketChatAttachment> createAttachments(Set<Issue> issues) {
// return issues.stream()
// .map(attachmentCreator::create)
// .collect(toList());
// }
// }
| import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.AppConfiguration;
import se.gustavkarlsson.rocketchat.jira_trigger.routes.DetectIssueRoute; | package se.gustavkarlsson.rocketchat.jira_trigger.server;
public class ServerModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/AppConfiguration.java
// @Singleton
// public class AppConfiguration {
// private static final String KEY_PREFIX = "app.";
// static final String IP_ADDRESS_KEY = KEY_PREFIX + "ip_address";
// static final String PORT_KEY = KEY_PREFIX + "port";
// static final String MAX_THREADS_KEY = KEY_PREFIX + "max_threads";
//
// private final String ipAddress;
// private final int port;
// private final int maxThreads;
//
// @Inject
// AppConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// ipAddress = notBlank(configMap.getString(IP_ADDRESS_KEY), String.format("Non-blank %s must be provided", IP_ADDRESS_KEY));
// port = notNull(configMap.getLong(PORT_KEY), String.format("%s must be provided", PORT_KEY)).intValue();
// inclusiveBetween(1, Server.MAX_PORT_NUMBER, port, String.format("%s must be within %d and %d. Was: %d", PORT_KEY, 1, Server.MAX_PORT_NUMBER, port));
// maxThreads = notNull(configMap.getLong(MAX_THREADS_KEY), String.format("%s must be provided", MAX_THREADS_KEY)).intValue();
// inclusiveBetween(1, Integer.MAX_VALUE, maxThreads, String.format("%s must be within %d and %d. Was: %d", MAX_THREADS_KEY, 1, Integer.MAX_VALUE, maxThreads));
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getMaxThreads() {
// return maxThreads;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/routes/DetectIssueRoute.java
// @Singleton
// public class DetectIssueRoute extends RocketChatMessageRoute {
// private static final Logger log = getLogger(DetectIssueRoute.class);
//
// private final List<Validator> validators;
// private final JiraKeyParser jiraKeyParser;
// private final IssueRestClient issueClient;
// private final ToRocketChatMessageFactory messageFactory;
// private final AttachmentCreator attachmentCreator;
//
// @Inject
// DetectIssueRoute(List<Validator> validators, JiraKeyParser jiraKeyParser, IssueRestClient issueClient,
// ToRocketChatMessageFactory messageFactory, AttachmentCreator attachmentCreator) {
// this.validators = noNullElements(validators);
// this.jiraKeyParser = notNull(jiraKeyParser);
// this.issueClient = notNull(issueClient);
// this.messageFactory = notNull(messageFactory);
// this.attachmentCreator = notNull(attachmentCreator);
// }
//
// @Override
// protected ToRocketChatMessage handle(Request request, Response response, FromRocketChatMessage fromRocketChatMessage) {
// log.debug("Validating message");
// if (!isValid(fromRocketChatMessage)) {
// log.info("Validation failed. Ignoring");
// return null;
// }
//
// log.debug("Parsing keys from text: '{}'", fromRocketChatMessage.getText());
// Set<String> jiraKeys = jiraKeyParser.parse(fromRocketChatMessage.getText());
// if (jiraKeys.isEmpty()) {
// log.info("No keys found. Ignoring");
// return null;
// }
// log.info("Identified {} keys", jiraKeys.size());
// log.debug("Keys: {}", jiraKeys);
//
// log.debug("Fetching issues...");
// Set<Issue> issues = getIssues(jiraKeys);
// log.info("Found {} issues", issues.size());
// if (issues.isEmpty()) {
// log.info("No issues found. Ignoring");
// return null;
// }
// log.debug("Issues: {}", issues.stream().map(Issue::getId).collect(toList()));
// log.debug("Creating message");
// ToRocketChatMessage message = messageFactory.create();
// message.setText(issues.size() == 1 ? "Found 1 issue" : String.format("Found %d issues", issues.size()));
// List<ToRocketChatAttachment> attachments = createAttachments(issues);
// message.setAttachments(attachments);
// return message;
// }
//
// private boolean isValid(FromRocketChatMessage fromRocketChatMessage) {
// return validators.stream().allMatch(validator -> validator.isValid(fromRocketChatMessage));
// }
//
// private Set<Issue> getIssues(Set<String> jiraKeys) {
// return jiraKeys.parallelStream()
// .map(this::getIssue)
// .filter(Objects::nonNull)
// .collect(Collectors.toSet());
// }
//
// private Issue getIssue(String jiraKey) {
// try {
// return issueClient.getIssue(jiraKey).claim();
// } catch (RestClientException e) {
// if (e.getStatusCode().or(0) != NOT_FOUND_404) {
// log.error("Jira client error", e);
// }
// return null;
// }
// }
//
// private List<ToRocketChatAttachment> createAttachments(Set<Issue> issues) {
// return issues.stream()
// .map(attachmentCreator::create)
// .collect(toList());
// }
// }
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/server/ServerModule.java
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.AppConfiguration;
import se.gustavkarlsson.rocketchat.jira_trigger.routes.DetectIssueRoute;
package se.gustavkarlsson.rocketchat.jira_trigger.server;
public class ServerModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton | Server provideServer(AppConfiguration appConfig, DetectIssueRoute detectIssueRoute, JiraServerInfoLogger jiraServerInfoLogger) { |
gustavkarlsson/rocketchat-jira-trigger | src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/AttachmentCreator.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/FieldCreator.java
// public interface FieldCreator {
// Field create(Issue issue);
// }
| import com.atlassian.jira.rest.client.api.domain.BasicPriority;
import com.atlassian.jira.rest.client.api.domain.Issue;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.FieldCreator;
import se.gustavkarlsson.rocketchat.models.to_rocket_chat.Field;
import se.gustavkarlsson.rocketchat.models.to_rocket_chat.ToRocketChatAttachment;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.apache.commons.lang.StringEscapeUtils.unescapeHtml;
import static org.apache.commons.lang3.Validate.*; | package se.gustavkarlsson.rocketchat.jira_trigger.messages;
public class AttachmentCreator {
static final String BLOCKER_COLOR = "#FF4437";
static final String CRITICAL_COLOR = "#D04437";
static final String MAJOR_COLOR = "#E3833C";
static final String MINOR_COLOR = "#F6C342";
static final String TRIVIAL_COLOR = "#707070";
private final boolean priorityColors;
private final String defaultColor; | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/FieldCreator.java
// public interface FieldCreator {
// Field create(Issue issue);
// }
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/AttachmentCreator.java
import com.atlassian.jira.rest.client.api.domain.BasicPriority;
import com.atlassian.jira.rest.client.api.domain.Issue;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.FieldCreator;
import se.gustavkarlsson.rocketchat.models.to_rocket_chat.Field;
import se.gustavkarlsson.rocketchat.models.to_rocket_chat.ToRocketChatAttachment;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.apache.commons.lang.StringEscapeUtils.unescapeHtml;
import static org.apache.commons.lang3.Validate.*;
package se.gustavkarlsson.rocketchat.jira_trigger.messages;
public class AttachmentCreator {
static final String BLOCKER_COLOR = "#FF4437";
static final String CRITICAL_COLOR = "#D04437";
static final String MAJOR_COLOR = "#E3833C";
static final String MINOR_COLOR = "#F6C342";
static final String TRIVIAL_COLOR = "#707070";
private final boolean priorityColors;
private final String defaultColor; | private final List<FieldCreator> fieldCreators; |
gustavkarlsson/rocketchat-jira-trigger | src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/server/Server.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/routes/DetectIssueRoute.java
// @Singleton
// public class DetectIssueRoute extends RocketChatMessageRoute {
// private static final Logger log = getLogger(DetectIssueRoute.class);
//
// private final List<Validator> validators;
// private final JiraKeyParser jiraKeyParser;
// private final IssueRestClient issueClient;
// private final ToRocketChatMessageFactory messageFactory;
// private final AttachmentCreator attachmentCreator;
//
// @Inject
// DetectIssueRoute(List<Validator> validators, JiraKeyParser jiraKeyParser, IssueRestClient issueClient,
// ToRocketChatMessageFactory messageFactory, AttachmentCreator attachmentCreator) {
// this.validators = noNullElements(validators);
// this.jiraKeyParser = notNull(jiraKeyParser);
// this.issueClient = notNull(issueClient);
// this.messageFactory = notNull(messageFactory);
// this.attachmentCreator = notNull(attachmentCreator);
// }
//
// @Override
// protected ToRocketChatMessage handle(Request request, Response response, FromRocketChatMessage fromRocketChatMessage) {
// log.debug("Validating message");
// if (!isValid(fromRocketChatMessage)) {
// log.info("Validation failed. Ignoring");
// return null;
// }
//
// log.debug("Parsing keys from text: '{}'", fromRocketChatMessage.getText());
// Set<String> jiraKeys = jiraKeyParser.parse(fromRocketChatMessage.getText());
// if (jiraKeys.isEmpty()) {
// log.info("No keys found. Ignoring");
// return null;
// }
// log.info("Identified {} keys", jiraKeys.size());
// log.debug("Keys: {}", jiraKeys);
//
// log.debug("Fetching issues...");
// Set<Issue> issues = getIssues(jiraKeys);
// log.info("Found {} issues", issues.size());
// if (issues.isEmpty()) {
// log.info("No issues found. Ignoring");
// return null;
// }
// log.debug("Issues: {}", issues.stream().map(Issue::getId).collect(toList()));
// log.debug("Creating message");
// ToRocketChatMessage message = messageFactory.create();
// message.setText(issues.size() == 1 ? "Found 1 issue" : String.format("Found %d issues", issues.size()));
// List<ToRocketChatAttachment> attachments = createAttachments(issues);
// message.setAttachments(attachments);
// return message;
// }
//
// private boolean isValid(FromRocketChatMessage fromRocketChatMessage) {
// return validators.stream().allMatch(validator -> validator.isValid(fromRocketChatMessage));
// }
//
// private Set<Issue> getIssues(Set<String> jiraKeys) {
// return jiraKeys.parallelStream()
// .map(this::getIssue)
// .filter(Objects::nonNull)
// .collect(Collectors.toSet());
// }
//
// private Issue getIssue(String jiraKey) {
// try {
// return issueClient.getIssue(jiraKey).claim();
// } catch (RestClientException e) {
// if (e.getStatusCode().or(0) != NOT_FOUND_404) {
// log.error("Jira client error", e);
// }
// return null;
// }
// }
//
// private List<ToRocketChatAttachment> createAttachments(Set<Issue> issues) {
// return issues.stream()
// .map(attachmentCreator::create)
// .collect(toList());
// }
// }
| import org.slf4j.Logger;
import se.gustavkarlsson.rocketchat.jira_trigger.routes.DetectIssueRoute;
import spark.Request;
import spark.Response;
import spark.Service;
import static org.apache.commons.lang3.Validate.*;
import static org.slf4j.LoggerFactory.getLogger;
import static spark.Service.ignite; | package se.gustavkarlsson.rocketchat.jira_trigger.server;
public class Server {
private static final Logger log = getLogger(Server.class);
public static final long MAX_PORT_NUMBER = 65535;
private static final String APPLICATION_JSON = "application/json";
private final int maxThreads;
private final String ipAddress;
private final int port; | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/routes/DetectIssueRoute.java
// @Singleton
// public class DetectIssueRoute extends RocketChatMessageRoute {
// private static final Logger log = getLogger(DetectIssueRoute.class);
//
// private final List<Validator> validators;
// private final JiraKeyParser jiraKeyParser;
// private final IssueRestClient issueClient;
// private final ToRocketChatMessageFactory messageFactory;
// private final AttachmentCreator attachmentCreator;
//
// @Inject
// DetectIssueRoute(List<Validator> validators, JiraKeyParser jiraKeyParser, IssueRestClient issueClient,
// ToRocketChatMessageFactory messageFactory, AttachmentCreator attachmentCreator) {
// this.validators = noNullElements(validators);
// this.jiraKeyParser = notNull(jiraKeyParser);
// this.issueClient = notNull(issueClient);
// this.messageFactory = notNull(messageFactory);
// this.attachmentCreator = notNull(attachmentCreator);
// }
//
// @Override
// protected ToRocketChatMessage handle(Request request, Response response, FromRocketChatMessage fromRocketChatMessage) {
// log.debug("Validating message");
// if (!isValid(fromRocketChatMessage)) {
// log.info("Validation failed. Ignoring");
// return null;
// }
//
// log.debug("Parsing keys from text: '{}'", fromRocketChatMessage.getText());
// Set<String> jiraKeys = jiraKeyParser.parse(fromRocketChatMessage.getText());
// if (jiraKeys.isEmpty()) {
// log.info("No keys found. Ignoring");
// return null;
// }
// log.info("Identified {} keys", jiraKeys.size());
// log.debug("Keys: {}", jiraKeys);
//
// log.debug("Fetching issues...");
// Set<Issue> issues = getIssues(jiraKeys);
// log.info("Found {} issues", issues.size());
// if (issues.isEmpty()) {
// log.info("No issues found. Ignoring");
// return null;
// }
// log.debug("Issues: {}", issues.stream().map(Issue::getId).collect(toList()));
// log.debug("Creating message");
// ToRocketChatMessage message = messageFactory.create();
// message.setText(issues.size() == 1 ? "Found 1 issue" : String.format("Found %d issues", issues.size()));
// List<ToRocketChatAttachment> attachments = createAttachments(issues);
// message.setAttachments(attachments);
// return message;
// }
//
// private boolean isValid(FromRocketChatMessage fromRocketChatMessage) {
// return validators.stream().allMatch(validator -> validator.isValid(fromRocketChatMessage));
// }
//
// private Set<Issue> getIssues(Set<String> jiraKeys) {
// return jiraKeys.parallelStream()
// .map(this::getIssue)
// .filter(Objects::nonNull)
// .collect(Collectors.toSet());
// }
//
// private Issue getIssue(String jiraKey) {
// try {
// return issueClient.getIssue(jiraKey).claim();
// } catch (RestClientException e) {
// if (e.getStatusCode().or(0) != NOT_FOUND_404) {
// log.error("Jira client error", e);
// }
// return null;
// }
// }
//
// private List<ToRocketChatAttachment> createAttachments(Set<Issue> issues) {
// return issues.stream()
// .map(attachmentCreator::create)
// .collect(toList());
// }
// }
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/server/Server.java
import org.slf4j.Logger;
import se.gustavkarlsson.rocketchat.jira_trigger.routes.DetectIssueRoute;
import spark.Request;
import spark.Response;
import spark.Service;
import static org.apache.commons.lang3.Validate.*;
import static org.slf4j.LoggerFactory.getLogger;
import static spark.Service.ignite;
package se.gustavkarlsson.rocketchat.jira_trigger.server;
public class Server {
private static final Logger log = getLogger(Server.class);
public static final long MAX_PORT_NUMBER = 65535;
private static final String APPLICATION_JSON = "application/json";
private final int maxThreads;
private final String ipAddress;
private final int port; | private final DetectIssueRoute detectIssueRoute; |
gustavkarlsson/rocketchat-jira-trigger | src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/jira/JiraModule.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/JiraConfiguration.java
// @Singleton
// public class JiraConfiguration {
// private static final String KEY_PREFIX = "jira.";
// static final String URI_KEY = KEY_PREFIX + "uri";
// static final String USER_KEY = KEY_PREFIX + "username";
// static final String PASSWORD_KEY = KEY_PREFIX + "password";
//
// private final URI uri;
// private final String username;
// private final String password;
//
// @Inject
// JiraConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// uri = URI.create(notNull(configMap.getString(URI_KEY), String.format("%s must be provided", URI_KEY)));
// username = configMap.getString(USER_KEY);
// password = configMap.getString(PASSWORD_KEY);
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public URI getUri() {
// return uri;
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getPassword() {
// return password;
// }
// }
| import com.atlassian.jira.rest.client.api.AuthenticationHandler;
import com.atlassian.jira.rest.client.api.IssueRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.MetadataRestClient;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.JiraConfiguration;
import java.io.Console; | package se.gustavkarlsson.rocketchat.jira_trigger.jira;
public class JiraModule extends AbstractModule {
@Override
protected void configure() {
bind(AuthenticationHandler.class).toProvider(AuthHandlerProvider.class);
}
@Provides
@Singleton | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/JiraConfiguration.java
// @Singleton
// public class JiraConfiguration {
// private static final String KEY_PREFIX = "jira.";
// static final String URI_KEY = KEY_PREFIX + "uri";
// static final String USER_KEY = KEY_PREFIX + "username";
// static final String PASSWORD_KEY = KEY_PREFIX + "password";
//
// private final URI uri;
// private final String username;
// private final String password;
//
// @Inject
// JiraConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// uri = URI.create(notNull(configMap.getString(URI_KEY), String.format("%s must be provided", URI_KEY)));
// username = configMap.getString(USER_KEY);
// password = configMap.getString(PASSWORD_KEY);
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public URI getUri() {
// return uri;
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getPassword() {
// return password;
// }
// }
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/jira/JiraModule.java
import com.atlassian.jira.rest.client.api.AuthenticationHandler;
import com.atlassian.jira.rest.client.api.IssueRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.MetadataRestClient;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.JiraConfiguration;
import java.io.Console;
package se.gustavkarlsson.rocketchat.jira_trigger.jira;
public class JiraModule extends AbstractModule {
@Override
protected void configure() {
bind(AuthenticationHandler.class).toProvider(AuthHandlerProvider.class);
}
@Provides
@Singleton | JiraRestClient provideJiraRestClient(JiraConfiguration jiraConfig, AuthenticationHandler authHandler) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.