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 |
|---|---|---|---|---|---|---|
idega/is.idega.idegaweb.egov.course | src/java/is/idega/idegaweb/egov/course/data/CourseBMPBean.java | // Path: src/java/is/idega/idegaweb/egov/course/data/rent/RentableItem.java
// public interface RentableItem extends IDOEntity {
//
// public String getType();
// public void setType(String type);
//
// public String getName();
// public void setName(String name);
//
// public Double getRentPrice(SchoolSeason season);
// public void setRentPrice(SchoolSeason season, Double rentPrice);
//
// public Integer getQuantity();
// public void setQuantity(Integer quantity);
//
// public Integer getRentedAmount();
// public void setRentedAmount(Integer rented);
//
// public void addPrice(CoursePrice price) throws IDOAddRelationshipException;
// public Collection<CoursePrice> getAllPrices();
// public void removePrice(CoursePrice price) throws IDORemoveRelationshipException;
// public void removeAllPrices() throws IDORemoveRelationshipException;
// }
| import is.idega.idegaweb.egov.course.data.rent.RentableItem;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.logging.Level;
import javax.ejb.FinderException;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.idega.block.school.data.School;
import com.idega.block.school.data.SchoolSeason;
import com.idega.block.school.data.SchoolType;
import com.idega.data.GenericEntity;
import com.idega.data.IDOAddRelationshipException;
import com.idega.data.IDOException;
import com.idega.data.IDOFinderException;
import com.idega.data.IDOLookupException;
import com.idega.data.IDORelationshipException;
import com.idega.data.IDORemoveRelationshipException;
import com.idega.data.query.AND;
import com.idega.data.query.Column;
import com.idega.data.query.CountColumn;
import com.idega.data.query.InCriteria;
import com.idega.data.query.MatchCriteria;
import com.idega.data.query.MaxColumn;
import com.idega.data.query.OR;
import com.idega.data.query.SelectQuery;
import com.idega.data.query.Table;
import com.idega.idegaweb.IWMainApplication;
import com.idega.util.ListUtil; | return ENTITY_NAME;
}
@SuppressWarnings("unchecked")
@Override
public void initializeAttributes() {
addAttribute(getIDColumnName());
addAttribute(COLUMN_COURSE_NUMBER, "Course number", Integer.class);
addAttribute(COLUMN_NAME, "Name", String.class, 50);
addAttribute(COLUMN_USER, "User", String.class);
addAttribute(COLUMN_DESCRIPTION, "Description", String.class);
addAttribute(COLUMN_START_DATE, "Start date", Timestamp.class);
addAttribute(COLUMN_END_DATE, "End date", Timestamp.class);
addAttribute(COLUMN_REGISTRATION_END, "Registration end", Timestamp.class);
addAttribute(COLUMN_ACCOUNTING_KEY, "Accounting key", String.class, 30);
addAttribute(COLUMN_BIRTHYEAR_FROM, "Birthyear from", Integer.class);
addAttribute(COLUMN_BIRTHYEAR_TO, "Birthyear from", Integer.class);
addAttribute(COLUMN_MAX_PARTICIPANTS, "Max", Integer.class);
addAttribute(COLUMN_PRICE, "Price", Float.class);
addAttribute(COLUMN_COST, "Cost", Float.class);
addAttribute(COLUMN_OPEN_FOR_REGISTRATION, "Open for registration", Boolean.class);
addAttribute(COLUMN_PRE_CARE, "Has pre care", Boolean.class);
addAttribute(COLUMN_POST_CARE, "Has post care", Boolean.class);
addManyToOneRelationship(COLUMN_COURSE_TYPE, CourseType.class);
addManyToOneRelationship(COLUMN_COURSE_PRICE, CoursePrice.class);
addManyToOneRelationship(COLUMN_PROVIDER, School.class);
addManyToManyRelationShip(CoursePrice.class, COLUMN_COURSE_PRICES);
addManyToManyRelationShip(SchoolSeason.class, COLUMN_COURSE_SEASONS);
| // Path: src/java/is/idega/idegaweb/egov/course/data/rent/RentableItem.java
// public interface RentableItem extends IDOEntity {
//
// public String getType();
// public void setType(String type);
//
// public String getName();
// public void setName(String name);
//
// public Double getRentPrice(SchoolSeason season);
// public void setRentPrice(SchoolSeason season, Double rentPrice);
//
// public Integer getQuantity();
// public void setQuantity(Integer quantity);
//
// public Integer getRentedAmount();
// public void setRentedAmount(Integer rented);
//
// public void addPrice(CoursePrice price) throws IDOAddRelationshipException;
// public Collection<CoursePrice> getAllPrices();
// public void removePrice(CoursePrice price) throws IDORemoveRelationshipException;
// public void removeAllPrices() throws IDORemoveRelationshipException;
// }
// Path: src/java/is/idega/idegaweb/egov/course/data/CourseBMPBean.java
import is.idega.idegaweb.egov.course.data.rent.RentableItem;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.logging.Level;
import javax.ejb.FinderException;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.idega.block.school.data.School;
import com.idega.block.school.data.SchoolSeason;
import com.idega.block.school.data.SchoolType;
import com.idega.data.GenericEntity;
import com.idega.data.IDOAddRelationshipException;
import com.idega.data.IDOException;
import com.idega.data.IDOFinderException;
import com.idega.data.IDOLookupException;
import com.idega.data.IDORelationshipException;
import com.idega.data.IDORemoveRelationshipException;
import com.idega.data.query.AND;
import com.idega.data.query.Column;
import com.idega.data.query.CountColumn;
import com.idega.data.query.InCriteria;
import com.idega.data.query.MatchCriteria;
import com.idega.data.query.MaxColumn;
import com.idega.data.query.OR;
import com.idega.data.query.SelectQuery;
import com.idega.data.query.Table;
import com.idega.idegaweb.IWMainApplication;
import com.idega.util.ListUtil;
return ENTITY_NAME;
}
@SuppressWarnings("unchecked")
@Override
public void initializeAttributes() {
addAttribute(getIDColumnName());
addAttribute(COLUMN_COURSE_NUMBER, "Course number", Integer.class);
addAttribute(COLUMN_NAME, "Name", String.class, 50);
addAttribute(COLUMN_USER, "User", String.class);
addAttribute(COLUMN_DESCRIPTION, "Description", String.class);
addAttribute(COLUMN_START_DATE, "Start date", Timestamp.class);
addAttribute(COLUMN_END_DATE, "End date", Timestamp.class);
addAttribute(COLUMN_REGISTRATION_END, "Registration end", Timestamp.class);
addAttribute(COLUMN_ACCOUNTING_KEY, "Accounting key", String.class, 30);
addAttribute(COLUMN_BIRTHYEAR_FROM, "Birthyear from", Integer.class);
addAttribute(COLUMN_BIRTHYEAR_TO, "Birthyear from", Integer.class);
addAttribute(COLUMN_MAX_PARTICIPANTS, "Max", Integer.class);
addAttribute(COLUMN_PRICE, "Price", Float.class);
addAttribute(COLUMN_COST, "Cost", Float.class);
addAttribute(COLUMN_OPEN_FOR_REGISTRATION, "Open for registration", Boolean.class);
addAttribute(COLUMN_PRE_CARE, "Has pre care", Boolean.class);
addAttribute(COLUMN_POST_CARE, "Has post care", Boolean.class);
addManyToOneRelationship(COLUMN_COURSE_TYPE, CourseType.class);
addManyToOneRelationship(COLUMN_COURSE_PRICE, CoursePrice.class);
addManyToOneRelationship(COLUMN_PROVIDER, School.class);
addManyToManyRelationShip(CoursePrice.class, COLUMN_COURSE_PRICES);
addManyToManyRelationShip(SchoolSeason.class, COLUMN_COURSE_SEASONS);
| Map<String, ? extends RentableItem> entities = null; |
idega/is.idega.idegaweb.egov.course | src/java/is/idega/idegaweb/egov/course/data/rent/RentableItem.java | // Path: src/java/is/idega/idegaweb/egov/course/data/CoursePrice.java
// public interface CoursePrice extends IDOEntity {
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getName
// */
// public String getName();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getSchoolArea
// */
// public SchoolArea getSchoolArea();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getCourseType
// */
// public CourseType getCourseType();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getValidFrom
// */
// public Timestamp getValidFrom();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getValidTo
// */
// public Timestamp getValidTo();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getNumberOfDays
// */
// public int getNumberOfDays();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getPrice
// */
// public int getPrice();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getPreCarePrice
// */
// public int getPreCarePrice();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getPostCarePrice
// */
// public int getPostCarePrice();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setName
// */
// public void setName(String name);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setSchoolArea
// */
// public void setSchoolArea(SchoolArea area);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setCourseType
// */
// public void setCourseType(CourseType type);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setValidFrom
// */
// public void setValidFrom(Timestamp stamp);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setValidTo
// */
// public void setValidTo(Timestamp stamp);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setValid
// */
// public void setValid(boolean valid);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setNumberOfDays
// */
// public void setNumberOfDays(int noDays);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setPrice
// */
// public void setPrice(int price);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setPreCarePrice
// */
// public void setPreCarePrice(int price);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setPostCarePrice
// */
// public void setPostCarePrice(int price);
//
// public SchoolType getSchoolType();
// public void setSchoolType(SchoolType schoolType);
//
// public SchoolSeason getSchoolSeason();
// public void setSchoolSeason(SchoolSeason season);
// }
| import is.idega.idegaweb.egov.course.data.CoursePrice;
import java.util.Collection;
import com.idega.block.school.data.SchoolSeason;
import com.idega.data.IDOAddRelationshipException;
import com.idega.data.IDOEntity;
import com.idega.data.IDORemoveRelationshipException; | package is.idega.idegaweb.egov.course.data.rent;
public interface RentableItem extends IDOEntity {
public String getType();
public void setType(String type);
public String getName();
public void setName(String name);
public Double getRentPrice(SchoolSeason season);
public void setRentPrice(SchoolSeason season, Double rentPrice);
public Integer getQuantity();
public void setQuantity(Integer quantity);
public Integer getRentedAmount();
public void setRentedAmount(Integer rented);
| // Path: src/java/is/idega/idegaweb/egov/course/data/CoursePrice.java
// public interface CoursePrice extends IDOEntity {
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getName
// */
// public String getName();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getSchoolArea
// */
// public SchoolArea getSchoolArea();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getCourseType
// */
// public CourseType getCourseType();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getValidFrom
// */
// public Timestamp getValidFrom();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getValidTo
// */
// public Timestamp getValidTo();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getNumberOfDays
// */
// public int getNumberOfDays();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getPrice
// */
// public int getPrice();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getPreCarePrice
// */
// public int getPreCarePrice();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getPostCarePrice
// */
// public int getPostCarePrice();
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setName
// */
// public void setName(String name);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setSchoolArea
// */
// public void setSchoolArea(SchoolArea area);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setCourseType
// */
// public void setCourseType(CourseType type);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setValidFrom
// */
// public void setValidFrom(Timestamp stamp);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setValidTo
// */
// public void setValidTo(Timestamp stamp);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setValid
// */
// public void setValid(boolean valid);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setNumberOfDays
// */
// public void setNumberOfDays(int noDays);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setPrice
// */
// public void setPrice(int price);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setPreCarePrice
// */
// public void setPreCarePrice(int price);
//
// /**
// * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setPostCarePrice
// */
// public void setPostCarePrice(int price);
//
// public SchoolType getSchoolType();
// public void setSchoolType(SchoolType schoolType);
//
// public SchoolSeason getSchoolSeason();
// public void setSchoolSeason(SchoolSeason season);
// }
// Path: src/java/is/idega/idegaweb/egov/course/data/rent/RentableItem.java
import is.idega.idegaweb.egov.course.data.CoursePrice;
import java.util.Collection;
import com.idega.block.school.data.SchoolSeason;
import com.idega.data.IDOAddRelationshipException;
import com.idega.data.IDOEntity;
import com.idega.data.IDORemoveRelationshipException;
package is.idega.idegaweb.egov.course.data.rent;
public interface RentableItem extends IDOEntity {
public String getType();
public void setType(String type);
public String getName();
public void setName(String name);
public Double getRentPrice(SchoolSeason season);
public void setRentPrice(SchoolSeason season, Double rentPrice);
public Integer getQuantity();
public void setQuantity(Integer quantity);
public Integer getRentedAmount();
public void setRentedAmount(Integer rented);
| public void addPrice(CoursePrice price) throws IDOAddRelationshipException; |
struktured/ocamljava-maven-plugin | ocamljava-dependency-analyzer/src/main/java/mandelbrot/dependency/data/ModuleKey.java | // Path: ocamljava-dependency-analyzer/src/main/java/mandelbrot/dependency/analyzer/Analyzer.java
// public class Analyzer {
//
// public static Optional<String> moduleNameOfSource(final String source) {
// if (StringUtils.isBlank(source))
// return Optional.absent();
//
// final String name = new File(source).getName();
// final String extension = org.codehaus.plexus.util.FileUtils
// .getExtension(name);
//
// final String rawModuleName = name.substring(0, name.length()
// - (extension.length() == 0 ? 0 : extension.length()
// + File.separator.length()));
//
// final String lowerCasedName = rawModuleName.toLowerCase();
//
// if (lowerCasedName.isEmpty())
// return Optional.absent();
//
// return Optional.of(lowerCasedName);
//
// }
// }
| import java.io.File;
import java.util.Comparator;
import mandelbrot.dependency.analyzer.Analyzer;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonSubTypes;
import org.codehaus.jackson.annotate.JsonTypeName;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.StringUtils;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions; |
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ModuleDescriptor other = (ModuleDescriptor) obj;
if (moduleName == null) {
if (other.moduleName != null)
return false;
} else if (!moduleName.equals(other.moduleName))
return false;
if (moduleType != other.moduleType)
return false;
return true;
}
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
public static ModuleKey fromFile(final File sourceFile) { | // Path: ocamljava-dependency-analyzer/src/main/java/mandelbrot/dependency/analyzer/Analyzer.java
// public class Analyzer {
//
// public static Optional<String> moduleNameOfSource(final String source) {
// if (StringUtils.isBlank(source))
// return Optional.absent();
//
// final String name = new File(source).getName();
// final String extension = org.codehaus.plexus.util.FileUtils
// .getExtension(name);
//
// final String rawModuleName = name.substring(0, name.length()
// - (extension.length() == 0 ? 0 : extension.length()
// + File.separator.length()));
//
// final String lowerCasedName = rawModuleName.toLowerCase();
//
// if (lowerCasedName.isEmpty())
// return Optional.absent();
//
// return Optional.of(lowerCasedName);
//
// }
// }
// Path: ocamljava-dependency-analyzer/src/main/java/mandelbrot/dependency/data/ModuleKey.java
import java.io.File;
import java.util.Comparator;
import mandelbrot.dependency.analyzer.Analyzer;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonSubTypes;
import org.codehaus.jackson.annotate.JsonTypeName;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.StringUtils;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ModuleDescriptor other = (ModuleDescriptor) obj;
if (moduleName == null) {
if (other.moduleName != null)
return false;
} else if (!moduleName.equals(other.moduleName))
return false;
if (moduleType != other.moduleType)
return false;
return true;
}
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
public static ModuleKey fromFile(final File sourceFile) { | return new ModuleKey.Builder().setModuleName(Analyzer.moduleNameOfSource(sourceFile.getPath()).get()) |
struktured/ocamljava-maven-plugin | ocamljava-maven-plugins/ocamljava-jar-maven-plugin/src/main/java/mandelbrot/ocamljava_maven_plugin/OcamlJavaTestJarMojo.java | // Path: ocamljava-maven-plugins/ocamljava-maven-plugin-base/src/main/java/mandelbrot/ocamljava_maven_plugin/OcamlJavaConstants.java
// public static final String COMPILED_IMPL_JAVA_EXTENSION = "cmj";
| import static mandelbrot.ocamljava_maven_plugin.OcamlJavaConstants.COMPILED_IMPL_JAVA_EXTENSION;
import java.io.File;
import ocaml.compilers.ocamljavaMain;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.codehaus.plexus.util.FileUtils;
import com.google.common.collect.ImmutableList; |
public ImmutableList<String> gatherOcamlCompiledSources(final File root) {
final ImmutableList.Builder<String> files = ImmutableList.builder();
if (root.isFile() && isOcamlCompiledSourceFile(root)) {
files.add(root.getPath());
return files.build();
}
final File[] listFiles;
if (!root.isDirectory() || (listFiles = root.listFiles()) == null)
return files.build();
for (final File file : listFiles) {
if (file.isDirectory()) {
getLog().info("scanning directory: " + file);
files.addAll(gatherOcamlCompiledSources(file));
} else {
if (isOcamlCompiledSourceFile(file)) {
getLog().info("adding ocaml source file: " + file);
files.add(file.getPath());
}
}
}
return files.build();
}
private boolean isOcamlCompiledSourceFile(final File file) {
final String extension = FileUtils.getExtension(file.getPath()); | // Path: ocamljava-maven-plugins/ocamljava-maven-plugin-base/src/main/java/mandelbrot/ocamljava_maven_plugin/OcamlJavaConstants.java
// public static final String COMPILED_IMPL_JAVA_EXTENSION = "cmj";
// Path: ocamljava-maven-plugins/ocamljava-jar-maven-plugin/src/main/java/mandelbrot/ocamljava_maven_plugin/OcamlJavaTestJarMojo.java
import static mandelbrot.ocamljava_maven_plugin.OcamlJavaConstants.COMPILED_IMPL_JAVA_EXTENSION;
import java.io.File;
import ocaml.compilers.ocamljavaMain;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.codehaus.plexus.util.FileUtils;
import com.google.common.collect.ImmutableList;
public ImmutableList<String> gatherOcamlCompiledSources(final File root) {
final ImmutableList.Builder<String> files = ImmutableList.builder();
if (root.isFile() && isOcamlCompiledSourceFile(root)) {
files.add(root.getPath());
return files.build();
}
final File[] listFiles;
if (!root.isDirectory() || (listFiles = root.listFiles()) == null)
return files.build();
for (final File file : listFiles) {
if (file.isDirectory()) {
getLog().info("scanning directory: " + file);
files.addAll(gatherOcamlCompiledSources(file));
} else {
if (isOcamlCompiledSourceFile(file)) {
getLog().info("adding ocaml source file: " + file);
files.add(file.getPath());
}
}
}
return files.build();
}
private boolean isOcamlCompiledSourceFile(final File file) {
final String extension = FileUtils.getExtension(file.getPath()); | return COMPILED_IMPL_JAVA_EXTENSION.equalsIgnoreCase(extension); |
chukanov/mnp | test/com/eyeline/mnp/test/ConcurrentStorageTest.java | // Path: src/com/eyeline/mnp/ConcurrentStorage.java
// public class ConcurrentStorage implements Storage {
// private Storage realStorage;
// private ReadWriteLock lock = new ReentrantReadWriteLock();
// private Lock readLock = lock.readLock();
// private Lock writeLock = lock.writeLock();
//
// public ConcurrentStorage(Storage realStorage) {
// this.realStorage = realStorage;
// }
//
// public void setRealStorage(Storage realStorage) {
// try{
// writeLock.lock();
// this.realStorage = realStorage;
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// try{
// writeLock.lock();
// return realStorage.put(mask, mno);
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public Mno remove(Mask mask) {
// try{
// writeLock.lock();
// return realStorage.remove(mask);
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public void clear() {
// try{
// writeLock.lock();
// realStorage.clear();
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public Mno lookup(String subscriber) {
// try{
// readLock.lock();
// return realStorage.lookup(subscriber);
// } finally {
// readLock.unlock();
// }
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
| import com.eyeline.mnp.ConcurrentStorage;
import com.eyeline.mnp.Storage; | package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class ConcurrentStorageTest extends BaseStorageTest {
@Override | // Path: src/com/eyeline/mnp/ConcurrentStorage.java
// public class ConcurrentStorage implements Storage {
// private Storage realStorage;
// private ReadWriteLock lock = new ReentrantReadWriteLock();
// private Lock readLock = lock.readLock();
// private Lock writeLock = lock.writeLock();
//
// public ConcurrentStorage(Storage realStorage) {
// this.realStorage = realStorage;
// }
//
// public void setRealStorage(Storage realStorage) {
// try{
// writeLock.lock();
// this.realStorage = realStorage;
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// try{
// writeLock.lock();
// return realStorage.put(mask, mno);
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public Mno remove(Mask mask) {
// try{
// writeLock.lock();
// return realStorage.remove(mask);
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public void clear() {
// try{
// writeLock.lock();
// realStorage.clear();
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public Mno lookup(String subscriber) {
// try{
// readLock.lock();
// return realStorage.lookup(subscriber);
// } finally {
// readLock.unlock();
// }
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
// Path: test/com/eyeline/mnp/test/ConcurrentStorageTest.java
import com.eyeline.mnp.ConcurrentStorage;
import com.eyeline.mnp.Storage;
package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class ConcurrentStorageTest extends BaseStorageTest {
@Override | protected Storage build() { |
chukanov/mnp | test/com/eyeline/mnp/test/ConcurrentStorageTest.java | // Path: src/com/eyeline/mnp/ConcurrentStorage.java
// public class ConcurrentStorage implements Storage {
// private Storage realStorage;
// private ReadWriteLock lock = new ReentrantReadWriteLock();
// private Lock readLock = lock.readLock();
// private Lock writeLock = lock.writeLock();
//
// public ConcurrentStorage(Storage realStorage) {
// this.realStorage = realStorage;
// }
//
// public void setRealStorage(Storage realStorage) {
// try{
// writeLock.lock();
// this.realStorage = realStorage;
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// try{
// writeLock.lock();
// return realStorage.put(mask, mno);
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public Mno remove(Mask mask) {
// try{
// writeLock.lock();
// return realStorage.remove(mask);
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public void clear() {
// try{
// writeLock.lock();
// realStorage.clear();
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public Mno lookup(String subscriber) {
// try{
// readLock.lock();
// return realStorage.lookup(subscriber);
// } finally {
// readLock.unlock();
// }
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
| import com.eyeline.mnp.ConcurrentStorage;
import com.eyeline.mnp.Storage; | package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class ConcurrentStorageTest extends BaseStorageTest {
@Override
protected Storage build() { | // Path: src/com/eyeline/mnp/ConcurrentStorage.java
// public class ConcurrentStorage implements Storage {
// private Storage realStorage;
// private ReadWriteLock lock = new ReentrantReadWriteLock();
// private Lock readLock = lock.readLock();
// private Lock writeLock = lock.writeLock();
//
// public ConcurrentStorage(Storage realStorage) {
// this.realStorage = realStorage;
// }
//
// public void setRealStorage(Storage realStorage) {
// try{
// writeLock.lock();
// this.realStorage = realStorage;
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// try{
// writeLock.lock();
// return realStorage.put(mask, mno);
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public Mno remove(Mask mask) {
// try{
// writeLock.lock();
// return realStorage.remove(mask);
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public void clear() {
// try{
// writeLock.lock();
// realStorage.clear();
// } finally {
// writeLock.unlock();
// }
// }
//
// @Override
// public Mno lookup(String subscriber) {
// try{
// readLock.lock();
// return realStorage.lookup(subscriber);
// } finally {
// readLock.unlock();
// }
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
// Path: test/com/eyeline/mnp/test/ConcurrentStorageTest.java
import com.eyeline.mnp.ConcurrentStorage;
import com.eyeline.mnp.Storage;
package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class ConcurrentStorageTest extends BaseStorageTest {
@Override
protected Storage build() { | return new ConcurrentStorage(super.build()); |
chukanov/mnp | src/com/eyeline/mnp/ConcurrentStorage.java | // Path: src/com/eyeline/mnp/mask/Mask.java
// public final class Mask {
// public static final int MAX_LENGTH = 15;
// private static final String EMPTY_MASK = "";
// public static final char WILDCARD = '?';
// private static final char ZERO = '0';
//
// private final byte[] data;
//
// public Mask(String mask) {
// this.data = mask.getBytes(Charset.forName("ASCII"));
// }
//
// private Mask(byte[] data) {
// this.data = data;
// }
//
// /**
// *
// * @param number telephone number mask
// * @return true – if number matches mask, false – if otherwise. if number is null - return false
// *
// */
// public boolean match(String number) {
// if (this.data.length == 0 || number == null) return false;
// if (number.length()!=data.length) return false;
// for (int i=0; i<number.length(); i++) {
// if (data[i] == WILDCARD) continue;
// if (data[i] != number.charAt(i)) return false;
// }
// return true;
// }
//
// /**
// * Return wider mask
// * 123 returns 12?
// * 12? returns 1??
// * 1?? returns ???
// * ??? returns null
// * @return Return wider mask
// */
// public Mask getWider() {
// int i;
// for (i=data.length-1; i>=0; i--) {
// if (data[i] != WILDCARD) {
// break;
// }
// }
// if (i < 0) {
// return null;
// } else {
// byte[] newData = new byte[data.length];
// System.arraycopy(data, 0, newData, 0, data.length);
// newData[i] = WILDCARD;
// return new Mask(newData);
// }
// }
//
// /**
// *
// * @return int lenght of the mask
// */
// public int length(){
// return data.length;
// }
//
// public char charAt(int position) {
// return (char) data[position];
// }
//
// /**
// *
// * @return string representation of mask
// */
// @Override
// public String toString() {
// return new String(data);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Mask mask = (Mask) o;
// return Arrays.equals(data, mask.data);
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(data);
// }
//
// /**
// * constructs mask from string representation with validation
// * @param mask string representation fo mask
// * @return new mask
// * @throws IllegalArgumentException if mask has a bad format
// */
// public static Mask parse(String mask) {
// String m = mask;
// if (m == null) {
// m = EMPTY_MASK;
// }
// if (m.length() > MAX_LENGTH)
// throw new IllegalArgumentException("mask: "+mask+" is longer than limit "+ MAX_LENGTH + " (by E.164 standard)");
// Mask res = new Mask(m);
// byte[] data = res.data;
// if (m.indexOf(WILDCARD)!=-1) {
// boolean gotWildcard = false;
// for (byte c: data) {
// if (c == WILDCARD && !gotWildcard) {
// gotWildcard = true;
// } else if (gotWildcard && c!=WILDCARD){
// throw new IllegalArgumentException("mask: "+m+" is invalid ("+m+")");
// } else if (!gotWildcard) {
// try {
// digit((char) c);
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(e.getMessage()+" in mask: "+mask);
// }
// }
// }
// } else {
// for (byte c: data) {
// if (!Character.isDigit(c)) {
// throw new IllegalArgumentException("mask: "+m+" is contains invalid character ("+c+")");
// }
// }
// }
// return res;
// }
//
// /**
// * @param mask mask to check validity
// * @return true if valid, false - if not
// */
// public static boolean isValid(String mask) {
// try{
// parse(mask);
// return true;
// } catch (Exception e){
// return false;
// }
// }
// /**
// *
// * @param c character from mask
// * @return digit represents current char in number
// * @throws IllegalArgumentException if char is out of supported range (0-9)
// */
// public static int digit(char c) {
// int i = c - ZERO;
// if (i < 0 || i > 9)
// throw new IllegalArgumentException("char " + c + " is out of supported range (0-9)");
// return i;
// }
// }
| import com.eyeline.mnp.mask.Mask;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock; | package com.eyeline.mnp;
/**
* @author Chukanov
*/
public class ConcurrentStorage implements Storage {
private Storage realStorage;
private ReadWriteLock lock = new ReentrantReadWriteLock();
private Lock readLock = lock.readLock();
private Lock writeLock = lock.writeLock();
public ConcurrentStorage(Storage realStorage) {
this.realStorage = realStorage;
}
public void setRealStorage(Storage realStorage) {
try{
writeLock.lock();
this.realStorage = realStorage;
} finally {
writeLock.unlock();
}
}
@Override | // Path: src/com/eyeline/mnp/mask/Mask.java
// public final class Mask {
// public static final int MAX_LENGTH = 15;
// private static final String EMPTY_MASK = "";
// public static final char WILDCARD = '?';
// private static final char ZERO = '0';
//
// private final byte[] data;
//
// public Mask(String mask) {
// this.data = mask.getBytes(Charset.forName("ASCII"));
// }
//
// private Mask(byte[] data) {
// this.data = data;
// }
//
// /**
// *
// * @param number telephone number mask
// * @return true – if number matches mask, false – if otherwise. if number is null - return false
// *
// */
// public boolean match(String number) {
// if (this.data.length == 0 || number == null) return false;
// if (number.length()!=data.length) return false;
// for (int i=0; i<number.length(); i++) {
// if (data[i] == WILDCARD) continue;
// if (data[i] != number.charAt(i)) return false;
// }
// return true;
// }
//
// /**
// * Return wider mask
// * 123 returns 12?
// * 12? returns 1??
// * 1?? returns ???
// * ??? returns null
// * @return Return wider mask
// */
// public Mask getWider() {
// int i;
// for (i=data.length-1; i>=0; i--) {
// if (data[i] != WILDCARD) {
// break;
// }
// }
// if (i < 0) {
// return null;
// } else {
// byte[] newData = new byte[data.length];
// System.arraycopy(data, 0, newData, 0, data.length);
// newData[i] = WILDCARD;
// return new Mask(newData);
// }
// }
//
// /**
// *
// * @return int lenght of the mask
// */
// public int length(){
// return data.length;
// }
//
// public char charAt(int position) {
// return (char) data[position];
// }
//
// /**
// *
// * @return string representation of mask
// */
// @Override
// public String toString() {
// return new String(data);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Mask mask = (Mask) o;
// return Arrays.equals(data, mask.data);
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(data);
// }
//
// /**
// * constructs mask from string representation with validation
// * @param mask string representation fo mask
// * @return new mask
// * @throws IllegalArgumentException if mask has a bad format
// */
// public static Mask parse(String mask) {
// String m = mask;
// if (m == null) {
// m = EMPTY_MASK;
// }
// if (m.length() > MAX_LENGTH)
// throw new IllegalArgumentException("mask: "+mask+" is longer than limit "+ MAX_LENGTH + " (by E.164 standard)");
// Mask res = new Mask(m);
// byte[] data = res.data;
// if (m.indexOf(WILDCARD)!=-1) {
// boolean gotWildcard = false;
// for (byte c: data) {
// if (c == WILDCARD && !gotWildcard) {
// gotWildcard = true;
// } else if (gotWildcard && c!=WILDCARD){
// throw new IllegalArgumentException("mask: "+m+" is invalid ("+m+")");
// } else if (!gotWildcard) {
// try {
// digit((char) c);
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(e.getMessage()+" in mask: "+mask);
// }
// }
// }
// } else {
// for (byte c: data) {
// if (!Character.isDigit(c)) {
// throw new IllegalArgumentException("mask: "+m+" is contains invalid character ("+c+")");
// }
// }
// }
// return res;
// }
//
// /**
// * @param mask mask to check validity
// * @return true if valid, false - if not
// */
// public static boolean isValid(String mask) {
// try{
// parse(mask);
// return true;
// } catch (Exception e){
// return false;
// }
// }
// /**
// *
// * @param c character from mask
// * @return digit represents current char in number
// * @throws IllegalArgumentException if char is out of supported range (0-9)
// */
// public static int digit(char c) {
// int i = c - ZERO;
// if (i < 0 || i > 9)
// throw new IllegalArgumentException("char " + c + " is out of supported range (0-9)");
// return i;
// }
// }
// Path: src/com/eyeline/mnp/ConcurrentStorage.java
import com.eyeline.mnp.mask.Mask;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
package com.eyeline.mnp;
/**
* @author Chukanov
*/
public class ConcurrentStorage implements Storage {
private Storage realStorage;
private ReadWriteLock lock = new ReentrantReadWriteLock();
private Lock readLock = lock.readLock();
private Lock writeLock = lock.writeLock();
public ConcurrentStorage(Storage realStorage) {
this.realStorage = realStorage;
}
public void setRealStorage(Storage realStorage) {
try{
writeLock.lock();
this.realStorage = realStorage;
} finally {
writeLock.unlock();
}
}
@Override | public Mno put(Mask mask, Mno mno) { |
chukanov/mnp | src/com/eyeline/mnp/parser/ZniisMnpParser.java | // Path: src/com/eyeline/utils/BlankRunnable.java
// public class BlankRunnable implements Runnable{
// @Override
// public void run() {}
// }
//
// Path: src/com/eyeline/utils/DirectoryWatchDog.java
// public abstract class DirectoryWatchDog {
// private static final Logger log = Logger.getLogger(DirectoryWatchDog.class);
//
// protected ExecutorService service =
// Executors.newSingleThreadExecutor(new NamedThreadFactory(this.getClass().getSimpleName()+"-WatchDog"));
// protected WatchService watchService;
//
// protected abstract void processChangedFile(Path filePath) throws Exception;
// protected abstract Path getWatchDir();
//
// private Runnable listener = new BlankRunnable();
//
// private boolean shutup = false;
// private Future scheduledFuture;
//
// @SuppressWarnings("unchecked")
// public synchronized void start() throws IOException {
// this.shutup = false;
// watchService = FileSystems.getDefault().newWatchService();
// final Path watchDir = getWatchDir();
// watchDir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);
// scheduledFuture = service.submit(() -> {
// while (true) {
// if (shutup) {
// return;
// }
// WatchKey key;
// try {
// key = watchService.take();
// } catch (InterruptedException x) {
// return;
// } catch (ClosedWatchServiceException e){
// log.warn("",e);
// break;
// }
// for (WatchEvent<?> event : key.pollEvents()) {
// WatchEvent.Kind<?> kind = event.kind();
// if (kind == StandardWatchEventKinds.OVERFLOW) {
// continue;
// }
// WatchEvent<Path> ev = (WatchEvent<Path>) event;
// Path filePath = ev.context();
// try {
// log.debug("changed file: "+filePath);
// this.processChangedFile(watchDir.resolve(filePath));
// } catch (Exception e) {
// log.warn("Can't process file: "+filePath, e);
// } finally {
// listener.run();
// }
// }
// boolean valid = key.reset();
// if (!valid) {
// break;
// }
// }
// });
// }
//
// public void setListener(Runnable listener) {
// this.listener = listener;
// }
//
// public synchronized void stop() {
// this.shutup = true;
// if (scheduledFuture != null) {
// scheduledFuture.cancel(false);
// }
// if (watchService != null) {
// try {
// watchService.close();
// } catch (Exception e) {
// log.warn("Can't close watchService", e);
// }
// }
// }
// }
| import com.eyeline.utils.BlankRunnable;
import com.eyeline.utils.DirectoryWatchDog;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.function.Consumer;
import java.util.stream.Stream; | String[] data = line.split(Character.toString(delimeter));
String subscriber = countryCode + data[0].trim();
String title = data[1].trim();
MnpParser.Number number = new MnpParser.Number(subscriber, title);
try {
consumer.accept(number);
} catch (Throwable t) {
System.err.print("Error at file: "+file+", line: "+line);
t.printStackTrace();
}
});
}
}
@Override
public void parseAllPorted(Consumer<Number> consumer) throws Exception {
this.parse(dir.resolve(FILENAME_ALL), consumer);
}
@Override
public void parseLastestPorted(Consumer<Number> consumer) throws Exception {
this.parse(dir.resolve(FILENAME_LASTEST), consumer);
}
@Override
public void parseReturned(Consumer<Number> consumer) throws Exception {
this.parse(dir.resolve(FILENAME_RETURNED), consumer);
}
| // Path: src/com/eyeline/utils/BlankRunnable.java
// public class BlankRunnable implements Runnable{
// @Override
// public void run() {}
// }
//
// Path: src/com/eyeline/utils/DirectoryWatchDog.java
// public abstract class DirectoryWatchDog {
// private static final Logger log = Logger.getLogger(DirectoryWatchDog.class);
//
// protected ExecutorService service =
// Executors.newSingleThreadExecutor(new NamedThreadFactory(this.getClass().getSimpleName()+"-WatchDog"));
// protected WatchService watchService;
//
// protected abstract void processChangedFile(Path filePath) throws Exception;
// protected abstract Path getWatchDir();
//
// private Runnable listener = new BlankRunnable();
//
// private boolean shutup = false;
// private Future scheduledFuture;
//
// @SuppressWarnings("unchecked")
// public synchronized void start() throws IOException {
// this.shutup = false;
// watchService = FileSystems.getDefault().newWatchService();
// final Path watchDir = getWatchDir();
// watchDir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);
// scheduledFuture = service.submit(() -> {
// while (true) {
// if (shutup) {
// return;
// }
// WatchKey key;
// try {
// key = watchService.take();
// } catch (InterruptedException x) {
// return;
// } catch (ClosedWatchServiceException e){
// log.warn("",e);
// break;
// }
// for (WatchEvent<?> event : key.pollEvents()) {
// WatchEvent.Kind<?> kind = event.kind();
// if (kind == StandardWatchEventKinds.OVERFLOW) {
// continue;
// }
// WatchEvent<Path> ev = (WatchEvent<Path>) event;
// Path filePath = ev.context();
// try {
// log.debug("changed file: "+filePath);
// this.processChangedFile(watchDir.resolve(filePath));
// } catch (Exception e) {
// log.warn("Can't process file: "+filePath, e);
// } finally {
// listener.run();
// }
// }
// boolean valid = key.reset();
// if (!valid) {
// break;
// }
// }
// });
// }
//
// public void setListener(Runnable listener) {
// this.listener = listener;
// }
//
// public synchronized void stop() {
// this.shutup = true;
// if (scheduledFuture != null) {
// scheduledFuture.cancel(false);
// }
// if (watchService != null) {
// try {
// watchService.close();
// } catch (Exception e) {
// log.warn("Can't close watchService", e);
// }
// }
// }
// }
// Path: src/com/eyeline/mnp/parser/ZniisMnpParser.java
import com.eyeline.utils.BlankRunnable;
import com.eyeline.utils.DirectoryWatchDog;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.function.Consumer;
import java.util.stream.Stream;
String[] data = line.split(Character.toString(delimeter));
String subscriber = countryCode + data[0].trim();
String title = data[1].trim();
MnpParser.Number number = new MnpParser.Number(subscriber, title);
try {
consumer.accept(number);
} catch (Throwable t) {
System.err.print("Error at file: "+file+", line: "+line);
t.printStackTrace();
}
});
}
}
@Override
public void parseAllPorted(Consumer<Number> consumer) throws Exception {
this.parse(dir.resolve(FILENAME_ALL), consumer);
}
@Override
public void parseLastestPorted(Consumer<Number> consumer) throws Exception {
this.parse(dir.resolve(FILENAME_LASTEST), consumer);
}
@Override
public void parseReturned(Consumer<Number> consumer) throws Exception {
this.parse(dir.resolve(FILENAME_RETURNED), consumer);
}
| private Runnable doOnAllUpdates = new BlankRunnable(); |
chukanov/mnp | src/com/eyeline/mnp/Storage.java | // Path: src/com/eyeline/mnp/mask/Mask.java
// public final class Mask {
// public static final int MAX_LENGTH = 15;
// private static final String EMPTY_MASK = "";
// public static final char WILDCARD = '?';
// private static final char ZERO = '0';
//
// private final byte[] data;
//
// public Mask(String mask) {
// this.data = mask.getBytes(Charset.forName("ASCII"));
// }
//
// private Mask(byte[] data) {
// this.data = data;
// }
//
// /**
// *
// * @param number telephone number mask
// * @return true – if number matches mask, false – if otherwise. if number is null - return false
// *
// */
// public boolean match(String number) {
// if (this.data.length == 0 || number == null) return false;
// if (number.length()!=data.length) return false;
// for (int i=0; i<number.length(); i++) {
// if (data[i] == WILDCARD) continue;
// if (data[i] != number.charAt(i)) return false;
// }
// return true;
// }
//
// /**
// * Return wider mask
// * 123 returns 12?
// * 12? returns 1??
// * 1?? returns ???
// * ??? returns null
// * @return Return wider mask
// */
// public Mask getWider() {
// int i;
// for (i=data.length-1; i>=0; i--) {
// if (data[i] != WILDCARD) {
// break;
// }
// }
// if (i < 0) {
// return null;
// } else {
// byte[] newData = new byte[data.length];
// System.arraycopy(data, 0, newData, 0, data.length);
// newData[i] = WILDCARD;
// return new Mask(newData);
// }
// }
//
// /**
// *
// * @return int lenght of the mask
// */
// public int length(){
// return data.length;
// }
//
// public char charAt(int position) {
// return (char) data[position];
// }
//
// /**
// *
// * @return string representation of mask
// */
// @Override
// public String toString() {
// return new String(data);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Mask mask = (Mask) o;
// return Arrays.equals(data, mask.data);
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(data);
// }
//
// /**
// * constructs mask from string representation with validation
// * @param mask string representation fo mask
// * @return new mask
// * @throws IllegalArgumentException if mask has a bad format
// */
// public static Mask parse(String mask) {
// String m = mask;
// if (m == null) {
// m = EMPTY_MASK;
// }
// if (m.length() > MAX_LENGTH)
// throw new IllegalArgumentException("mask: "+mask+" is longer than limit "+ MAX_LENGTH + " (by E.164 standard)");
// Mask res = new Mask(m);
// byte[] data = res.data;
// if (m.indexOf(WILDCARD)!=-1) {
// boolean gotWildcard = false;
// for (byte c: data) {
// if (c == WILDCARD && !gotWildcard) {
// gotWildcard = true;
// } else if (gotWildcard && c!=WILDCARD){
// throw new IllegalArgumentException("mask: "+m+" is invalid ("+m+")");
// } else if (!gotWildcard) {
// try {
// digit((char) c);
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(e.getMessage()+" in mask: "+mask);
// }
// }
// }
// } else {
// for (byte c: data) {
// if (!Character.isDigit(c)) {
// throw new IllegalArgumentException("mask: "+m+" is contains invalid character ("+c+")");
// }
// }
// }
// return res;
// }
//
// /**
// * @param mask mask to check validity
// * @return true if valid, false - if not
// */
// public static boolean isValid(String mask) {
// try{
// parse(mask);
// return true;
// } catch (Exception e){
// return false;
// }
// }
// /**
// *
// * @param c character from mask
// * @return digit represents current char in number
// * @throws IllegalArgumentException if char is out of supported range (0-9)
// */
// public static int digit(char c) {
// int i = c - ZERO;
// if (i < 0 || i > 9)
// throw new IllegalArgumentException("char " + c + " is out of supported range (0-9)");
// return i;
// }
// }
| import com.eyeline.mnp.mask.Mask; | package com.eyeline.mnp;
/**
* Represents MNO storage with ability to retrieve MNP by phone number
* @author Chukanov
*/
public interface Storage {
/**
* Lookup MNO by phone number
* @param subscriber phone number
* @return mno if exists, otherwise null
*/
public Mno lookup(String subscriber);
/**
* Adds a new mask to mno in storage
* but only if mask is not exists
* @param mask new mask
* @param mno mno
* @return Mno – old value if present
*/ | // Path: src/com/eyeline/mnp/mask/Mask.java
// public final class Mask {
// public static final int MAX_LENGTH = 15;
// private static final String EMPTY_MASK = "";
// public static final char WILDCARD = '?';
// private static final char ZERO = '0';
//
// private final byte[] data;
//
// public Mask(String mask) {
// this.data = mask.getBytes(Charset.forName("ASCII"));
// }
//
// private Mask(byte[] data) {
// this.data = data;
// }
//
// /**
// *
// * @param number telephone number mask
// * @return true – if number matches mask, false – if otherwise. if number is null - return false
// *
// */
// public boolean match(String number) {
// if (this.data.length == 0 || number == null) return false;
// if (number.length()!=data.length) return false;
// for (int i=0; i<number.length(); i++) {
// if (data[i] == WILDCARD) continue;
// if (data[i] != number.charAt(i)) return false;
// }
// return true;
// }
//
// /**
// * Return wider mask
// * 123 returns 12?
// * 12? returns 1??
// * 1?? returns ???
// * ??? returns null
// * @return Return wider mask
// */
// public Mask getWider() {
// int i;
// for (i=data.length-1; i>=0; i--) {
// if (data[i] != WILDCARD) {
// break;
// }
// }
// if (i < 0) {
// return null;
// } else {
// byte[] newData = new byte[data.length];
// System.arraycopy(data, 0, newData, 0, data.length);
// newData[i] = WILDCARD;
// return new Mask(newData);
// }
// }
//
// /**
// *
// * @return int lenght of the mask
// */
// public int length(){
// return data.length;
// }
//
// public char charAt(int position) {
// return (char) data[position];
// }
//
// /**
// *
// * @return string representation of mask
// */
// @Override
// public String toString() {
// return new String(data);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Mask mask = (Mask) o;
// return Arrays.equals(data, mask.data);
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(data);
// }
//
// /**
// * constructs mask from string representation with validation
// * @param mask string representation fo mask
// * @return new mask
// * @throws IllegalArgumentException if mask has a bad format
// */
// public static Mask parse(String mask) {
// String m = mask;
// if (m == null) {
// m = EMPTY_MASK;
// }
// if (m.length() > MAX_LENGTH)
// throw new IllegalArgumentException("mask: "+mask+" is longer than limit "+ MAX_LENGTH + " (by E.164 standard)");
// Mask res = new Mask(m);
// byte[] data = res.data;
// if (m.indexOf(WILDCARD)!=-1) {
// boolean gotWildcard = false;
// for (byte c: data) {
// if (c == WILDCARD && !gotWildcard) {
// gotWildcard = true;
// } else if (gotWildcard && c!=WILDCARD){
// throw new IllegalArgumentException("mask: "+m+" is invalid ("+m+")");
// } else if (!gotWildcard) {
// try {
// digit((char) c);
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(e.getMessage()+" in mask: "+mask);
// }
// }
// }
// } else {
// for (byte c: data) {
// if (!Character.isDigit(c)) {
// throw new IllegalArgumentException("mask: "+m+" is contains invalid character ("+c+")");
// }
// }
// }
// return res;
// }
//
// /**
// * @param mask mask to check validity
// * @return true if valid, false - if not
// */
// public static boolean isValid(String mask) {
// try{
// parse(mask);
// return true;
// } catch (Exception e){
// return false;
// }
// }
// /**
// *
// * @param c character from mask
// * @return digit represents current char in number
// * @throws IllegalArgumentException if char is out of supported range (0-9)
// */
// public static int digit(char c) {
// int i = c - ZERO;
// if (i < 0 || i > 9)
// throw new IllegalArgumentException("char " + c + " is out of supported range (0-9)");
// return i;
// }
// }
// Path: src/com/eyeline/mnp/Storage.java
import com.eyeline.mnp.mask.Mask;
package com.eyeline.mnp;
/**
* Represents MNO storage with ability to retrieve MNP by phone number
* @author Chukanov
*/
public interface Storage {
/**
* Lookup MNO by phone number
* @param subscriber phone number
* @return mno if exists, otherwise null
*/
public Mno lookup(String subscriber);
/**
* Adds a new mask to mno in storage
* but only if mask is not exists
* @param mask new mask
* @param mno mno
* @return Mno – old value if present
*/ | public Mno put(Mask mask, Mno mno); |
chukanov/mnp | src/com/eyeline/mnp/HashMapStringStorage.java | // Path: src/com/eyeline/mnp/mask/Mask.java
// public final class Mask {
// public static final int MAX_LENGTH = 15;
// private static final String EMPTY_MASK = "";
// public static final char WILDCARD = '?';
// private static final char ZERO = '0';
//
// private final byte[] data;
//
// public Mask(String mask) {
// this.data = mask.getBytes(Charset.forName("ASCII"));
// }
//
// private Mask(byte[] data) {
// this.data = data;
// }
//
// /**
// *
// * @param number telephone number mask
// * @return true – if number matches mask, false – if otherwise. if number is null - return false
// *
// */
// public boolean match(String number) {
// if (this.data.length == 0 || number == null) return false;
// if (number.length()!=data.length) return false;
// for (int i=0; i<number.length(); i++) {
// if (data[i] == WILDCARD) continue;
// if (data[i] != number.charAt(i)) return false;
// }
// return true;
// }
//
// /**
// * Return wider mask
// * 123 returns 12?
// * 12? returns 1??
// * 1?? returns ???
// * ??? returns null
// * @return Return wider mask
// */
// public Mask getWider() {
// int i;
// for (i=data.length-1; i>=0; i--) {
// if (data[i] != WILDCARD) {
// break;
// }
// }
// if (i < 0) {
// return null;
// } else {
// byte[] newData = new byte[data.length];
// System.arraycopy(data, 0, newData, 0, data.length);
// newData[i] = WILDCARD;
// return new Mask(newData);
// }
// }
//
// /**
// *
// * @return int lenght of the mask
// */
// public int length(){
// return data.length;
// }
//
// public char charAt(int position) {
// return (char) data[position];
// }
//
// /**
// *
// * @return string representation of mask
// */
// @Override
// public String toString() {
// return new String(data);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Mask mask = (Mask) o;
// return Arrays.equals(data, mask.data);
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(data);
// }
//
// /**
// * constructs mask from string representation with validation
// * @param mask string representation fo mask
// * @return new mask
// * @throws IllegalArgumentException if mask has a bad format
// */
// public static Mask parse(String mask) {
// String m = mask;
// if (m == null) {
// m = EMPTY_MASK;
// }
// if (m.length() > MAX_LENGTH)
// throw new IllegalArgumentException("mask: "+mask+" is longer than limit "+ MAX_LENGTH + " (by E.164 standard)");
// Mask res = new Mask(m);
// byte[] data = res.data;
// if (m.indexOf(WILDCARD)!=-1) {
// boolean gotWildcard = false;
// for (byte c: data) {
// if (c == WILDCARD && !gotWildcard) {
// gotWildcard = true;
// } else if (gotWildcard && c!=WILDCARD){
// throw new IllegalArgumentException("mask: "+m+" is invalid ("+m+")");
// } else if (!gotWildcard) {
// try {
// digit((char) c);
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(e.getMessage()+" in mask: "+mask);
// }
// }
// }
// } else {
// for (byte c: data) {
// if (!Character.isDigit(c)) {
// throw new IllegalArgumentException("mask: "+m+" is contains invalid character ("+c+")");
// }
// }
// }
// return res;
// }
//
// /**
// * @param mask mask to check validity
// * @return true if valid, false - if not
// */
// public static boolean isValid(String mask) {
// try{
// parse(mask);
// return true;
// } catch (Exception e){
// return false;
// }
// }
// /**
// *
// * @param c character from mask
// * @return digit represents current char in number
// * @throws IllegalArgumentException if char is out of supported range (0-9)
// */
// public static int digit(char c) {
// int i = c - ZERO;
// if (i < 0 || i > 9)
// throw new IllegalArgumentException("char " + c + " is out of supported range (0-9)");
// return i;
// }
// }
| import com.eyeline.mnp.mask.Mask;
import java.util.HashMap;
import java.util.Map; | package com.eyeline.mnp;
/**
* Mno storage based on HashMap<String,Mno>
* @author Chukanov
*/
public class HashMapStringStorage implements Storage {
private Map<String, Mno> storage = new HashMap<>();
@Override
public Mno lookup(String subscriber) {
if (subscriber == null) return null;
Mno result = storage.get(subscriber);
if (result!=null) {
return result;
}
StringBuilder mask = new StringBuilder(subscriber);
for (int i=subscriber.length()-1; i>=0; i--) { | // Path: src/com/eyeline/mnp/mask/Mask.java
// public final class Mask {
// public static final int MAX_LENGTH = 15;
// private static final String EMPTY_MASK = "";
// public static final char WILDCARD = '?';
// private static final char ZERO = '0';
//
// private final byte[] data;
//
// public Mask(String mask) {
// this.data = mask.getBytes(Charset.forName("ASCII"));
// }
//
// private Mask(byte[] data) {
// this.data = data;
// }
//
// /**
// *
// * @param number telephone number mask
// * @return true – if number matches mask, false – if otherwise. if number is null - return false
// *
// */
// public boolean match(String number) {
// if (this.data.length == 0 || number == null) return false;
// if (number.length()!=data.length) return false;
// for (int i=0; i<number.length(); i++) {
// if (data[i] == WILDCARD) continue;
// if (data[i] != number.charAt(i)) return false;
// }
// return true;
// }
//
// /**
// * Return wider mask
// * 123 returns 12?
// * 12? returns 1??
// * 1?? returns ???
// * ??? returns null
// * @return Return wider mask
// */
// public Mask getWider() {
// int i;
// for (i=data.length-1; i>=0; i--) {
// if (data[i] != WILDCARD) {
// break;
// }
// }
// if (i < 0) {
// return null;
// } else {
// byte[] newData = new byte[data.length];
// System.arraycopy(data, 0, newData, 0, data.length);
// newData[i] = WILDCARD;
// return new Mask(newData);
// }
// }
//
// /**
// *
// * @return int lenght of the mask
// */
// public int length(){
// return data.length;
// }
//
// public char charAt(int position) {
// return (char) data[position];
// }
//
// /**
// *
// * @return string representation of mask
// */
// @Override
// public String toString() {
// return new String(data);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Mask mask = (Mask) o;
// return Arrays.equals(data, mask.data);
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(data);
// }
//
// /**
// * constructs mask from string representation with validation
// * @param mask string representation fo mask
// * @return new mask
// * @throws IllegalArgumentException if mask has a bad format
// */
// public static Mask parse(String mask) {
// String m = mask;
// if (m == null) {
// m = EMPTY_MASK;
// }
// if (m.length() > MAX_LENGTH)
// throw new IllegalArgumentException("mask: "+mask+" is longer than limit "+ MAX_LENGTH + " (by E.164 standard)");
// Mask res = new Mask(m);
// byte[] data = res.data;
// if (m.indexOf(WILDCARD)!=-1) {
// boolean gotWildcard = false;
// for (byte c: data) {
// if (c == WILDCARD && !gotWildcard) {
// gotWildcard = true;
// } else if (gotWildcard && c!=WILDCARD){
// throw new IllegalArgumentException("mask: "+m+" is invalid ("+m+")");
// } else if (!gotWildcard) {
// try {
// digit((char) c);
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(e.getMessage()+" in mask: "+mask);
// }
// }
// }
// } else {
// for (byte c: data) {
// if (!Character.isDigit(c)) {
// throw new IllegalArgumentException("mask: "+m+" is contains invalid character ("+c+")");
// }
// }
// }
// return res;
// }
//
// /**
// * @param mask mask to check validity
// * @return true if valid, false - if not
// */
// public static boolean isValid(String mask) {
// try{
// parse(mask);
// return true;
// } catch (Exception e){
// return false;
// }
// }
// /**
// *
// * @param c character from mask
// * @return digit represents current char in number
// * @throws IllegalArgumentException if char is out of supported range (0-9)
// */
// public static int digit(char c) {
// int i = c - ZERO;
// if (i < 0 || i > 9)
// throw new IllegalArgumentException("char " + c + " is out of supported range (0-9)");
// return i;
// }
// }
// Path: src/com/eyeline/mnp/HashMapStringStorage.java
import com.eyeline.mnp.mask.Mask;
import java.util.HashMap;
import java.util.Map;
package com.eyeline.mnp;
/**
* Mno storage based on HashMap<String,Mno>
* @author Chukanov
*/
public class HashMapStringStorage implements Storage {
private Map<String, Mno> storage = new HashMap<>();
@Override
public Mno lookup(String subscriber) {
if (subscriber == null) return null;
Mno result = storage.get(subscriber);
if (result!=null) {
return result;
}
StringBuilder mask = new StringBuilder(subscriber);
for (int i=subscriber.length()-1; i>=0; i--) { | mask.replace(i, i+1, Character.toString(Mask.WILDCARD)); |
chukanov/mnp | src/com/eyeline/mnp/parser/MasksParser.java | // Path: src/com/eyeline/mnp/mask/Mask.java
// public final class Mask {
// public static final int MAX_LENGTH = 15;
// private static final String EMPTY_MASK = "";
// public static final char WILDCARD = '?';
// private static final char ZERO = '0';
//
// private final byte[] data;
//
// public Mask(String mask) {
// this.data = mask.getBytes(Charset.forName("ASCII"));
// }
//
// private Mask(byte[] data) {
// this.data = data;
// }
//
// /**
// *
// * @param number telephone number mask
// * @return true – if number matches mask, false – if otherwise. if number is null - return false
// *
// */
// public boolean match(String number) {
// if (this.data.length == 0 || number == null) return false;
// if (number.length()!=data.length) return false;
// for (int i=0; i<number.length(); i++) {
// if (data[i] == WILDCARD) continue;
// if (data[i] != number.charAt(i)) return false;
// }
// return true;
// }
//
// /**
// * Return wider mask
// * 123 returns 12?
// * 12? returns 1??
// * 1?? returns ???
// * ??? returns null
// * @return Return wider mask
// */
// public Mask getWider() {
// int i;
// for (i=data.length-1; i>=0; i--) {
// if (data[i] != WILDCARD) {
// break;
// }
// }
// if (i < 0) {
// return null;
// } else {
// byte[] newData = new byte[data.length];
// System.arraycopy(data, 0, newData, 0, data.length);
// newData[i] = WILDCARD;
// return new Mask(newData);
// }
// }
//
// /**
// *
// * @return int lenght of the mask
// */
// public int length(){
// return data.length;
// }
//
// public char charAt(int position) {
// return (char) data[position];
// }
//
// /**
// *
// * @return string representation of mask
// */
// @Override
// public String toString() {
// return new String(data);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Mask mask = (Mask) o;
// return Arrays.equals(data, mask.data);
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(data);
// }
//
// /**
// * constructs mask from string representation with validation
// * @param mask string representation fo mask
// * @return new mask
// * @throws IllegalArgumentException if mask has a bad format
// */
// public static Mask parse(String mask) {
// String m = mask;
// if (m == null) {
// m = EMPTY_MASK;
// }
// if (m.length() > MAX_LENGTH)
// throw new IllegalArgumentException("mask: "+mask+" is longer than limit "+ MAX_LENGTH + " (by E.164 standard)");
// Mask res = new Mask(m);
// byte[] data = res.data;
// if (m.indexOf(WILDCARD)!=-1) {
// boolean gotWildcard = false;
// for (byte c: data) {
// if (c == WILDCARD && !gotWildcard) {
// gotWildcard = true;
// } else if (gotWildcard && c!=WILDCARD){
// throw new IllegalArgumentException("mask: "+m+" is invalid ("+m+")");
// } else if (!gotWildcard) {
// try {
// digit((char) c);
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(e.getMessage()+" in mask: "+mask);
// }
// }
// }
// } else {
// for (byte c: data) {
// if (!Character.isDigit(c)) {
// throw new IllegalArgumentException("mask: "+m+" is contains invalid character ("+c+")");
// }
// }
// }
// return res;
// }
//
// /**
// * @param mask mask to check validity
// * @return true if valid, false - if not
// */
// public static boolean isValid(String mask) {
// try{
// parse(mask);
// return true;
// } catch (Exception e){
// return false;
// }
// }
// /**
// *
// * @param c character from mask
// * @return digit represents current char in number
// * @throws IllegalArgumentException if char is out of supported range (0-9)
// */
// public static int digit(char c) {
// int i = c - ZERO;
// if (i < 0 || i > 9)
// throw new IllegalArgumentException("char " + c + " is out of supported range (0-9)");
// return i;
// }
// }
| import com.eyeline.mnp.mask.Mask;
import java.util.Set;
import java.util.function.Consumer; | package com.eyeline.mnp.parser;
/**
* @author Chukanov
*/
public interface MasksParser {
public void parse(Consumer<MnoInfo> consumer) throws Exception;
public static class MnoInfo {
private String title;
private String area;
private String country; | // Path: src/com/eyeline/mnp/mask/Mask.java
// public final class Mask {
// public static final int MAX_LENGTH = 15;
// private static final String EMPTY_MASK = "";
// public static final char WILDCARD = '?';
// private static final char ZERO = '0';
//
// private final byte[] data;
//
// public Mask(String mask) {
// this.data = mask.getBytes(Charset.forName("ASCII"));
// }
//
// private Mask(byte[] data) {
// this.data = data;
// }
//
// /**
// *
// * @param number telephone number mask
// * @return true – if number matches mask, false – if otherwise. if number is null - return false
// *
// */
// public boolean match(String number) {
// if (this.data.length == 0 || number == null) return false;
// if (number.length()!=data.length) return false;
// for (int i=0; i<number.length(); i++) {
// if (data[i] == WILDCARD) continue;
// if (data[i] != number.charAt(i)) return false;
// }
// return true;
// }
//
// /**
// * Return wider mask
// * 123 returns 12?
// * 12? returns 1??
// * 1?? returns ???
// * ??? returns null
// * @return Return wider mask
// */
// public Mask getWider() {
// int i;
// for (i=data.length-1; i>=0; i--) {
// if (data[i] != WILDCARD) {
// break;
// }
// }
// if (i < 0) {
// return null;
// } else {
// byte[] newData = new byte[data.length];
// System.arraycopy(data, 0, newData, 0, data.length);
// newData[i] = WILDCARD;
// return new Mask(newData);
// }
// }
//
// /**
// *
// * @return int lenght of the mask
// */
// public int length(){
// return data.length;
// }
//
// public char charAt(int position) {
// return (char) data[position];
// }
//
// /**
// *
// * @return string representation of mask
// */
// @Override
// public String toString() {
// return new String(data);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Mask mask = (Mask) o;
// return Arrays.equals(data, mask.data);
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(data);
// }
//
// /**
// * constructs mask from string representation with validation
// * @param mask string representation fo mask
// * @return new mask
// * @throws IllegalArgumentException if mask has a bad format
// */
// public static Mask parse(String mask) {
// String m = mask;
// if (m == null) {
// m = EMPTY_MASK;
// }
// if (m.length() > MAX_LENGTH)
// throw new IllegalArgumentException("mask: "+mask+" is longer than limit "+ MAX_LENGTH + " (by E.164 standard)");
// Mask res = new Mask(m);
// byte[] data = res.data;
// if (m.indexOf(WILDCARD)!=-1) {
// boolean gotWildcard = false;
// for (byte c: data) {
// if (c == WILDCARD && !gotWildcard) {
// gotWildcard = true;
// } else if (gotWildcard && c!=WILDCARD){
// throw new IllegalArgumentException("mask: "+m+" is invalid ("+m+")");
// } else if (!gotWildcard) {
// try {
// digit((char) c);
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(e.getMessage()+" in mask: "+mask);
// }
// }
// }
// } else {
// for (byte c: data) {
// if (!Character.isDigit(c)) {
// throw new IllegalArgumentException("mask: "+m+" is contains invalid character ("+c+")");
// }
// }
// }
// return res;
// }
//
// /**
// * @param mask mask to check validity
// * @return true if valid, false - if not
// */
// public static boolean isValid(String mask) {
// try{
// parse(mask);
// return true;
// } catch (Exception e){
// return false;
// }
// }
// /**
// *
// * @param c character from mask
// * @return digit represents current char in number
// * @throws IllegalArgumentException if char is out of supported range (0-9)
// */
// public static int digit(char c) {
// int i = c - ZERO;
// if (i < 0 || i > 9)
// throw new IllegalArgumentException("char " + c + " is out of supported range (0-9)");
// return i;
// }
// }
// Path: src/com/eyeline/mnp/parser/MasksParser.java
import com.eyeline.mnp.mask.Mask;
import java.util.Set;
import java.util.function.Consumer;
package com.eyeline.mnp.parser;
/**
* @author Chukanov
*/
public interface MasksParser {
public void parse(Consumer<MnoInfo> consumer) throws Exception;
public static class MnoInfo {
private String title;
private String area;
private String country; | private Set<Mask> masks; |
chukanov/mnp | src/com/eyeline/mnp/ChainStorage.java | // Path: src/com/eyeline/mnp/mask/Mask.java
// public final class Mask {
// public static final int MAX_LENGTH = 15;
// private static final String EMPTY_MASK = "";
// public static final char WILDCARD = '?';
// private static final char ZERO = '0';
//
// private final byte[] data;
//
// public Mask(String mask) {
// this.data = mask.getBytes(Charset.forName("ASCII"));
// }
//
// private Mask(byte[] data) {
// this.data = data;
// }
//
// /**
// *
// * @param number telephone number mask
// * @return true – if number matches mask, false – if otherwise. if number is null - return false
// *
// */
// public boolean match(String number) {
// if (this.data.length == 0 || number == null) return false;
// if (number.length()!=data.length) return false;
// for (int i=0; i<number.length(); i++) {
// if (data[i] == WILDCARD) continue;
// if (data[i] != number.charAt(i)) return false;
// }
// return true;
// }
//
// /**
// * Return wider mask
// * 123 returns 12?
// * 12? returns 1??
// * 1?? returns ???
// * ??? returns null
// * @return Return wider mask
// */
// public Mask getWider() {
// int i;
// for (i=data.length-1; i>=0; i--) {
// if (data[i] != WILDCARD) {
// break;
// }
// }
// if (i < 0) {
// return null;
// } else {
// byte[] newData = new byte[data.length];
// System.arraycopy(data, 0, newData, 0, data.length);
// newData[i] = WILDCARD;
// return new Mask(newData);
// }
// }
//
// /**
// *
// * @return int lenght of the mask
// */
// public int length(){
// return data.length;
// }
//
// public char charAt(int position) {
// return (char) data[position];
// }
//
// /**
// *
// * @return string representation of mask
// */
// @Override
// public String toString() {
// return new String(data);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Mask mask = (Mask) o;
// return Arrays.equals(data, mask.data);
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(data);
// }
//
// /**
// * constructs mask from string representation with validation
// * @param mask string representation fo mask
// * @return new mask
// * @throws IllegalArgumentException if mask has a bad format
// */
// public static Mask parse(String mask) {
// String m = mask;
// if (m == null) {
// m = EMPTY_MASK;
// }
// if (m.length() > MAX_LENGTH)
// throw new IllegalArgumentException("mask: "+mask+" is longer than limit "+ MAX_LENGTH + " (by E.164 standard)");
// Mask res = new Mask(m);
// byte[] data = res.data;
// if (m.indexOf(WILDCARD)!=-1) {
// boolean gotWildcard = false;
// for (byte c: data) {
// if (c == WILDCARD && !gotWildcard) {
// gotWildcard = true;
// } else if (gotWildcard && c!=WILDCARD){
// throw new IllegalArgumentException("mask: "+m+" is invalid ("+m+")");
// } else if (!gotWildcard) {
// try {
// digit((char) c);
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(e.getMessage()+" in mask: "+mask);
// }
// }
// }
// } else {
// for (byte c: data) {
// if (!Character.isDigit(c)) {
// throw new IllegalArgumentException("mask: "+m+" is contains invalid character ("+c+")");
// }
// }
// }
// return res;
// }
//
// /**
// * @param mask mask to check validity
// * @return true if valid, false - if not
// */
// public static boolean isValid(String mask) {
// try{
// parse(mask);
// return true;
// } catch (Exception e){
// return false;
// }
// }
// /**
// *
// * @param c character from mask
// * @return digit represents current char in number
// * @throws IllegalArgumentException if char is out of supported range (0-9)
// */
// public static int digit(char c) {
// int i = c - ZERO;
// if (i < 0 || i > 9)
// throw new IllegalArgumentException("char " + c + " is out of supported range (0-9)");
// return i;
// }
// }
| import com.eyeline.mnp.mask.Mask; | package com.eyeline.mnp;
/**
* Chained storage
* @author Chukanov
*/
public class ChainStorage implements Storage{
private Storage[] storages;
public ChainStorage(Storage... storages) {
this.storages = storages;
}
@Override
public Mno lookup(String subscriber) {
for (Storage storage: storages){
Mno mno = null;
if(storage!=null) {
mno = storage.lookup(subscriber);
}
if (mno!=null) return mno;
}
return null;
}
@Override | // Path: src/com/eyeline/mnp/mask/Mask.java
// public final class Mask {
// public static final int MAX_LENGTH = 15;
// private static final String EMPTY_MASK = "";
// public static final char WILDCARD = '?';
// private static final char ZERO = '0';
//
// private final byte[] data;
//
// public Mask(String mask) {
// this.data = mask.getBytes(Charset.forName("ASCII"));
// }
//
// private Mask(byte[] data) {
// this.data = data;
// }
//
// /**
// *
// * @param number telephone number mask
// * @return true – if number matches mask, false – if otherwise. if number is null - return false
// *
// */
// public boolean match(String number) {
// if (this.data.length == 0 || number == null) return false;
// if (number.length()!=data.length) return false;
// for (int i=0; i<number.length(); i++) {
// if (data[i] == WILDCARD) continue;
// if (data[i] != number.charAt(i)) return false;
// }
// return true;
// }
//
// /**
// * Return wider mask
// * 123 returns 12?
// * 12? returns 1??
// * 1?? returns ???
// * ??? returns null
// * @return Return wider mask
// */
// public Mask getWider() {
// int i;
// for (i=data.length-1; i>=0; i--) {
// if (data[i] != WILDCARD) {
// break;
// }
// }
// if (i < 0) {
// return null;
// } else {
// byte[] newData = new byte[data.length];
// System.arraycopy(data, 0, newData, 0, data.length);
// newData[i] = WILDCARD;
// return new Mask(newData);
// }
// }
//
// /**
// *
// * @return int lenght of the mask
// */
// public int length(){
// return data.length;
// }
//
// public char charAt(int position) {
// return (char) data[position];
// }
//
// /**
// *
// * @return string representation of mask
// */
// @Override
// public String toString() {
// return new String(data);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Mask mask = (Mask) o;
// return Arrays.equals(data, mask.data);
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(data);
// }
//
// /**
// * constructs mask from string representation with validation
// * @param mask string representation fo mask
// * @return new mask
// * @throws IllegalArgumentException if mask has a bad format
// */
// public static Mask parse(String mask) {
// String m = mask;
// if (m == null) {
// m = EMPTY_MASK;
// }
// if (m.length() > MAX_LENGTH)
// throw new IllegalArgumentException("mask: "+mask+" is longer than limit "+ MAX_LENGTH + " (by E.164 standard)");
// Mask res = new Mask(m);
// byte[] data = res.data;
// if (m.indexOf(WILDCARD)!=-1) {
// boolean gotWildcard = false;
// for (byte c: data) {
// if (c == WILDCARD && !gotWildcard) {
// gotWildcard = true;
// } else if (gotWildcard && c!=WILDCARD){
// throw new IllegalArgumentException("mask: "+m+" is invalid ("+m+")");
// } else if (!gotWildcard) {
// try {
// digit((char) c);
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(e.getMessage()+" in mask: "+mask);
// }
// }
// }
// } else {
// for (byte c: data) {
// if (!Character.isDigit(c)) {
// throw new IllegalArgumentException("mask: "+m+" is contains invalid character ("+c+")");
// }
// }
// }
// return res;
// }
//
// /**
// * @param mask mask to check validity
// * @return true if valid, false - if not
// */
// public static boolean isValid(String mask) {
// try{
// parse(mask);
// return true;
// } catch (Exception e){
// return false;
// }
// }
// /**
// *
// * @param c character from mask
// * @return digit represents current char in number
// * @throws IllegalArgumentException if char is out of supported range (0-9)
// */
// public static int digit(char c) {
// int i = c - ZERO;
// if (i < 0 || i > 9)
// throw new IllegalArgumentException("char " + c + " is out of supported range (0-9)");
// return i;
// }
// }
// Path: src/com/eyeline/mnp/ChainStorage.java
import com.eyeline.mnp.mask.Mask;
package com.eyeline.mnp;
/**
* Chained storage
* @author Chukanov
*/
public class ChainStorage implements Storage{
private Storage[] storages;
public ChainStorage(Storage... storages) {
this.storages = storages;
}
@Override
public Mno lookup(String subscriber) {
for (Storage storage: storages){
Mno mno = null;
if(storage!=null) {
mno = storage.lookup(subscriber);
}
if (mno!=null) return mno;
}
return null;
}
@Override | public Mno put(Mask mask, Mno mno) { |
chukanov/mnp | test/com/eyeline/mnp/test/HashMapStringStorageTest.java | // Path: src/com/eyeline/mnp/HashMapStringStorage.java
// public class HashMapStringStorage implements Storage {
// private Map<String, Mno> storage = new HashMap<>();
//
// @Override
// public Mno lookup(String subscriber) {
// if (subscriber == null) return null;
// Mno result = storage.get(subscriber);
// if (result!=null) {
// return result;
// }
// StringBuilder mask = new StringBuilder(subscriber);
// for (int i=subscriber.length()-1; i>=0; i--) {
// mask.replace(i, i+1, Character.toString(Mask.WILDCARD));
// result = storage.get(mask.toString());
// if (result!=null) return result;
// }
// return null;
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// if (mask == null || mno == null) return null;
// return storage.put(mask.toString(), mno);
// }
//
// @Override
// public Mno remove(Mask mask) {
// if (mask == null) return null;
// return storage.remove(mask.toString());
// }
//
// @Override
// public void clear() {
// storage = new HashMap<>();
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
| import com.eyeline.mnp.HashMapStringStorage;
import com.eyeline.mnp.Storage; | package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class HashMapStringStorageTest extends BaseStorageTest {
@Override | // Path: src/com/eyeline/mnp/HashMapStringStorage.java
// public class HashMapStringStorage implements Storage {
// private Map<String, Mno> storage = new HashMap<>();
//
// @Override
// public Mno lookup(String subscriber) {
// if (subscriber == null) return null;
// Mno result = storage.get(subscriber);
// if (result!=null) {
// return result;
// }
// StringBuilder mask = new StringBuilder(subscriber);
// for (int i=subscriber.length()-1; i>=0; i--) {
// mask.replace(i, i+1, Character.toString(Mask.WILDCARD));
// result = storage.get(mask.toString());
// if (result!=null) return result;
// }
// return null;
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// if (mask == null || mno == null) return null;
// return storage.put(mask.toString(), mno);
// }
//
// @Override
// public Mno remove(Mask mask) {
// if (mask == null) return null;
// return storage.remove(mask.toString());
// }
//
// @Override
// public void clear() {
// storage = new HashMap<>();
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
// Path: test/com/eyeline/mnp/test/HashMapStringStorageTest.java
import com.eyeline.mnp.HashMapStringStorage;
import com.eyeline.mnp.Storage;
package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class HashMapStringStorageTest extends BaseStorageTest {
@Override | protected Storage build() { |
chukanov/mnp | test/com/eyeline/mnp/test/HashMapStringStorageTest.java | // Path: src/com/eyeline/mnp/HashMapStringStorage.java
// public class HashMapStringStorage implements Storage {
// private Map<String, Mno> storage = new HashMap<>();
//
// @Override
// public Mno lookup(String subscriber) {
// if (subscriber == null) return null;
// Mno result = storage.get(subscriber);
// if (result!=null) {
// return result;
// }
// StringBuilder mask = new StringBuilder(subscriber);
// for (int i=subscriber.length()-1; i>=0; i--) {
// mask.replace(i, i+1, Character.toString(Mask.WILDCARD));
// result = storage.get(mask.toString());
// if (result!=null) return result;
// }
// return null;
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// if (mask == null || mno == null) return null;
// return storage.put(mask.toString(), mno);
// }
//
// @Override
// public Mno remove(Mask mask) {
// if (mask == null) return null;
// return storage.remove(mask.toString());
// }
//
// @Override
// public void clear() {
// storage = new HashMap<>();
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
| import com.eyeline.mnp.HashMapStringStorage;
import com.eyeline.mnp.Storage; | package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class HashMapStringStorageTest extends BaseStorageTest {
@Override
protected Storage build() { | // Path: src/com/eyeline/mnp/HashMapStringStorage.java
// public class HashMapStringStorage implements Storage {
// private Map<String, Mno> storage = new HashMap<>();
//
// @Override
// public Mno lookup(String subscriber) {
// if (subscriber == null) return null;
// Mno result = storage.get(subscriber);
// if (result!=null) {
// return result;
// }
// StringBuilder mask = new StringBuilder(subscriber);
// for (int i=subscriber.length()-1; i>=0; i--) {
// mask.replace(i, i+1, Character.toString(Mask.WILDCARD));
// result = storage.get(mask.toString());
// if (result!=null) return result;
// }
// return null;
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// if (mask == null || mno == null) return null;
// return storage.put(mask.toString(), mno);
// }
//
// @Override
// public Mno remove(Mask mask) {
// if (mask == null) return null;
// return storage.remove(mask.toString());
// }
//
// @Override
// public void clear() {
// storage = new HashMap<>();
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
// Path: test/com/eyeline/mnp/test/HashMapStringStorageTest.java
import com.eyeline.mnp.HashMapStringStorage;
import com.eyeline.mnp.Storage;
package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class HashMapStringStorageTest extends BaseStorageTest {
@Override
protected Storage build() { | return new HashMapStringStorage(); |
chukanov/mnp | test/com/eyeline/mnp/test/MaskTest.java | // Path: src/com/eyeline/mnp/mask/Mask.java
// public final class Mask {
// public static final int MAX_LENGTH = 15;
// private static final String EMPTY_MASK = "";
// public static final char WILDCARD = '?';
// private static final char ZERO = '0';
//
// private final byte[] data;
//
// public Mask(String mask) {
// this.data = mask.getBytes(Charset.forName("ASCII"));
// }
//
// private Mask(byte[] data) {
// this.data = data;
// }
//
// /**
// *
// * @param number telephone number mask
// * @return true – if number matches mask, false – if otherwise. if number is null - return false
// *
// */
// public boolean match(String number) {
// if (this.data.length == 0 || number == null) return false;
// if (number.length()!=data.length) return false;
// for (int i=0; i<number.length(); i++) {
// if (data[i] == WILDCARD) continue;
// if (data[i] != number.charAt(i)) return false;
// }
// return true;
// }
//
// /**
// * Return wider mask
// * 123 returns 12?
// * 12? returns 1??
// * 1?? returns ???
// * ??? returns null
// * @return Return wider mask
// */
// public Mask getWider() {
// int i;
// for (i=data.length-1; i>=0; i--) {
// if (data[i] != WILDCARD) {
// break;
// }
// }
// if (i < 0) {
// return null;
// } else {
// byte[] newData = new byte[data.length];
// System.arraycopy(data, 0, newData, 0, data.length);
// newData[i] = WILDCARD;
// return new Mask(newData);
// }
// }
//
// /**
// *
// * @return int lenght of the mask
// */
// public int length(){
// return data.length;
// }
//
// public char charAt(int position) {
// return (char) data[position];
// }
//
// /**
// *
// * @return string representation of mask
// */
// @Override
// public String toString() {
// return new String(data);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Mask mask = (Mask) o;
// return Arrays.equals(data, mask.data);
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(data);
// }
//
// /**
// * constructs mask from string representation with validation
// * @param mask string representation fo mask
// * @return new mask
// * @throws IllegalArgumentException if mask has a bad format
// */
// public static Mask parse(String mask) {
// String m = mask;
// if (m == null) {
// m = EMPTY_MASK;
// }
// if (m.length() > MAX_LENGTH)
// throw new IllegalArgumentException("mask: "+mask+" is longer than limit "+ MAX_LENGTH + " (by E.164 standard)");
// Mask res = new Mask(m);
// byte[] data = res.data;
// if (m.indexOf(WILDCARD)!=-1) {
// boolean gotWildcard = false;
// for (byte c: data) {
// if (c == WILDCARD && !gotWildcard) {
// gotWildcard = true;
// } else if (gotWildcard && c!=WILDCARD){
// throw new IllegalArgumentException("mask: "+m+" is invalid ("+m+")");
// } else if (!gotWildcard) {
// try {
// digit((char) c);
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(e.getMessage()+" in mask: "+mask);
// }
// }
// }
// } else {
// for (byte c: data) {
// if (!Character.isDigit(c)) {
// throw new IllegalArgumentException("mask: "+m+" is contains invalid character ("+c+")");
// }
// }
// }
// return res;
// }
//
// /**
// * @param mask mask to check validity
// * @return true if valid, false - if not
// */
// public static boolean isValid(String mask) {
// try{
// parse(mask);
// return true;
// } catch (Exception e){
// return false;
// }
// }
// /**
// *
// * @param c character from mask
// * @return digit represents current char in number
// * @throws IllegalArgumentException if char is out of supported range (0-9)
// */
// public static int digit(char c) {
// int i = c - ZERO;
// if (i < 0 || i > 9)
// throw new IllegalArgumentException("char " + c + " is out of supported range (0-9)");
// return i;
// }
// }
| import com.eyeline.mnp.mask.Mask;
import org.junit.Test;
import static org.junit.Assert.*; | package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class MaskTest {
@Test
public void testMatch() { | // Path: src/com/eyeline/mnp/mask/Mask.java
// public final class Mask {
// public static final int MAX_LENGTH = 15;
// private static final String EMPTY_MASK = "";
// public static final char WILDCARD = '?';
// private static final char ZERO = '0';
//
// private final byte[] data;
//
// public Mask(String mask) {
// this.data = mask.getBytes(Charset.forName("ASCII"));
// }
//
// private Mask(byte[] data) {
// this.data = data;
// }
//
// /**
// *
// * @param number telephone number mask
// * @return true – if number matches mask, false – if otherwise. if number is null - return false
// *
// */
// public boolean match(String number) {
// if (this.data.length == 0 || number == null) return false;
// if (number.length()!=data.length) return false;
// for (int i=0; i<number.length(); i++) {
// if (data[i] == WILDCARD) continue;
// if (data[i] != number.charAt(i)) return false;
// }
// return true;
// }
//
// /**
// * Return wider mask
// * 123 returns 12?
// * 12? returns 1??
// * 1?? returns ???
// * ??? returns null
// * @return Return wider mask
// */
// public Mask getWider() {
// int i;
// for (i=data.length-1; i>=0; i--) {
// if (data[i] != WILDCARD) {
// break;
// }
// }
// if (i < 0) {
// return null;
// } else {
// byte[] newData = new byte[data.length];
// System.arraycopy(data, 0, newData, 0, data.length);
// newData[i] = WILDCARD;
// return new Mask(newData);
// }
// }
//
// /**
// *
// * @return int lenght of the mask
// */
// public int length(){
// return data.length;
// }
//
// public char charAt(int position) {
// return (char) data[position];
// }
//
// /**
// *
// * @return string representation of mask
// */
// @Override
// public String toString() {
// return new String(data);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Mask mask = (Mask) o;
// return Arrays.equals(data, mask.data);
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(data);
// }
//
// /**
// * constructs mask from string representation with validation
// * @param mask string representation fo mask
// * @return new mask
// * @throws IllegalArgumentException if mask has a bad format
// */
// public static Mask parse(String mask) {
// String m = mask;
// if (m == null) {
// m = EMPTY_MASK;
// }
// if (m.length() > MAX_LENGTH)
// throw new IllegalArgumentException("mask: "+mask+" is longer than limit "+ MAX_LENGTH + " (by E.164 standard)");
// Mask res = new Mask(m);
// byte[] data = res.data;
// if (m.indexOf(WILDCARD)!=-1) {
// boolean gotWildcard = false;
// for (byte c: data) {
// if (c == WILDCARD && !gotWildcard) {
// gotWildcard = true;
// } else if (gotWildcard && c!=WILDCARD){
// throw new IllegalArgumentException("mask: "+m+" is invalid ("+m+")");
// } else if (!gotWildcard) {
// try {
// digit((char) c);
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(e.getMessage()+" in mask: "+mask);
// }
// }
// }
// } else {
// for (byte c: data) {
// if (!Character.isDigit(c)) {
// throw new IllegalArgumentException("mask: "+m+" is contains invalid character ("+c+")");
// }
// }
// }
// return res;
// }
//
// /**
// * @param mask mask to check validity
// * @return true if valid, false - if not
// */
// public static boolean isValid(String mask) {
// try{
// parse(mask);
// return true;
// } catch (Exception e){
// return false;
// }
// }
// /**
// *
// * @param c character from mask
// * @return digit represents current char in number
// * @throws IllegalArgumentException if char is out of supported range (0-9)
// */
// public static int digit(char c) {
// int i = c - ZERO;
// if (i < 0 || i > 9)
// throw new IllegalArgumentException("char " + c + " is out of supported range (0-9)");
// return i;
// }
// }
// Path: test/com/eyeline/mnp/test/MaskTest.java
import com.eyeline.mnp.mask.Mask;
import org.junit.Test;
import static org.junit.Assert.*;
package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class MaskTest {
@Test
public void testMatch() { | Mask mask = new Mask("791393679??"); |
chukanov/mnp | test/com/eyeline/mnp/test/HashMapStorageTest.java | // Path: src/com/eyeline/mnp/HashMapStorage.java
// public class HashMapStorage implements Storage {
// private Map<Mask, Mno> storage = new HashMap<>();
//
// @Override
// public Mno lookup(String subscriber) {
// if (subscriber == null) return null;
// Mask mask = Mask.parse(subscriber);
// while (mask!=null) {
// Mno result = storage.get(mask);
// if (result!=null) {
// return result;
// }
// mask = mask.getWider();
// }
// return null;
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// if (mask == null || mno == null) return null;
// return storage.put(mask, mno);
// }
//
// @Override
// public Mno remove(Mask mask) {
// if (mask == null) return null;
// return storage.remove(mask);
// }
//
// @Override
// public void clear() {
// storage = new HashMap<>();
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
| import com.eyeline.mnp.HashMapStorage;
import com.eyeline.mnp.Storage; | package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class HashMapStorageTest extends BaseStorageTest {
@Override | // Path: src/com/eyeline/mnp/HashMapStorage.java
// public class HashMapStorage implements Storage {
// private Map<Mask, Mno> storage = new HashMap<>();
//
// @Override
// public Mno lookup(String subscriber) {
// if (subscriber == null) return null;
// Mask mask = Mask.parse(subscriber);
// while (mask!=null) {
// Mno result = storage.get(mask);
// if (result!=null) {
// return result;
// }
// mask = mask.getWider();
// }
// return null;
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// if (mask == null || mno == null) return null;
// return storage.put(mask, mno);
// }
//
// @Override
// public Mno remove(Mask mask) {
// if (mask == null) return null;
// return storage.remove(mask);
// }
//
// @Override
// public void clear() {
// storage = new HashMap<>();
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
// Path: test/com/eyeline/mnp/test/HashMapStorageTest.java
import com.eyeline.mnp.HashMapStorage;
import com.eyeline.mnp.Storage;
package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class HashMapStorageTest extends BaseStorageTest {
@Override | protected Storage build() { |
chukanov/mnp | test/com/eyeline/mnp/test/HashMapStorageTest.java | // Path: src/com/eyeline/mnp/HashMapStorage.java
// public class HashMapStorage implements Storage {
// private Map<Mask, Mno> storage = new HashMap<>();
//
// @Override
// public Mno lookup(String subscriber) {
// if (subscriber == null) return null;
// Mask mask = Mask.parse(subscriber);
// while (mask!=null) {
// Mno result = storage.get(mask);
// if (result!=null) {
// return result;
// }
// mask = mask.getWider();
// }
// return null;
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// if (mask == null || mno == null) return null;
// return storage.put(mask, mno);
// }
//
// @Override
// public Mno remove(Mask mask) {
// if (mask == null) return null;
// return storage.remove(mask);
// }
//
// @Override
// public void clear() {
// storage = new HashMap<>();
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
| import com.eyeline.mnp.HashMapStorage;
import com.eyeline.mnp.Storage; | package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class HashMapStorageTest extends BaseStorageTest {
@Override
protected Storage build() { | // Path: src/com/eyeline/mnp/HashMapStorage.java
// public class HashMapStorage implements Storage {
// private Map<Mask, Mno> storage = new HashMap<>();
//
// @Override
// public Mno lookup(String subscriber) {
// if (subscriber == null) return null;
// Mask mask = Mask.parse(subscriber);
// while (mask!=null) {
// Mno result = storage.get(mask);
// if (result!=null) {
// return result;
// }
// mask = mask.getWider();
// }
// return null;
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// if (mask == null || mno == null) return null;
// return storage.put(mask, mno);
// }
//
// @Override
// public Mno remove(Mask mask) {
// if (mask == null) return null;
// return storage.remove(mask);
// }
//
// @Override
// public void clear() {
// storage = new HashMap<>();
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
// Path: test/com/eyeline/mnp/test/HashMapStorageTest.java
import com.eyeline.mnp.HashMapStorage;
import com.eyeline.mnp.Storage;
package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class HashMapStorageTest extends BaseStorageTest {
@Override
protected Storage build() { | return new HashMapStorage(); |
chukanov/mnp | services/web-service/src/com/eyeline/mnp/web/MnpApi.java | // Path: src/com/eyeline/mnp/Mno.java
// public class Mno {
//
// private String id;
// private String country;
// private String title;
// private String area;
//
// public Mno(String id, String country, String title, String area) {
// this.id = id;
// this.country = country;
// this.title = title;
// this.area = area;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getArea() {
// return area;
// }
//
// public String getCountry() {
// return country;
// }
//
// @Override
// public String toString() {
// return "Mno{" +
// "id='" + id + '\'' +
// ", country='" + country + '\'' +
// ", title='" + title + '\'' +
// ", area='" + area + '\'' +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Mno mno = (Mno) o;
// return id.equals(mno.id);
//
// }
//
// @Override
// public int hashCode() {
// return id.hashCode();
// }
// }
| import com.eyeline.mnp.Mno;
import org.apache.log4j.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; | package com.eyeline.mnp.web;
/**
* @author Chukanov
*/
@Path("mnp")
public class MnpApi {
private static Logger log = Logger.getLogger(MnpApi.class);
@GET
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public String lookup(@QueryParam("subscriber") String subscriber) {
try { | // Path: src/com/eyeline/mnp/Mno.java
// public class Mno {
//
// private String id;
// private String country;
// private String title;
// private String area;
//
// public Mno(String id, String country, String title, String area) {
// this.id = id;
// this.country = country;
// this.title = title;
// this.area = area;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getArea() {
// return area;
// }
//
// public String getCountry() {
// return country;
// }
//
// @Override
// public String toString() {
// return "Mno{" +
// "id='" + id + '\'' +
// ", country='" + country + '\'' +
// ", title='" + title + '\'' +
// ", area='" + area + '\'' +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Mno mno = (Mno) o;
// return id.equals(mno.id);
//
// }
//
// @Override
// public int hashCode() {
// return id.hashCode();
// }
// }
// Path: services/web-service/src/com/eyeline/mnp/web/MnpApi.java
import com.eyeline.mnp.Mno;
import org.apache.log4j.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
package com.eyeline.mnp.web;
/**
* @author Chukanov
*/
@Path("mnp")
public class MnpApi {
private static Logger log = Logger.getLogger(MnpApi.class);
@GET
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public String lookup(@QueryParam("subscriber") String subscriber) {
try { | Mno mno = RestServer.getStorage().lookup(subscriber); |
chukanov/mnp | test/com/eyeline/mnp/test/ChainStorageTest.java | // Path: src/com/eyeline/mnp/ChainStorage.java
// public class ChainStorage implements Storage{
// private Storage[] storages;
//
// public ChainStorage(Storage... storages) {
// this.storages = storages;
// }
//
// @Override
// public Mno lookup(String subscriber) {
// for (Storage storage: storages){
// Mno mno = null;
// if(storage!=null) {
// mno = storage.lookup(subscriber);
// }
// if (mno!=null) return mno;
// }
// return null;
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// Mno result = null;
// for (Storage storage: storages) {
// if (storage!=null) {
// result = storage.put(mask, mno);
// }
// }
// return result;
// }
//
// @Override
// public Mno remove(Mask mask) {
// Mno mno = null;
// for (Storage storage: storages) {
// if (storage!=null) {
// mno = storage.remove(mask);
// }
// }
// return mno;
// }
//
// @Override
// public void clear() {
// for (Storage storage: storages) {
// if (storage!=null) {
// storage.clear();
// }
// }
// }
// }
//
// Path: src/com/eyeline/mnp/MasksStorage.java
// public class MasksStorage implements Storage{
//
// private MaskTrieMap<Mno> storage = new MaskTrieMap<>();
//
// @Override
// public Mno lookup(String phone) {
// if (phone == null) return null;
// return storage.lookup(Mask.parse(phone));
// }
//
// public Mno put(Mask mask, Mno mno) {
// if (mask == null || mno == null) return null;
// return storage.set(mask, mno);
// }
//
// @Override
// public Mno remove(Mask mask) {
// if (mask == null) return null;
// return storage.remove(mask);
// }
//
// @Override
// public void clear() {
// storage = new MaskTrieMap<>();
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
| import com.eyeline.mnp.ChainStorage;
import com.eyeline.mnp.MasksStorage;
import com.eyeline.mnp.Storage; | package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class ChainStorageTest extends BaseStorageTest {
@Override | // Path: src/com/eyeline/mnp/ChainStorage.java
// public class ChainStorage implements Storage{
// private Storage[] storages;
//
// public ChainStorage(Storage... storages) {
// this.storages = storages;
// }
//
// @Override
// public Mno lookup(String subscriber) {
// for (Storage storage: storages){
// Mno mno = null;
// if(storage!=null) {
// mno = storage.lookup(subscriber);
// }
// if (mno!=null) return mno;
// }
// return null;
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// Mno result = null;
// for (Storage storage: storages) {
// if (storage!=null) {
// result = storage.put(mask, mno);
// }
// }
// return result;
// }
//
// @Override
// public Mno remove(Mask mask) {
// Mno mno = null;
// for (Storage storage: storages) {
// if (storage!=null) {
// mno = storage.remove(mask);
// }
// }
// return mno;
// }
//
// @Override
// public void clear() {
// for (Storage storage: storages) {
// if (storage!=null) {
// storage.clear();
// }
// }
// }
// }
//
// Path: src/com/eyeline/mnp/MasksStorage.java
// public class MasksStorage implements Storage{
//
// private MaskTrieMap<Mno> storage = new MaskTrieMap<>();
//
// @Override
// public Mno lookup(String phone) {
// if (phone == null) return null;
// return storage.lookup(Mask.parse(phone));
// }
//
// public Mno put(Mask mask, Mno mno) {
// if (mask == null || mno == null) return null;
// return storage.set(mask, mno);
// }
//
// @Override
// public Mno remove(Mask mask) {
// if (mask == null) return null;
// return storage.remove(mask);
// }
//
// @Override
// public void clear() {
// storage = new MaskTrieMap<>();
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
// Path: test/com/eyeline/mnp/test/ChainStorageTest.java
import com.eyeline.mnp.ChainStorage;
import com.eyeline.mnp.MasksStorage;
import com.eyeline.mnp.Storage;
package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class ChainStorageTest extends BaseStorageTest {
@Override | protected Storage build() { |
chukanov/mnp | test/com/eyeline/mnp/test/ChainStorageTest.java | // Path: src/com/eyeline/mnp/ChainStorage.java
// public class ChainStorage implements Storage{
// private Storage[] storages;
//
// public ChainStorage(Storage... storages) {
// this.storages = storages;
// }
//
// @Override
// public Mno lookup(String subscriber) {
// for (Storage storage: storages){
// Mno mno = null;
// if(storage!=null) {
// mno = storage.lookup(subscriber);
// }
// if (mno!=null) return mno;
// }
// return null;
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// Mno result = null;
// for (Storage storage: storages) {
// if (storage!=null) {
// result = storage.put(mask, mno);
// }
// }
// return result;
// }
//
// @Override
// public Mno remove(Mask mask) {
// Mno mno = null;
// for (Storage storage: storages) {
// if (storage!=null) {
// mno = storage.remove(mask);
// }
// }
// return mno;
// }
//
// @Override
// public void clear() {
// for (Storage storage: storages) {
// if (storage!=null) {
// storage.clear();
// }
// }
// }
// }
//
// Path: src/com/eyeline/mnp/MasksStorage.java
// public class MasksStorage implements Storage{
//
// private MaskTrieMap<Mno> storage = new MaskTrieMap<>();
//
// @Override
// public Mno lookup(String phone) {
// if (phone == null) return null;
// return storage.lookup(Mask.parse(phone));
// }
//
// public Mno put(Mask mask, Mno mno) {
// if (mask == null || mno == null) return null;
// return storage.set(mask, mno);
// }
//
// @Override
// public Mno remove(Mask mask) {
// if (mask == null) return null;
// return storage.remove(mask);
// }
//
// @Override
// public void clear() {
// storage = new MaskTrieMap<>();
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
| import com.eyeline.mnp.ChainStorage;
import com.eyeline.mnp.MasksStorage;
import com.eyeline.mnp.Storage; | package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class ChainStorageTest extends BaseStorageTest {
@Override
protected Storage build() { | // Path: src/com/eyeline/mnp/ChainStorage.java
// public class ChainStorage implements Storage{
// private Storage[] storages;
//
// public ChainStorage(Storage... storages) {
// this.storages = storages;
// }
//
// @Override
// public Mno lookup(String subscriber) {
// for (Storage storage: storages){
// Mno mno = null;
// if(storage!=null) {
// mno = storage.lookup(subscriber);
// }
// if (mno!=null) return mno;
// }
// return null;
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// Mno result = null;
// for (Storage storage: storages) {
// if (storage!=null) {
// result = storage.put(mask, mno);
// }
// }
// return result;
// }
//
// @Override
// public Mno remove(Mask mask) {
// Mno mno = null;
// for (Storage storage: storages) {
// if (storage!=null) {
// mno = storage.remove(mask);
// }
// }
// return mno;
// }
//
// @Override
// public void clear() {
// for (Storage storage: storages) {
// if (storage!=null) {
// storage.clear();
// }
// }
// }
// }
//
// Path: src/com/eyeline/mnp/MasksStorage.java
// public class MasksStorage implements Storage{
//
// private MaskTrieMap<Mno> storage = new MaskTrieMap<>();
//
// @Override
// public Mno lookup(String phone) {
// if (phone == null) return null;
// return storage.lookup(Mask.parse(phone));
// }
//
// public Mno put(Mask mask, Mno mno) {
// if (mask == null || mno == null) return null;
// return storage.set(mask, mno);
// }
//
// @Override
// public Mno remove(Mask mask) {
// if (mask == null) return null;
// return storage.remove(mask);
// }
//
// @Override
// public void clear() {
// storage = new MaskTrieMap<>();
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
// Path: test/com/eyeline/mnp/test/ChainStorageTest.java
import com.eyeline.mnp.ChainStorage;
import com.eyeline.mnp.MasksStorage;
import com.eyeline.mnp.Storage;
package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class ChainStorageTest extends BaseStorageTest {
@Override
protected Storage build() { | return new ChainStorage(new MasksStorage(), new MasksStorage()); |
chukanov/mnp | test/com/eyeline/mnp/test/ChainStorageTest.java | // Path: src/com/eyeline/mnp/ChainStorage.java
// public class ChainStorage implements Storage{
// private Storage[] storages;
//
// public ChainStorage(Storage... storages) {
// this.storages = storages;
// }
//
// @Override
// public Mno lookup(String subscriber) {
// for (Storage storage: storages){
// Mno mno = null;
// if(storage!=null) {
// mno = storage.lookup(subscriber);
// }
// if (mno!=null) return mno;
// }
// return null;
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// Mno result = null;
// for (Storage storage: storages) {
// if (storage!=null) {
// result = storage.put(mask, mno);
// }
// }
// return result;
// }
//
// @Override
// public Mno remove(Mask mask) {
// Mno mno = null;
// for (Storage storage: storages) {
// if (storage!=null) {
// mno = storage.remove(mask);
// }
// }
// return mno;
// }
//
// @Override
// public void clear() {
// for (Storage storage: storages) {
// if (storage!=null) {
// storage.clear();
// }
// }
// }
// }
//
// Path: src/com/eyeline/mnp/MasksStorage.java
// public class MasksStorage implements Storage{
//
// private MaskTrieMap<Mno> storage = new MaskTrieMap<>();
//
// @Override
// public Mno lookup(String phone) {
// if (phone == null) return null;
// return storage.lookup(Mask.parse(phone));
// }
//
// public Mno put(Mask mask, Mno mno) {
// if (mask == null || mno == null) return null;
// return storage.set(mask, mno);
// }
//
// @Override
// public Mno remove(Mask mask) {
// if (mask == null) return null;
// return storage.remove(mask);
// }
//
// @Override
// public void clear() {
// storage = new MaskTrieMap<>();
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
| import com.eyeline.mnp.ChainStorage;
import com.eyeline.mnp.MasksStorage;
import com.eyeline.mnp.Storage; | package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class ChainStorageTest extends BaseStorageTest {
@Override
protected Storage build() { | // Path: src/com/eyeline/mnp/ChainStorage.java
// public class ChainStorage implements Storage{
// private Storage[] storages;
//
// public ChainStorage(Storage... storages) {
// this.storages = storages;
// }
//
// @Override
// public Mno lookup(String subscriber) {
// for (Storage storage: storages){
// Mno mno = null;
// if(storage!=null) {
// mno = storage.lookup(subscriber);
// }
// if (mno!=null) return mno;
// }
// return null;
// }
//
// @Override
// public Mno put(Mask mask, Mno mno) {
// Mno result = null;
// for (Storage storage: storages) {
// if (storage!=null) {
// result = storage.put(mask, mno);
// }
// }
// return result;
// }
//
// @Override
// public Mno remove(Mask mask) {
// Mno mno = null;
// for (Storage storage: storages) {
// if (storage!=null) {
// mno = storage.remove(mask);
// }
// }
// return mno;
// }
//
// @Override
// public void clear() {
// for (Storage storage: storages) {
// if (storage!=null) {
// storage.clear();
// }
// }
// }
// }
//
// Path: src/com/eyeline/mnp/MasksStorage.java
// public class MasksStorage implements Storage{
//
// private MaskTrieMap<Mno> storage = new MaskTrieMap<>();
//
// @Override
// public Mno lookup(String phone) {
// if (phone == null) return null;
// return storage.lookup(Mask.parse(phone));
// }
//
// public Mno put(Mask mask, Mno mno) {
// if (mask == null || mno == null) return null;
// return storage.set(mask, mno);
// }
//
// @Override
// public Mno remove(Mask mask) {
// if (mask == null) return null;
// return storage.remove(mask);
// }
//
// @Override
// public void clear() {
// storage = new MaskTrieMap<>();
// }
// }
//
// Path: src/com/eyeline/mnp/Storage.java
// public interface Storage {
// /**
// * Lookup MNO by phone number
// * @param subscriber phone number
// * @return mno if exists, otherwise null
// */
// public Mno lookup(String subscriber);
//
// /**
// * Adds a new mask to mno in storage
// * but only if mask is not exists
// * @param mask new mask
// * @param mno mno
// * @return Mno – old value if present
// */
// public Mno put(Mask mask, Mno mno);
//
// /**
// * remove mask from the storage
// * @param mask mask
// * @return old value
// */
// public Mno remove(Mask mask);
//
// /**
// * clear the storage
// */
// public void clear();
// }
// Path: test/com/eyeline/mnp/test/ChainStorageTest.java
import com.eyeline.mnp.ChainStorage;
import com.eyeline.mnp.MasksStorage;
import com.eyeline.mnp.Storage;
package com.eyeline.mnp.test;
/**
* @author Chukanov
*/
public class ChainStorageTest extends BaseStorageTest {
@Override
protected Storage build() { | return new ChainStorage(new MasksStorage(), new MasksStorage()); |
Tirasa/ADSDDL | src/main/java/net/tirasa/adsddl/ntsd/controls/SDFlagsControl.java | // Path: src/main/java/net/tirasa/adsddl/ntsd/utils/NumberFacility.java
// public class NumberFacility {
//
// /**
// * Gets byte array corresponding to a given unsigned integer.
// *
// * @param value unsigned integer.
// * @return byte array.
// */
// public static byte[] getUIntBytes(final long value) {
// return Arrays.copyOfRange(ByteBuffer.allocate(8).putLong(value).array(), 4, 8);
// }
//
// /**
// * Gets byte array from integer.
// *
// * @param value integer.
// * @return byte array.
// */
// public static byte[] getBytes(final int value) {
// return ByteBuffer.allocate(4).putInt(value).array();
// }
//
// /**
// * Gets byte array from integer.
// *
// * @param value integer.
// * @param length array size.
// * @return byte array.
// */
// public static byte[] getBytes(final int value, final int length) {
// return ByteBuffer.allocate(length).putInt(value).array();
// }
//
// /**
// * Remove 0x00 bytes from left side.
// *
// * @param bytes source array.
// * @return trimmed array.
// */
// @SuppressWarnings("empty-statement")
// public static byte[] leftTrim(final byte... bytes) {
// int pos = 0;
// for (; pos < bytes.length && bytes[pos] == 0x00; pos++);
//
// if (pos < bytes.length) {
// return Arrays.copyOfRange(bytes, pos, bytes.length);
// } else {
// return new byte[] { 0x00 };
// }
// }
//
// /**
// * Remove 0x00 bytes from right side.
// *
// * @param bytes source array.
// * @return trimmed array.
// */
// public static byte[] rightTrim(final byte... bytes) {
// return Hex.reverse(leftTrim(Hex.reverse(bytes)));
// }
//
// /**
// * Gets bits as boolean array from a given byte array.
// *
// * @param bytes bytes.
// * @return bits.
// */
// public static boolean[] getBits(final byte... bytes) {
// if (bytes.length > 4) {
// throw new InvalidParameterException("Invalid number of bytes");
// }
//
// final boolean[] res = new boolean[bytes.length * 8];
//
// int pos = 0;
//
// for (byte b : bytes) {
// for (boolean bool : getBits(b)) {
// res[pos] = bool;
// pos++;
// }
// }
//
// return res;
// }
//
// /**
// * Gets bits as boolean array from a given byte.
// *
// * @param b byte.
// * @return bits.
// */
// public static boolean[] getBits(final byte b) {
// final boolean[] res = new boolean[8];
// for (int i = 0; i < 8; i++) {
// res[7 - i] = (b & (1 << i)) != 0;
// }
// return res;
// }
//
// /**
// * Reverts bytes and retrieves the corresponding integer value.
// *
// * @param bytes bytes.
// * @return integer.
// */
// public static int getReverseInt(final byte... bytes) {
// return (int) getReverseUInt(bytes);
// }
//
// /**
// * Reverses bytes and retrieves the corresponding unsigned integer value.
// *
// * @param bytes bytes.
// * @return unsigned integer.
// */
// public static long getReverseUInt(final byte... bytes) {
// return getUInt(Hex.reverse(bytes));
// }
//
// /**
// * Gets byte array corresponding to the given integer value, reverses obtained byte array and retrieves the new
// * integer value.
// *
// * @param value integer value.
// * @return reversed integer value.
// */
// public static int getReverseInt(final int value) {
// return (int) getReverseUInt(value);
// }
//
// /**
// * Gets byte array corresponding to the given integer value, reverses obtained byte array and retrieves the new
// * unsigned integer value.
// *
// * @param value integer value.
// * @return reversed unsigned integer value.
// */
// public static long getReverseUInt(final int value) {
// return getReverseUInt(getBytes(value));
// }
//
// /**
// * Gets integer value corresponding to the given bytes.
// *
// * @param bytes bytes.
// * @return integer.
// */
// public static int getInt(final byte... bytes) {
// return (int) getUInt(bytes);
// }
//
// /**
// * Gets unsigned integer value corresponding to the given bytes.
// *
// * @param bytes bytes.
// * @return unsigned integer.
// */
// public static long getUInt(final byte... bytes) {
// if (bytes.length > 4) {
// throw new InvalidParameterException("Invalid number of bytes");
// }
//
// long res = 0;
// for (int i = 0; i < bytes.length; i++) {
// res |= bytes[i] & 0xFF;
// if (i < bytes.length - 1) {
// res <<= 8;
// }
// }
//
// return res;
// }
// }
| import java.nio.ByteBuffer;
import javax.naming.ldap.BasicControl;
import net.tirasa.adsddl.ntsd.utils.NumberFacility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /**
* Constructor.
*
* @param criticality The control's criticality.
* @param flags SD Flags Control.
*/
public SDFlagsControl(final boolean criticality, final Integer flags) {
super(OID, criticality, null);
this.flags = flags == null ? 0x00000001 + 0x00000002 + 0x00000004 + 0x00000008 : flags;
try {
this.value = berEncodedValue();
} catch (Exception e) {
LOG.error("Error setting SD control flags", e);
this.value = new byte[0];
}
}
/**
* BER encode the flags.
*
* @return flags BER encoded.
*/
private byte[] berEncodedValue() {
final ByteBuffer buff = ByteBuffer.allocate(5);
buff.put((byte) 0x30); // (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
buff.put((byte) 0x03); // size
buff.put((byte) 0x02); // 4bytes int tag
buff.put((byte) 0x01); // int size | // Path: src/main/java/net/tirasa/adsddl/ntsd/utils/NumberFacility.java
// public class NumberFacility {
//
// /**
// * Gets byte array corresponding to a given unsigned integer.
// *
// * @param value unsigned integer.
// * @return byte array.
// */
// public static byte[] getUIntBytes(final long value) {
// return Arrays.copyOfRange(ByteBuffer.allocate(8).putLong(value).array(), 4, 8);
// }
//
// /**
// * Gets byte array from integer.
// *
// * @param value integer.
// * @return byte array.
// */
// public static byte[] getBytes(final int value) {
// return ByteBuffer.allocate(4).putInt(value).array();
// }
//
// /**
// * Gets byte array from integer.
// *
// * @param value integer.
// * @param length array size.
// * @return byte array.
// */
// public static byte[] getBytes(final int value, final int length) {
// return ByteBuffer.allocate(length).putInt(value).array();
// }
//
// /**
// * Remove 0x00 bytes from left side.
// *
// * @param bytes source array.
// * @return trimmed array.
// */
// @SuppressWarnings("empty-statement")
// public static byte[] leftTrim(final byte... bytes) {
// int pos = 0;
// for (; pos < bytes.length && bytes[pos] == 0x00; pos++);
//
// if (pos < bytes.length) {
// return Arrays.copyOfRange(bytes, pos, bytes.length);
// } else {
// return new byte[] { 0x00 };
// }
// }
//
// /**
// * Remove 0x00 bytes from right side.
// *
// * @param bytes source array.
// * @return trimmed array.
// */
// public static byte[] rightTrim(final byte... bytes) {
// return Hex.reverse(leftTrim(Hex.reverse(bytes)));
// }
//
// /**
// * Gets bits as boolean array from a given byte array.
// *
// * @param bytes bytes.
// * @return bits.
// */
// public static boolean[] getBits(final byte... bytes) {
// if (bytes.length > 4) {
// throw new InvalidParameterException("Invalid number of bytes");
// }
//
// final boolean[] res = new boolean[bytes.length * 8];
//
// int pos = 0;
//
// for (byte b : bytes) {
// for (boolean bool : getBits(b)) {
// res[pos] = bool;
// pos++;
// }
// }
//
// return res;
// }
//
// /**
// * Gets bits as boolean array from a given byte.
// *
// * @param b byte.
// * @return bits.
// */
// public static boolean[] getBits(final byte b) {
// final boolean[] res = new boolean[8];
// for (int i = 0; i < 8; i++) {
// res[7 - i] = (b & (1 << i)) != 0;
// }
// return res;
// }
//
// /**
// * Reverts bytes and retrieves the corresponding integer value.
// *
// * @param bytes bytes.
// * @return integer.
// */
// public static int getReverseInt(final byte... bytes) {
// return (int) getReverseUInt(bytes);
// }
//
// /**
// * Reverses bytes and retrieves the corresponding unsigned integer value.
// *
// * @param bytes bytes.
// * @return unsigned integer.
// */
// public static long getReverseUInt(final byte... bytes) {
// return getUInt(Hex.reverse(bytes));
// }
//
// /**
// * Gets byte array corresponding to the given integer value, reverses obtained byte array and retrieves the new
// * integer value.
// *
// * @param value integer value.
// * @return reversed integer value.
// */
// public static int getReverseInt(final int value) {
// return (int) getReverseUInt(value);
// }
//
// /**
// * Gets byte array corresponding to the given integer value, reverses obtained byte array and retrieves the new
// * unsigned integer value.
// *
// * @param value integer value.
// * @return reversed unsigned integer value.
// */
// public static long getReverseUInt(final int value) {
// return getReverseUInt(getBytes(value));
// }
//
// /**
// * Gets integer value corresponding to the given bytes.
// *
// * @param bytes bytes.
// * @return integer.
// */
// public static int getInt(final byte... bytes) {
// return (int) getUInt(bytes);
// }
//
// /**
// * Gets unsigned integer value corresponding to the given bytes.
// *
// * @param bytes bytes.
// * @return unsigned integer.
// */
// public static long getUInt(final byte... bytes) {
// if (bytes.length > 4) {
// throw new InvalidParameterException("Invalid number of bytes");
// }
//
// long res = 0;
// for (int i = 0; i < bytes.length; i++) {
// res |= bytes[i] & 0xFF;
// if (i < bytes.length - 1) {
// res <<= 8;
// }
// }
//
// return res;
// }
// }
// Path: src/main/java/net/tirasa/adsddl/ntsd/controls/SDFlagsControl.java
import java.nio.ByteBuffer;
import javax.naming.ldap.BasicControl;
import net.tirasa.adsddl.ntsd.utils.NumberFacility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Constructor.
*
* @param criticality The control's criticality.
* @param flags SD Flags Control.
*/
public SDFlagsControl(final boolean criticality, final Integer flags) {
super(OID, criticality, null);
this.flags = flags == null ? 0x00000001 + 0x00000002 + 0x00000004 + 0x00000008 : flags;
try {
this.value = berEncodedValue();
} catch (Exception e) {
LOG.error("Error setting SD control flags", e);
this.value = new byte[0];
}
}
/**
* BER encode the flags.
*
* @return flags BER encoded.
*/
private byte[] berEncodedValue() {
final ByteBuffer buff = ByteBuffer.allocate(5);
buff.put((byte) 0x30); // (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
buff.put((byte) 0x03); // size
buff.put((byte) 0x02); // 4bytes int tag
buff.put((byte) 0x01); // int size | buff.put(NumberFacility.leftTrim(NumberFacility.getBytes(flags))); // value |
Tirasa/ADSDDL | src/test/java/net/tirasa/adsddl/it/DirSyncTest.java | // Path: src/main/java/net/tirasa/adsddl/ntsd/controls/DirSyncControl.java
// public class DirSyncControl extends BasicControl {
//
// private static final long serialVersionUID = -930993758829518418L;
//
// /**
// * LDAP_SERVER_DIRSYNC_OID.
// * Directory synchronization control.
// */
// public static final String OID = "1.2.840.113556.1.4.841";
//
// /**
// * Empty cookie.
// */
// private static final byte[] EMPTY_COOKIE = new byte[0];
//
// /**
// * LDAP_DIRSYNC_INCREMENTAL_VALUES | LDAP_DIRSYNC_ANCESTORS_FIRST_ORDER | LDAP_DIRSYNC_OBJECT_SECURITY
// * LDAP_DIRSYNC_OBJECT_SECURITY: 0x00000001
// * LDAP_DIRSYNC_ANCESTORS_FIRST_ORDER: 0x00000800
// * LDAP_DIRSYNC_PUBLIC_DATA_ONLY: 0x00002000
// * LDAP_DIRSYNC_INCREMENTAL_VALUES: 0x80000000
// */
// private int flags = 0x80000801;
//
// private final byte[] cookie;
//
// /**
// * Constructor.
// * Specify an empty cookie.
// */
// public DirSyncControl() {
// super(OID, true, null);
// this.cookie = EMPTY_COOKIE;
// super.value = berEncodedValue();
// }
//
// /**
// * Constructor.
// *
// * @param cookie cookie.
// */
// public DirSyncControl(byte[] cookie) {
// super(OID, true, cookie);
// this.cookie = cookie;
// super.value = berEncodedValue();
// }
//
// /**
// * BER encode the cookie value.
// *
// * @param cookie cookie value to be encoded.
// * @return ber encoded cookie value.
// */
// private byte[] berEncodedValue() {
// final byte[] cookieSize = NumberFacility.leftTrim(NumberFacility.getBytes(cookie.length));
// final byte[] size = NumberFacility.leftTrim(NumberFacility.getBytes(14 + cookieSize.length + cookie.length));
//
// final ByteBuffer buff = ByteBuffer.allocate(1 + 1 + size.length + 14 + cookieSize.length + cookie.length);
//
// buff.put((byte) 0x30); // (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
// buff.put((byte) (size.length == 1 ? 0x81 : size.length == 2 ? 0x82 : 0x83)); // size type (short or long form)
// buff.put(size); // sequence size
// buff.put((byte) 0x02); // 4bytes int tag
// buff.put((byte) 0x04); // int size
// buff.putInt(flags); // flags
// buff.put((byte) 0x02); // 4bytes int tag
// buff.put((byte) 0x04); // int size
// buff.putInt(Integer.MAX_VALUE); // max attribute count
// buff.put((byte) 0x04); // byte array tag
// buff.put((byte) (cookieSize.length == 1 ? 0x81 : cookieSize.length == 2 ? 0x82 : 0x83)); // short or long form
// buff.put(cookieSize); // byte array size
// if (cookie.length > 0) {
// buff.put(cookie); // (cookie, Ber.ASN_OCTET_STR);
// }
// return buff.array();
// }
//
// public DirSyncControl setFlags(final int flags) {
// this.flags = flags;
// // value encoding must be regenerated to provide new flags ...
// super.value = berEncodedValue();
// return this;
// }
// }
| import static org.junit.Assert.assertEquals;
import com.sun.jndi.ldap.ctl.DirSyncResponseControl;
import java.util.AbstractMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.LdapContext;
import net.tirasa.adsddl.ntsd.controls.DirSyncControl;
import org.junit.Test; | /*
* Copyright (C) 2018 Tirasa (info@tirasa.net)
*
* 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 net.tirasa.adsddl.it;
public class DirSyncTest extends AbstractTest {
private static final long serialVersionUID = 1L;
@Test
public void syncUser() throws Exception {
// -----------------------------------
// Create search control
// -----------------------------------
final SearchControls searchCtls = createDefaultSearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchCtls.setReturningAttributes(null);
searchCtls.setTimeLimit(20000);
// -----------------------------------
// retrieve latest sync token | // Path: src/main/java/net/tirasa/adsddl/ntsd/controls/DirSyncControl.java
// public class DirSyncControl extends BasicControl {
//
// private static final long serialVersionUID = -930993758829518418L;
//
// /**
// * LDAP_SERVER_DIRSYNC_OID.
// * Directory synchronization control.
// */
// public static final String OID = "1.2.840.113556.1.4.841";
//
// /**
// * Empty cookie.
// */
// private static final byte[] EMPTY_COOKIE = new byte[0];
//
// /**
// * LDAP_DIRSYNC_INCREMENTAL_VALUES | LDAP_DIRSYNC_ANCESTORS_FIRST_ORDER | LDAP_DIRSYNC_OBJECT_SECURITY
// * LDAP_DIRSYNC_OBJECT_SECURITY: 0x00000001
// * LDAP_DIRSYNC_ANCESTORS_FIRST_ORDER: 0x00000800
// * LDAP_DIRSYNC_PUBLIC_DATA_ONLY: 0x00002000
// * LDAP_DIRSYNC_INCREMENTAL_VALUES: 0x80000000
// */
// private int flags = 0x80000801;
//
// private final byte[] cookie;
//
// /**
// * Constructor.
// * Specify an empty cookie.
// */
// public DirSyncControl() {
// super(OID, true, null);
// this.cookie = EMPTY_COOKIE;
// super.value = berEncodedValue();
// }
//
// /**
// * Constructor.
// *
// * @param cookie cookie.
// */
// public DirSyncControl(byte[] cookie) {
// super(OID, true, cookie);
// this.cookie = cookie;
// super.value = berEncodedValue();
// }
//
// /**
// * BER encode the cookie value.
// *
// * @param cookie cookie value to be encoded.
// * @return ber encoded cookie value.
// */
// private byte[] berEncodedValue() {
// final byte[] cookieSize = NumberFacility.leftTrim(NumberFacility.getBytes(cookie.length));
// final byte[] size = NumberFacility.leftTrim(NumberFacility.getBytes(14 + cookieSize.length + cookie.length));
//
// final ByteBuffer buff = ByteBuffer.allocate(1 + 1 + size.length + 14 + cookieSize.length + cookie.length);
//
// buff.put((byte) 0x30); // (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
// buff.put((byte) (size.length == 1 ? 0x81 : size.length == 2 ? 0x82 : 0x83)); // size type (short or long form)
// buff.put(size); // sequence size
// buff.put((byte) 0x02); // 4bytes int tag
// buff.put((byte) 0x04); // int size
// buff.putInt(flags); // flags
// buff.put((byte) 0x02); // 4bytes int tag
// buff.put((byte) 0x04); // int size
// buff.putInt(Integer.MAX_VALUE); // max attribute count
// buff.put((byte) 0x04); // byte array tag
// buff.put((byte) (cookieSize.length == 1 ? 0x81 : cookieSize.length == 2 ? 0x82 : 0x83)); // short or long form
// buff.put(cookieSize); // byte array size
// if (cookie.length > 0) {
// buff.put(cookie); // (cookie, Ber.ASN_OCTET_STR);
// }
// return buff.array();
// }
//
// public DirSyncControl setFlags(final int flags) {
// this.flags = flags;
// // value encoding must be regenerated to provide new flags ...
// super.value = berEncodedValue();
// return this;
// }
// }
// Path: src/test/java/net/tirasa/adsddl/it/DirSyncTest.java
import static org.junit.Assert.assertEquals;
import com.sun.jndi.ldap.ctl.DirSyncResponseControl;
import java.util.AbstractMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.LdapContext;
import net.tirasa.adsddl.ntsd.controls.DirSyncControl;
import org.junit.Test;
/*
* Copyright (C) 2018 Tirasa (info@tirasa.net)
*
* 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 net.tirasa.adsddl.it;
public class DirSyncTest extends AbstractTest {
private static final long serialVersionUID = 1L;
@Test
public void syncUser() throws Exception {
// -----------------------------------
// Create search control
// -----------------------------------
final SearchControls searchCtls = createDefaultSearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchCtls.setReturningAttributes(null);
searchCtls.setTimeLimit(20000);
// -----------------------------------
// retrieve latest sync token | ctx.setRequestControls(new Control[] { new DirSyncControl().setFlags(0x00000801) }); |
Atmosphere/wasync | wasync/src/main/java/org/atmosphere/wasync/decoder/TrackMessageSizeDecoder.java | // Path: wasync/src/main/java/org/atmosphere/wasync/Event.java
// public enum Event {
//
// /**
// * This event is fired when the connection is open. This event is only fired once.
// */
// OPEN,
//
// /**
// * This event is fired when the connection gets closed. This event is only fired once.
// */
// CLOSE,
//
// /**
// * This event is fired every time a new message is received.
// */
// MESSAGE,
//
// /**
// * This event is fired every time the connection re-opened
// */
// REOPENED,
//
// /**
// * This event is fired when unexpected error happens. This event is only fired once.
// */
// ERROR,
//
// /**
// * This event is fire when the response's status is received. This event is only fired once.
// */
// STATUS,
//
// /**
// * This event is fire when the response's headers is received. This event is only fired once.
// */
// HEADERS,
//
// /**
// * This event is fire when the response's bytes are received.
// */
// MESSAGE_BYTES,
//
// /**
// * This event is fire when the connection has been established. The Transport propagated is the one that worked.
// * This event is only fired once.
// */
// TRANSPORT
//
// }
//
// Path: wasync/src/main/java/org/atmosphere/wasync/ReplayDecoder.java
// public interface ReplayDecoder<U, T> extends Decoder<U, Decoded<List<T>>> {
//
// /**
// * Decode a String into a List of Objects. Each element of the List will be dispatched to the decoders that where
// * added after an implementation of that interface.
// *
// *
// * @param e Event
// * @param s a object of type U
// * @return a List of Object
// */
// @Override
// public Decoded<List<T>> decode(Event e, U s);
// }
| import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.atmosphere.wasync.Event;
import org.atmosphere.wasync.ReplayDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright 2008-2022 Async-IO.org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.wasync.decoder;
public class TrackMessageSizeDecoder implements ReplayDecoder<String, String> {
private final Logger logger = LoggerFactory.getLogger(TrackMessageSizeDecoder.class);
private final String delimiter;
private final StringBuffer messagesBuffer = new StringBuffer();
private final AtomicBoolean skipFirstMessage = new AtomicBoolean();
private final Decoded<List<String>> empty = new Decoded<List<String>>(Collections.<String>emptyList());
private final static String charReplacement = "!!&;_!!";
public TrackMessageSizeDecoder() {
this.delimiter = "|";
}
public TrackMessageSizeDecoder(boolean protocolEnabled) {
this.delimiter = "|";
skipFirstMessage.set(protocolEnabled);
}
public TrackMessageSizeDecoder(String delimiter, boolean protocolEnabled) {
this.delimiter = delimiter;
skipFirstMessage.set(protocolEnabled);
}
@Override | // Path: wasync/src/main/java/org/atmosphere/wasync/Event.java
// public enum Event {
//
// /**
// * This event is fired when the connection is open. This event is only fired once.
// */
// OPEN,
//
// /**
// * This event is fired when the connection gets closed. This event is only fired once.
// */
// CLOSE,
//
// /**
// * This event is fired every time a new message is received.
// */
// MESSAGE,
//
// /**
// * This event is fired every time the connection re-opened
// */
// REOPENED,
//
// /**
// * This event is fired when unexpected error happens. This event is only fired once.
// */
// ERROR,
//
// /**
// * This event is fire when the response's status is received. This event is only fired once.
// */
// STATUS,
//
// /**
// * This event is fire when the response's headers is received. This event is only fired once.
// */
// HEADERS,
//
// /**
// * This event is fire when the response's bytes are received.
// */
// MESSAGE_BYTES,
//
// /**
// * This event is fire when the connection has been established. The Transport propagated is the one that worked.
// * This event is only fired once.
// */
// TRANSPORT
//
// }
//
// Path: wasync/src/main/java/org/atmosphere/wasync/ReplayDecoder.java
// public interface ReplayDecoder<U, T> extends Decoder<U, Decoded<List<T>>> {
//
// /**
// * Decode a String into a List of Objects. Each element of the List will be dispatched to the decoders that where
// * added after an implementation of that interface.
// *
// *
// * @param e Event
// * @param s a object of type U
// * @return a List of Object
// */
// @Override
// public Decoded<List<T>> decode(Event e, U s);
// }
// Path: wasync/src/main/java/org/atmosphere/wasync/decoder/TrackMessageSizeDecoder.java
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.atmosphere.wasync.Event;
import org.atmosphere.wasync.ReplayDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Copyright 2008-2022 Async-IO.org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.wasync.decoder;
public class TrackMessageSizeDecoder implements ReplayDecoder<String, String> {
private final Logger logger = LoggerFactory.getLogger(TrackMessageSizeDecoder.class);
private final String delimiter;
private final StringBuffer messagesBuffer = new StringBuffer();
private final AtomicBoolean skipFirstMessage = new AtomicBoolean();
private final Decoded<List<String>> empty = new Decoded<List<String>>(Collections.<String>emptyList());
private final static String charReplacement = "!!&;_!!";
public TrackMessageSizeDecoder() {
this.delimiter = "|";
}
public TrackMessageSizeDecoder(boolean protocolEnabled) {
this.delimiter = "|";
skipFirstMessage.set(protocolEnabled);
}
public TrackMessageSizeDecoder(String delimiter, boolean protocolEnabled) {
this.delimiter = delimiter;
skipFirstMessage.set(protocolEnabled);
}
@Override | public Decoded<List<String>> decode(Event type, String message) { |
Atmosphere/wasync | wasync/src/main/java/org/atmosphere/wasync/ClientFactory.java | // Path: wasync/src/main/java/org/atmosphere/wasync/impl/DefaultClient.java
// public class DefaultClient implements Client<DefaultOptions, OptionsBuilder,RequestBuilder> {
//
// public DefaultClient() {
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Socket create() {
// return ClientUtil.create();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Socket create(DefaultOptions options) {
// return ClientUtil.create(options);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public RequestBuilder newRequestBuilder() {
// RequestBuilder b = new DefaultRequestBuilder();
// return b.resolver(FunctionResolver.DEFAULT);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public OptionsBuilder newOptionsBuilder() {
// return new DefaultOptionsBuilder();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public RequestBuilder newRequestBuilder(Class<RequestBuilder> clazz) {
// RequestBuilder b = null;
// try {
// b = clazz.newInstance();
// } catch (InstantiationException e) {
// throw new RuntimeException(e);
// } catch (IllegalAccessException e) {
// throw new RuntimeException(e);
// }
// return b.resolver(FunctionResolver.DEFAULT);
// }
// }
| import org.atmosphere.wasync.impl.DefaultClient; | /*
* Copyright 2008-2022 Async-IO.org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.wasync;
/**
* Create a {@link Client}. By default, the {@link DefaultClient} will be returned. To override the {@link DefaultClient},
* just specify the provider using the -Dwasync.client property.
*
* @author Jeanfrancois Arcand
*/
public class ClientFactory {
private final static ClientFactory factory = new ClientFactory();
private final String clientClassName;
public ClientFactory() {
clientClassName = System.getProperty("wasync.client");
}
/**
* Return the default Factory.
*
* @return this
*/
public final static ClientFactory getDefault() {
return factory;
}
/**
* Return a new {@link Client} instance
*
* @return a new {@link Client} instance
*/
public Client<? extends Options, ? extends OptionsBuilder, ? extends RequestBuilder> newClient() {
if (clientClassName == null) { | // Path: wasync/src/main/java/org/atmosphere/wasync/impl/DefaultClient.java
// public class DefaultClient implements Client<DefaultOptions, OptionsBuilder,RequestBuilder> {
//
// public DefaultClient() {
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Socket create() {
// return ClientUtil.create();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Socket create(DefaultOptions options) {
// return ClientUtil.create(options);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public RequestBuilder newRequestBuilder() {
// RequestBuilder b = new DefaultRequestBuilder();
// return b.resolver(FunctionResolver.DEFAULT);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public OptionsBuilder newOptionsBuilder() {
// return new DefaultOptionsBuilder();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public RequestBuilder newRequestBuilder(Class<RequestBuilder> clazz) {
// RequestBuilder b = null;
// try {
// b = clazz.newInstance();
// } catch (InstantiationException e) {
// throw new RuntimeException(e);
// } catch (IllegalAccessException e) {
// throw new RuntimeException(e);
// }
// return b.resolver(FunctionResolver.DEFAULT);
// }
// }
// Path: wasync/src/main/java/org/atmosphere/wasync/ClientFactory.java
import org.atmosphere.wasync.impl.DefaultClient;
/*
* Copyright 2008-2022 Async-IO.org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.wasync;
/**
* Create a {@link Client}. By default, the {@link DefaultClient} will be returned. To override the {@link DefaultClient},
* just specify the provider using the -Dwasync.client property.
*
* @author Jeanfrancois Arcand
*/
public class ClientFactory {
private final static ClientFactory factory = new ClientFactory();
private final String clientClassName;
public ClientFactory() {
clientClassName = System.getProperty("wasync.client");
}
/**
* Return the default Factory.
*
* @return this
*/
public final static ClientFactory getDefault() {
return factory;
}
/**
* Return a new {@link Client} instance
*
* @return a new {@link Client} instance
*/
public Client<? extends Options, ? extends OptionsBuilder, ? extends RequestBuilder> newClient() {
if (clientClassName == null) { | return new DefaultClient(); |
Atmosphere/wasync | wasync/src/test/java/org/atmosphere/tests/StreamingTest.java | // Path: wasync/src/main/java/org/atmosphere/wasync/Request.java
// public interface Request {
//
// public enum METHOD {GET, POST, TRACE, PUT, DELETE, OPTIONS}
// public enum TRANSPORT {WEBSOCKET, SSE, STREAMING, LONG_POLLING}
//
// /**
// * The list of transports to try
// * @return a {@link TRANSPORT}
// */
// List<TRANSPORT> transport();
//
// /**
// * The method
// * @return a {@link METHOD}
// */
// METHOD method();
//
// /**
// * Return the list of headers
// * @return a Map of headers
// */
// HttpHeaders headers();
//
// /**
// * Return the list of query params
// * @return a Map of headers
// */
// Map<String, List<String>> queryString();
//
// /**
// * The list of {@link Encoder} to use before the request is sent.
// * @return The list of {@link Encoder}
// */
// List<Encoder<?,?>> encoders();
//
// /**
// * The list of {@link Decoder} to use before the request is sent.
// * @return The list of {@link Decoder}
// */
// List<Decoder<?,?>> decoders();
//
// /**
// * The targetted URI
// * @return the targetted URI
// */
// String uri();
//
// /**
// * The {@link FunctionResolver} associated with that request.
// * @return The {@link FunctionResolver}
// */
// FunctionResolver functionResolver();
//
// }
| import org.atmosphere.wasync.Request;
import org.testng.annotations.Test; | /*
* Copyright 2008-2022 Async-IO.org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.tests;
public class StreamingTest extends BaseTest {
@Override | // Path: wasync/src/main/java/org/atmosphere/wasync/Request.java
// public interface Request {
//
// public enum METHOD {GET, POST, TRACE, PUT, DELETE, OPTIONS}
// public enum TRANSPORT {WEBSOCKET, SSE, STREAMING, LONG_POLLING}
//
// /**
// * The list of transports to try
// * @return a {@link TRANSPORT}
// */
// List<TRANSPORT> transport();
//
// /**
// * The method
// * @return a {@link METHOD}
// */
// METHOD method();
//
// /**
// * Return the list of headers
// * @return a Map of headers
// */
// HttpHeaders headers();
//
// /**
// * Return the list of query params
// * @return a Map of headers
// */
// Map<String, List<String>> queryString();
//
// /**
// * The list of {@link Encoder} to use before the request is sent.
// * @return The list of {@link Encoder}
// */
// List<Encoder<?,?>> encoders();
//
// /**
// * The list of {@link Decoder} to use before the request is sent.
// * @return The list of {@link Decoder}
// */
// List<Decoder<?,?>> decoders();
//
// /**
// * The targetted URI
// * @return the targetted URI
// */
// String uri();
//
// /**
// * The {@link FunctionResolver} associated with that request.
// * @return The {@link FunctionResolver}
// */
// FunctionResolver functionResolver();
//
// }
// Path: wasync/src/test/java/org/atmosphere/tests/StreamingTest.java
import org.atmosphere.wasync.Request;
import org.testng.annotations.Test;
/*
* Copyright 2008-2022 Async-IO.org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.tests;
public class StreamingTest extends BaseTest {
@Override | Request.TRANSPORT transport() { |
Atmosphere/wasync | wasync/src/test/java/org/atmosphere/wasync/decoder/TrackMessageSizeDecoderTest.java | // Path: wasync/src/main/java/org/atmosphere/wasync/Decoder.java
// public final static class Decoded<T> {
// /**
// * Use this object to prevent the delivering of messages to {@link Function}
// */
// public final static Decoded ABORT = new Decoded(null, ACTION.ABORT);
//
// public enum ACTION {
// /**
// * Continue the decoding/dispatching process.
// */
// CONTINUE,
// /**
// * Do not dispatch the message to {@link Function}
// */
// ABORT}
//
// private final T decodedMessage;
// private final ACTION action;
//
// /**
// * Create a decoded object
// * @param decodedMessage the decoded message
// * @param action the action
// */
// public Decoded(T decodedMessage, ACTION action) {
// this.decodedMessage = decodedMessage;
// this.action = action;
// }
//
// /**
// * Create a decoded object with action set to {@link ACTION#CONTINUE}
// * @param decodedMessage the decoded Message
// */
// public Decoded(T decodedMessage) {
// this.decodedMessage = decodedMessage;
// this.action = ACTION.CONTINUE;
// }
//
// /**
// * Return the decoded message.
// * @return the decoded message.
// */
// public T decoded() {
// return decodedMessage;
// }
//
// /**
// * Return the action.
// * @return the action.
// */
// public ACTION action() {
// return action;
// }
// }
//
// Path: wasync/src/main/java/org/atmosphere/wasync/Event.java
// public enum Event {
//
// /**
// * This event is fired when the connection is open. This event is only fired once.
// */
// OPEN,
//
// /**
// * This event is fired when the connection gets closed. This event is only fired once.
// */
// CLOSE,
//
// /**
// * This event is fired every time a new message is received.
// */
// MESSAGE,
//
// /**
// * This event is fired every time the connection re-opened
// */
// REOPENED,
//
// /**
// * This event is fired when unexpected error happens. This event is only fired once.
// */
// ERROR,
//
// /**
// * This event is fire when the response's status is received. This event is only fired once.
// */
// STATUS,
//
// /**
// * This event is fire when the response's headers is received. This event is only fired once.
// */
// HEADERS,
//
// /**
// * This event is fire when the response's bytes are received.
// */
// MESSAGE_BYTES,
//
// /**
// * This event is fire when the connection has been established. The Transport propagated is the one that worked.
// * This event is only fired once.
// */
// TRANSPORT
//
// }
| import static org.testng.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.atmosphere.wasync.Decoder.Decoded;
import org.atmosphere.wasync.Event;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test; | /*
* Copyright 2008-2022 Async-IO.org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.wasync.decoder;
/**
*
* @author Sebastian Lövdahl <slovdahl@hibox.fi>
*/
public class TrackMessageSizeDecoderTest {
private final String DELIMITER = "|";
private TrackMessageSizeDecoder decoder;
@AfterMethod
public void tearDownMethod() throws Exception {
decoder = null;
}
@Test
public void testWithProtocol() {
decoder = new TrackMessageSizeDecoder(DELIMITER, true);
String message = "37|{\"message\":\"ab\",\"time\":1373900488808}";
| // Path: wasync/src/main/java/org/atmosphere/wasync/Decoder.java
// public final static class Decoded<T> {
// /**
// * Use this object to prevent the delivering of messages to {@link Function}
// */
// public final static Decoded ABORT = new Decoded(null, ACTION.ABORT);
//
// public enum ACTION {
// /**
// * Continue the decoding/dispatching process.
// */
// CONTINUE,
// /**
// * Do not dispatch the message to {@link Function}
// */
// ABORT}
//
// private final T decodedMessage;
// private final ACTION action;
//
// /**
// * Create a decoded object
// * @param decodedMessage the decoded message
// * @param action the action
// */
// public Decoded(T decodedMessage, ACTION action) {
// this.decodedMessage = decodedMessage;
// this.action = action;
// }
//
// /**
// * Create a decoded object with action set to {@link ACTION#CONTINUE}
// * @param decodedMessage the decoded Message
// */
// public Decoded(T decodedMessage) {
// this.decodedMessage = decodedMessage;
// this.action = ACTION.CONTINUE;
// }
//
// /**
// * Return the decoded message.
// * @return the decoded message.
// */
// public T decoded() {
// return decodedMessage;
// }
//
// /**
// * Return the action.
// * @return the action.
// */
// public ACTION action() {
// return action;
// }
// }
//
// Path: wasync/src/main/java/org/atmosphere/wasync/Event.java
// public enum Event {
//
// /**
// * This event is fired when the connection is open. This event is only fired once.
// */
// OPEN,
//
// /**
// * This event is fired when the connection gets closed. This event is only fired once.
// */
// CLOSE,
//
// /**
// * This event is fired every time a new message is received.
// */
// MESSAGE,
//
// /**
// * This event is fired every time the connection re-opened
// */
// REOPENED,
//
// /**
// * This event is fired when unexpected error happens. This event is only fired once.
// */
// ERROR,
//
// /**
// * This event is fire when the response's status is received. This event is only fired once.
// */
// STATUS,
//
// /**
// * This event is fire when the response's headers is received. This event is only fired once.
// */
// HEADERS,
//
// /**
// * This event is fire when the response's bytes are received.
// */
// MESSAGE_BYTES,
//
// /**
// * This event is fire when the connection has been established. The Transport propagated is the one that worked.
// * This event is only fired once.
// */
// TRANSPORT
//
// }
// Path: wasync/src/test/java/org/atmosphere/wasync/decoder/TrackMessageSizeDecoderTest.java
import static org.testng.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.atmosphere.wasync.Decoder.Decoded;
import org.atmosphere.wasync.Event;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
/*
* Copyright 2008-2022 Async-IO.org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.wasync.decoder;
/**
*
* @author Sebastian Lövdahl <slovdahl@hibox.fi>
*/
public class TrackMessageSizeDecoderTest {
private final String DELIMITER = "|";
private TrackMessageSizeDecoder decoder;
@AfterMethod
public void tearDownMethod() throws Exception {
decoder = null;
}
@Test
public void testWithProtocol() {
decoder = new TrackMessageSizeDecoder(DELIMITER, true);
String message = "37|{\"message\":\"ab\",\"time\":1373900488808}";
| Decoded<List<String>> result = decoder.decode(Event.MESSAGE, message); |
Atmosphere/wasync | wasync/src/test/java/org/atmosphere/wasync/decoder/TrackMessageSizeDecoderTest.java | // Path: wasync/src/main/java/org/atmosphere/wasync/Decoder.java
// public final static class Decoded<T> {
// /**
// * Use this object to prevent the delivering of messages to {@link Function}
// */
// public final static Decoded ABORT = new Decoded(null, ACTION.ABORT);
//
// public enum ACTION {
// /**
// * Continue the decoding/dispatching process.
// */
// CONTINUE,
// /**
// * Do not dispatch the message to {@link Function}
// */
// ABORT}
//
// private final T decodedMessage;
// private final ACTION action;
//
// /**
// * Create a decoded object
// * @param decodedMessage the decoded message
// * @param action the action
// */
// public Decoded(T decodedMessage, ACTION action) {
// this.decodedMessage = decodedMessage;
// this.action = action;
// }
//
// /**
// * Create a decoded object with action set to {@link ACTION#CONTINUE}
// * @param decodedMessage the decoded Message
// */
// public Decoded(T decodedMessage) {
// this.decodedMessage = decodedMessage;
// this.action = ACTION.CONTINUE;
// }
//
// /**
// * Return the decoded message.
// * @return the decoded message.
// */
// public T decoded() {
// return decodedMessage;
// }
//
// /**
// * Return the action.
// * @return the action.
// */
// public ACTION action() {
// return action;
// }
// }
//
// Path: wasync/src/main/java/org/atmosphere/wasync/Event.java
// public enum Event {
//
// /**
// * This event is fired when the connection is open. This event is only fired once.
// */
// OPEN,
//
// /**
// * This event is fired when the connection gets closed. This event is only fired once.
// */
// CLOSE,
//
// /**
// * This event is fired every time a new message is received.
// */
// MESSAGE,
//
// /**
// * This event is fired every time the connection re-opened
// */
// REOPENED,
//
// /**
// * This event is fired when unexpected error happens. This event is only fired once.
// */
// ERROR,
//
// /**
// * This event is fire when the response's status is received. This event is only fired once.
// */
// STATUS,
//
// /**
// * This event is fire when the response's headers is received. This event is only fired once.
// */
// HEADERS,
//
// /**
// * This event is fire when the response's bytes are received.
// */
// MESSAGE_BYTES,
//
// /**
// * This event is fire when the connection has been established. The Transport propagated is the one that worked.
// * This event is only fired once.
// */
// TRANSPORT
//
// }
| import static org.testng.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.atmosphere.wasync.Decoder.Decoded;
import org.atmosphere.wasync.Event;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test; | /*
* Copyright 2008-2022 Async-IO.org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.wasync.decoder;
/**
*
* @author Sebastian Lövdahl <slovdahl@hibox.fi>
*/
public class TrackMessageSizeDecoderTest {
private final String DELIMITER = "|";
private TrackMessageSizeDecoder decoder;
@AfterMethod
public void tearDownMethod() throws Exception {
decoder = null;
}
@Test
public void testWithProtocol() {
decoder = new TrackMessageSizeDecoder(DELIMITER, true);
String message = "37|{\"message\":\"ab\",\"time\":1373900488808}";
| // Path: wasync/src/main/java/org/atmosphere/wasync/Decoder.java
// public final static class Decoded<T> {
// /**
// * Use this object to prevent the delivering of messages to {@link Function}
// */
// public final static Decoded ABORT = new Decoded(null, ACTION.ABORT);
//
// public enum ACTION {
// /**
// * Continue the decoding/dispatching process.
// */
// CONTINUE,
// /**
// * Do not dispatch the message to {@link Function}
// */
// ABORT}
//
// private final T decodedMessage;
// private final ACTION action;
//
// /**
// * Create a decoded object
// * @param decodedMessage the decoded message
// * @param action the action
// */
// public Decoded(T decodedMessage, ACTION action) {
// this.decodedMessage = decodedMessage;
// this.action = action;
// }
//
// /**
// * Create a decoded object with action set to {@link ACTION#CONTINUE}
// * @param decodedMessage the decoded Message
// */
// public Decoded(T decodedMessage) {
// this.decodedMessage = decodedMessage;
// this.action = ACTION.CONTINUE;
// }
//
// /**
// * Return the decoded message.
// * @return the decoded message.
// */
// public T decoded() {
// return decodedMessage;
// }
//
// /**
// * Return the action.
// * @return the action.
// */
// public ACTION action() {
// return action;
// }
// }
//
// Path: wasync/src/main/java/org/atmosphere/wasync/Event.java
// public enum Event {
//
// /**
// * This event is fired when the connection is open. This event is only fired once.
// */
// OPEN,
//
// /**
// * This event is fired when the connection gets closed. This event is only fired once.
// */
// CLOSE,
//
// /**
// * This event is fired every time a new message is received.
// */
// MESSAGE,
//
// /**
// * This event is fired every time the connection re-opened
// */
// REOPENED,
//
// /**
// * This event is fired when unexpected error happens. This event is only fired once.
// */
// ERROR,
//
// /**
// * This event is fire when the response's status is received. This event is only fired once.
// */
// STATUS,
//
// /**
// * This event is fire when the response's headers is received. This event is only fired once.
// */
// HEADERS,
//
// /**
// * This event is fire when the response's bytes are received.
// */
// MESSAGE_BYTES,
//
// /**
// * This event is fire when the connection has been established. The Transport propagated is the one that worked.
// * This event is only fired once.
// */
// TRANSPORT
//
// }
// Path: wasync/src/test/java/org/atmosphere/wasync/decoder/TrackMessageSizeDecoderTest.java
import static org.testng.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.atmosphere.wasync.Decoder.Decoded;
import org.atmosphere.wasync.Event;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
/*
* Copyright 2008-2022 Async-IO.org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.wasync.decoder;
/**
*
* @author Sebastian Lövdahl <slovdahl@hibox.fi>
*/
public class TrackMessageSizeDecoderTest {
private final String DELIMITER = "|";
private TrackMessageSizeDecoder decoder;
@AfterMethod
public void tearDownMethod() throws Exception {
decoder = null;
}
@Test
public void testWithProtocol() {
decoder = new TrackMessageSizeDecoder(DELIMITER, true);
String message = "37|{\"message\":\"ab\",\"time\":1373900488808}";
| Decoded<List<String>> result = decoder.decode(Event.MESSAGE, message); |
Atmosphere/wasync | wasync/src/test/java/org/atmosphere/tests/WebSocketsTest.java | // Path: wasync/src/main/java/org/atmosphere/wasync/Request.java
// public interface Request {
//
// public enum METHOD {GET, POST, TRACE, PUT, DELETE, OPTIONS}
// public enum TRANSPORT {WEBSOCKET, SSE, STREAMING, LONG_POLLING}
//
// /**
// * The list of transports to try
// * @return a {@link TRANSPORT}
// */
// List<TRANSPORT> transport();
//
// /**
// * The method
// * @return a {@link METHOD}
// */
// METHOD method();
//
// /**
// * Return the list of headers
// * @return a Map of headers
// */
// HttpHeaders headers();
//
// /**
// * Return the list of query params
// * @return a Map of headers
// */
// Map<String, List<String>> queryString();
//
// /**
// * The list of {@link Encoder} to use before the request is sent.
// * @return The list of {@link Encoder}
// */
// List<Encoder<?,?>> encoders();
//
// /**
// * The list of {@link Decoder} to use before the request is sent.
// * @return The list of {@link Decoder}
// */
// List<Decoder<?,?>> decoders();
//
// /**
// * The targetted URI
// * @return the targetted URI
// */
// String uri();
//
// /**
// * The {@link FunctionResolver} associated with that request.
// * @return The {@link FunctionResolver}
// */
// FunctionResolver functionResolver();
//
// }
| import org.atmosphere.wasync.Request;
import org.testng.annotations.Test; | /*
* Copyright 2008-2022 Async-IO.org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.tests;
public class WebSocketsTest extends BaseTest {
@Override | // Path: wasync/src/main/java/org/atmosphere/wasync/Request.java
// public interface Request {
//
// public enum METHOD {GET, POST, TRACE, PUT, DELETE, OPTIONS}
// public enum TRANSPORT {WEBSOCKET, SSE, STREAMING, LONG_POLLING}
//
// /**
// * The list of transports to try
// * @return a {@link TRANSPORT}
// */
// List<TRANSPORT> transport();
//
// /**
// * The method
// * @return a {@link METHOD}
// */
// METHOD method();
//
// /**
// * Return the list of headers
// * @return a Map of headers
// */
// HttpHeaders headers();
//
// /**
// * Return the list of query params
// * @return a Map of headers
// */
// Map<String, List<String>> queryString();
//
// /**
// * The list of {@link Encoder} to use before the request is sent.
// * @return The list of {@link Encoder}
// */
// List<Encoder<?,?>> encoders();
//
// /**
// * The list of {@link Decoder} to use before the request is sent.
// * @return The list of {@link Decoder}
// */
// List<Decoder<?,?>> decoders();
//
// /**
// * The targetted URI
// * @return the targetted URI
// */
// String uri();
//
// /**
// * The {@link FunctionResolver} associated with that request.
// * @return The {@link FunctionResolver}
// */
// FunctionResolver functionResolver();
//
// }
// Path: wasync/src/test/java/org/atmosphere/tests/WebSocketsTest.java
import org.atmosphere.wasync.Request;
import org.testng.annotations.Test;
/*
* Copyright 2008-2022 Async-IO.org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.tests;
public class WebSocketsTest extends BaseTest {
@Override | Request.TRANSPORT transport() { |
Atmosphere/wasync | wasync/src/main/java/org/atmosphere/wasync/impl/DefaultFuture.java | // Path: wasync/src/main/java/org/atmosphere/wasync/Future.java
// public interface Future extends java.util.concurrent.Future<Socket> {
// /**
// * Send data to the remote Server.
// * @param message the message to fire
// * @return a {@link Future}
// * @throws java.io.IOException
// */
// Future fire(Object message) throws IOException;
// /**
// * Mark the future done. If an exception occurred, this method will throw it.
// * @return a {@link Future}
// */
// Future finishOrThrowException() throws IOException;
//
// /**
// * If an exception occurs, the {@link Transport} will set it using this method. An application can also
// * use that method to interrupt a blocking {@link Socket#open(Request)} operation. This operation
// * must unlock the current blocked thread.
// * @param t a {@link IOException}
// * @return a {@link Future}
// */
// Future ioException(IOException t);
//
// /**
// * Mark this instance as done.
// */
// void done();
//
// /**
// * Close the underlying {@link Socket}
// */
// void close();
// }
//
// Path: wasync/src/main/java/org/atmosphere/wasync/Socket.java
// public interface Socket {
//
// /**
// * The current state of the underlying Socket.
// */
// public enum STATUS {
// /**
// * The socket is not yet connected
// */
// INIT,
// /**
// * The socket is open and ready to send messages
// */
// OPEN,
// /**
// * The socket was closed and re-opened
// */
// REOPENED,
// /**
// * The socket is close
// */
// CLOSE,
// /**
// * The socket is broken
// */
// ERROR }
//
// /**
// * Send data to the remote Server. The object will first be delivered to the set of {@link Encoder}, and then send to the server.
// * The server's response will be delivered to the set of defined {@link Function} using the opened {@link Transport}, e.g for
// * {@link Request.TRANSPORT#WEBSOCKET}, the same connection will be re-used and, for others transports, the suspended connection.
// * @param data object to send
// * @return a {@link Future}
// * @throws IOException
// */
// Future fire(Object data) throws IOException;
//
// /**
// * Associate a {@link Function} with the Socket. When a response is received, the library will try to associated
// * the decoded message (decoded by {@link Decoder}) to the defined type of the {@link Function}
// * @param function a {@link Function}
// * @return this
// */
// Socket on(Function<?> function);
//
// /**
// * Associate a {@link Function} with the Socket. When a response is received, the library will try to associated
// * the decoded message (decoded by {@link Decoder}) to the defined type of the {@link Function}. The default messages
// * are defined by {@link org.atmosphere.wasync.Event} but handling of custom message can be done using a {@link FunctionResolver}
// * @param function a {@link Function}
// * @return this
// */
// Socket on(String functionMessage, Function<?> function);
//
// /**
// * Associate a {@link Function} with an {@link Event}. When the event happen the library will try to associated
// * the decoded event (decoded by {@link Decoder}) to the defined type of the {@link Function}. The default event
// * are defined by {@link org.atmosphere.wasync.Event} but handling of custom event can be done using a {@link FunctionResolver}
// * @param function a {@link Function}
// * @return this
// */
// Socket on(Event event, Function<?> function);
//
// /**
// * Connect to the remote Server using the {@link Request}'s information.
// * @param request a {@link Request}
// * @return this
// * @throws IOException in case the connect fails or a network failure occurs.
// */
// Socket open(Request request) throws IOException;
//
// /**
// * Connect to the remote Server using the {@link Request}'s information, will timeout if the connection failed to open
// * within a certain time.
// * @param request a {@link Request}
// * @param timeout the maximum time to wait
// * @param unit the time unit of the timeout argument
// * @return this
// * @throws IOException in case the connect fails or a network failure occurs.
// */
// Socket open(Request request, long timeout, TimeUnit unit) throws IOException;
//
// /**
// * Close this Socket, asynchronously.
// */
// void close();
//
// /**
// * Return the {@link STATUS} of this Socket.
// */
// STATUS status();
// }
| import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.atmosphere.wasync.Future;
import org.atmosphere.wasync.Socket; | done();
try {
if (ioException != null) {
throw ioException;
}
} finally {
ioException = null;
}
return this;
}
/**
* {@inheritDoc}
*/
@Override
public Future ioException(IOException t) {
ioException = t;
done();
return this;
}
protected void reset(){
done.set(false);
latch = new CountDownLatch(1);
}
/**
* {@inheritDoc}
*/
@Override | // Path: wasync/src/main/java/org/atmosphere/wasync/Future.java
// public interface Future extends java.util.concurrent.Future<Socket> {
// /**
// * Send data to the remote Server.
// * @param message the message to fire
// * @return a {@link Future}
// * @throws java.io.IOException
// */
// Future fire(Object message) throws IOException;
// /**
// * Mark the future done. If an exception occurred, this method will throw it.
// * @return a {@link Future}
// */
// Future finishOrThrowException() throws IOException;
//
// /**
// * If an exception occurs, the {@link Transport} will set it using this method. An application can also
// * use that method to interrupt a blocking {@link Socket#open(Request)} operation. This operation
// * must unlock the current blocked thread.
// * @param t a {@link IOException}
// * @return a {@link Future}
// */
// Future ioException(IOException t);
//
// /**
// * Mark this instance as done.
// */
// void done();
//
// /**
// * Close the underlying {@link Socket}
// */
// void close();
// }
//
// Path: wasync/src/main/java/org/atmosphere/wasync/Socket.java
// public interface Socket {
//
// /**
// * The current state of the underlying Socket.
// */
// public enum STATUS {
// /**
// * The socket is not yet connected
// */
// INIT,
// /**
// * The socket is open and ready to send messages
// */
// OPEN,
// /**
// * The socket was closed and re-opened
// */
// REOPENED,
// /**
// * The socket is close
// */
// CLOSE,
// /**
// * The socket is broken
// */
// ERROR }
//
// /**
// * Send data to the remote Server. The object will first be delivered to the set of {@link Encoder}, and then send to the server.
// * The server's response will be delivered to the set of defined {@link Function} using the opened {@link Transport}, e.g for
// * {@link Request.TRANSPORT#WEBSOCKET}, the same connection will be re-used and, for others transports, the suspended connection.
// * @param data object to send
// * @return a {@link Future}
// * @throws IOException
// */
// Future fire(Object data) throws IOException;
//
// /**
// * Associate a {@link Function} with the Socket. When a response is received, the library will try to associated
// * the decoded message (decoded by {@link Decoder}) to the defined type of the {@link Function}
// * @param function a {@link Function}
// * @return this
// */
// Socket on(Function<?> function);
//
// /**
// * Associate a {@link Function} with the Socket. When a response is received, the library will try to associated
// * the decoded message (decoded by {@link Decoder}) to the defined type of the {@link Function}. The default messages
// * are defined by {@link org.atmosphere.wasync.Event} but handling of custom message can be done using a {@link FunctionResolver}
// * @param function a {@link Function}
// * @return this
// */
// Socket on(String functionMessage, Function<?> function);
//
// /**
// * Associate a {@link Function} with an {@link Event}. When the event happen the library will try to associated
// * the decoded event (decoded by {@link Decoder}) to the defined type of the {@link Function}. The default event
// * are defined by {@link org.atmosphere.wasync.Event} but handling of custom event can be done using a {@link FunctionResolver}
// * @param function a {@link Function}
// * @return this
// */
// Socket on(Event event, Function<?> function);
//
// /**
// * Connect to the remote Server using the {@link Request}'s information.
// * @param request a {@link Request}
// * @return this
// * @throws IOException in case the connect fails or a network failure occurs.
// */
// Socket open(Request request) throws IOException;
//
// /**
// * Connect to the remote Server using the {@link Request}'s information, will timeout if the connection failed to open
// * within a certain time.
// * @param request a {@link Request}
// * @param timeout the maximum time to wait
// * @param unit the time unit of the timeout argument
// * @return this
// * @throws IOException in case the connect fails or a network failure occurs.
// */
// Socket open(Request request, long timeout, TimeUnit unit) throws IOException;
//
// /**
// * Close this Socket, asynchronously.
// */
// void close();
//
// /**
// * Return the {@link STATUS} of this Socket.
// */
// STATUS status();
// }
// Path: wasync/src/main/java/org/atmosphere/wasync/impl/DefaultFuture.java
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.atmosphere.wasync.Future;
import org.atmosphere.wasync.Socket;
done();
try {
if (ioException != null) {
throw ioException;
}
} finally {
ioException = null;
}
return this;
}
/**
* {@inheritDoc}
*/
@Override
public Future ioException(IOException t) {
ioException = t;
done();
return this;
}
protected void reset(){
done.set(false);
latch = new CountDownLatch(1);
}
/**
* {@inheritDoc}
*/
@Override | public Socket get() throws InterruptedException, ExecutionException { |
yyqian/imagine | src/main/java/com/yyqian/imagine/repository/PostRepository.java | // Path: src/main/java/com/yyqian/imagine/po/Post.java
// @Entity
// @Table(name = "post")
// public class Post extends BaseUGC {
//
// @Column(name = "title", nullable = false)
// private String title;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "kind", nullable = false)
// private Kind kind;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "category")
// private Category category;
//
// // map to comment, bidirectional
// // @OneToMany tells the persistence provider this is an association and not an attribute.
// @OneToMany(mappedBy = "post", fetch = FetchType.EAGER, orphanRemoval = true, cascade =
// {CascadeType.PERSIST, CascadeType.MERGE})
// @JsonIgnore
// private List<Comment> comments = new ArrayList<Comment>();
//
// @Column(name = "comment_count", nullable = false)
// private int commentCount = 0;
//
// @Column(name = "site")
// private String site;
//
// // The default constructor only exists for the sake of JPA. You won’t use it directly, so it is
// // designated as protected.
// public Post() {
// }
//
// public Post(String title, String content, User user, Kind kind) {
// super(content, user);
// this.title = title;
// this.kind = kind;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public static enum Kind {PLAIN, LINK}
//
// public static enum Category {SHOW, ASK}
//
// public String getTitle() {
// return title;
// }
//
// public Kind getKind() {
// return kind;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public List<Comment> getComments() {
// return comments;
// }
//
// public int getCommentCount() {
// return commentCount;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public void setKind(Kind kind) {
// this.kind = kind;
// }
//
// public void setCategory(Category category) {
// this.category = category;
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// public void increaseCommentCount() {
// commentCount = commentCount + 1;
// }
//
// public void decreaseCommentCount() {
// if (commentCount > 0) {
// commentCount = commentCount - 1;
// }
// }
//
// public String getSite() {
// return site;
// }
//
// public void setSite(String site) {
// this.site = site;
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
| import com.yyqian.imagine.po.Post;
import com.yyqian.imagine.po.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Collection; | package com.yyqian.imagine.repository;
/**
* Created by yyqian on 12/5/15.
* In a typical Java application, you’d expect to write a class that implements PostRepository.
* But that’s what makes Spring Data JPA so powerful: You don’t have to write an implementation of
* the repository interface. Spring Data JPA creates an implementation on the fly when you run
* the application.
* In summary:
* 1. Interface-based programming entity
* 2. No implementation required
* 3. Queries derived from method names
* CrudRepository: exposed CRUD methods
* PagingAndSortingRepository: exposed CRUD methods and paging ones
* JpaRepository: findAll() will return List<T>, the transaction timeout for save() is customized
* to 10 secs.
*
* Repository annotation is optional, just for the sake of Intellij IDEA. IDEA will complain without it.
*/
@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
Collection<Post> findBySite(String site); | // Path: src/main/java/com/yyqian/imagine/po/Post.java
// @Entity
// @Table(name = "post")
// public class Post extends BaseUGC {
//
// @Column(name = "title", nullable = false)
// private String title;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "kind", nullable = false)
// private Kind kind;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "category")
// private Category category;
//
// // map to comment, bidirectional
// // @OneToMany tells the persistence provider this is an association and not an attribute.
// @OneToMany(mappedBy = "post", fetch = FetchType.EAGER, orphanRemoval = true, cascade =
// {CascadeType.PERSIST, CascadeType.MERGE})
// @JsonIgnore
// private List<Comment> comments = new ArrayList<Comment>();
//
// @Column(name = "comment_count", nullable = false)
// private int commentCount = 0;
//
// @Column(name = "site")
// private String site;
//
// // The default constructor only exists for the sake of JPA. You won’t use it directly, so it is
// // designated as protected.
// public Post() {
// }
//
// public Post(String title, String content, User user, Kind kind) {
// super(content, user);
// this.title = title;
// this.kind = kind;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public static enum Kind {PLAIN, LINK}
//
// public static enum Category {SHOW, ASK}
//
// public String getTitle() {
// return title;
// }
//
// public Kind getKind() {
// return kind;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public List<Comment> getComments() {
// return comments;
// }
//
// public int getCommentCount() {
// return commentCount;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public void setKind(Kind kind) {
// this.kind = kind;
// }
//
// public void setCategory(Category category) {
// this.category = category;
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// public void increaseCommentCount() {
// commentCount = commentCount + 1;
// }
//
// public void decreaseCommentCount() {
// if (commentCount > 0) {
// commentCount = commentCount - 1;
// }
// }
//
// public String getSite() {
// return site;
// }
//
// public void setSite(String site) {
// this.site = site;
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
// Path: src/main/java/com/yyqian/imagine/repository/PostRepository.java
import com.yyqian.imagine.po.Post;
import com.yyqian.imagine.po.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Collection;
package com.yyqian.imagine.repository;
/**
* Created by yyqian on 12/5/15.
* In a typical Java application, you’d expect to write a class that implements PostRepository.
* But that’s what makes Spring Data JPA so powerful: You don’t have to write an implementation of
* the repository interface. Spring Data JPA creates an implementation on the fly when you run
* the application.
* In summary:
* 1. Interface-based programming entity
* 2. No implementation required
* 3. Queries derived from method names
* CrudRepository: exposed CRUD methods
* PagingAndSortingRepository: exposed CRUD methods and paging ones
* JpaRepository: findAll() will return List<T>, the transaction timeout for save() is customized
* to 10 secs.
*
* Repository annotation is optional, just for the sake of Intellij IDEA. IDEA will complain without it.
*/
@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
Collection<Post> findBySite(String site); | Collection<Post> findByUser(User user); |
yyqian/imagine | src/main/java/com/yyqian/imagine/dto/validator/PostCreateFormValidator.java | // Path: src/main/java/com/yyqian/imagine/dto/PostCreateForm.java
// public class PostCreateForm {
//
// @NotEmpty
// private String title = "";
//
// private String url;
//
// private String text;
//
// public PostCreateForm() {
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title.trim();
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url.trim();
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text.trim();
// }
//
// }
| import com.yyqian.imagine.dto.PostCreateForm;
import org.apache.commons.validator.routines.UrlValidator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator; | package com.yyqian.imagine.dto.validator;
/**
* Created on 1/8/16.
*
* @author Yinyin Qian
*/
@Component
public class PostCreateFormValidator implements Validator {
private String[] schemes = {"http", "https"};
private UrlValidator urlValidator = new UrlValidator(schemes);
@Override
public boolean supports(Class<?> clazz) { | // Path: src/main/java/com/yyqian/imagine/dto/PostCreateForm.java
// public class PostCreateForm {
//
// @NotEmpty
// private String title = "";
//
// private String url;
//
// private String text;
//
// public PostCreateForm() {
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title.trim();
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url.trim();
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text.trim();
// }
//
// }
// Path: src/main/java/com/yyqian/imagine/dto/validator/PostCreateFormValidator.java
import com.yyqian.imagine.dto.PostCreateForm;
import org.apache.commons.validator.routines.UrlValidator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
package com.yyqian.imagine.dto.validator;
/**
* Created on 1/8/16.
*
* @author Yinyin Qian
*/
@Component
public class PostCreateFormValidator implements Validator {
private String[] schemes = {"http", "https"};
private UrlValidator urlValidator = new UrlValidator(schemes);
@Override
public boolean supports(Class<?> clazz) { | return clazz.equals(PostCreateForm.class); |
yyqian/imagine | src/main/java/com/yyqian/imagine/utility/RockAndRoll.java | // Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/VoteService.java
// public interface VoteService {
//
// PostVote createPostVote(PostVote postVote);
//
// CommentVote createCommentVote(CommentVote commentVote);
//
// PostVote upVotePostById(Long id);
//
// PostVote downVotePostById(Long id);
//
// CommentVote upVoteCommentById(Long id);
//
// CommentVote downVoteCommentById(Long id);
//
// boolean isPostVotedByCurrentUser(Post post);
//
// boolean isCommentVotedByCurrentUser(Comment comment);
//
// Collection<Post> getPostsVotedByCurrentUser();
//
// Collection<Comment> getCommentsVotedByCurrentUser();
//
// }
| import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.service.VoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream; | package com.yyqian.imagine.utility;
/**
* Created by yyqian on 12/5/15.
* runs in dev env
*/
@Component
@Profile(value = {"dev", "debug"})
public class RockAndRoll implements CommandLineRunner {
@Autowired | // Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/VoteService.java
// public interface VoteService {
//
// PostVote createPostVote(PostVote postVote);
//
// CommentVote createCommentVote(CommentVote commentVote);
//
// PostVote upVotePostById(Long id);
//
// PostVote downVotePostById(Long id);
//
// CommentVote upVoteCommentById(Long id);
//
// CommentVote downVoteCommentById(Long id);
//
// boolean isPostVotedByCurrentUser(Post post);
//
// boolean isCommentVotedByCurrentUser(Comment comment);
//
// Collection<Post> getPostsVotedByCurrentUser();
//
// Collection<Comment> getCommentsVotedByCurrentUser();
//
// }
// Path: src/main/java/com/yyqian/imagine/utility/RockAndRoll.java
import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.service.VoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
package com.yyqian.imagine.utility;
/**
* Created by yyqian on 12/5/15.
* runs in dev env
*/
@Component
@Profile(value = {"dev", "debug"})
public class RockAndRoll implements CommandLineRunner {
@Autowired | private PostService postService; |
yyqian/imagine | src/main/java/com/yyqian/imagine/utility/RockAndRoll.java | // Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/VoteService.java
// public interface VoteService {
//
// PostVote createPostVote(PostVote postVote);
//
// CommentVote createCommentVote(CommentVote commentVote);
//
// PostVote upVotePostById(Long id);
//
// PostVote downVotePostById(Long id);
//
// CommentVote upVoteCommentById(Long id);
//
// CommentVote downVoteCommentById(Long id);
//
// boolean isPostVotedByCurrentUser(Post post);
//
// boolean isCommentVotedByCurrentUser(Comment comment);
//
// Collection<Post> getPostsVotedByCurrentUser();
//
// Collection<Comment> getCommentsVotedByCurrentUser();
//
// }
| import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.service.VoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream; | package com.yyqian.imagine.utility;
/**
* Created by yyqian on 12/5/15.
* runs in dev env
*/
@Component
@Profile(value = {"dev", "debug"})
public class RockAndRoll implements CommandLineRunner {
@Autowired
private PostService postService;
@Autowired | // Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/VoteService.java
// public interface VoteService {
//
// PostVote createPostVote(PostVote postVote);
//
// CommentVote createCommentVote(CommentVote commentVote);
//
// PostVote upVotePostById(Long id);
//
// PostVote downVotePostById(Long id);
//
// CommentVote upVoteCommentById(Long id);
//
// CommentVote downVoteCommentById(Long id);
//
// boolean isPostVotedByCurrentUser(Post post);
//
// boolean isCommentVotedByCurrentUser(Comment comment);
//
// Collection<Post> getPostsVotedByCurrentUser();
//
// Collection<Comment> getCommentsVotedByCurrentUser();
//
// }
// Path: src/main/java/com/yyqian/imagine/utility/RockAndRoll.java
import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.service.VoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
package com.yyqian.imagine.utility;
/**
* Created by yyqian on 12/5/15.
* runs in dev env
*/
@Component
@Profile(value = {"dev", "debug"})
public class RockAndRoll implements CommandLineRunner {
@Autowired
private PostService postService;
@Autowired | private UserService userService; |
yyqian/imagine | src/main/java/com/yyqian/imagine/utility/RockAndRoll.java | // Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/VoteService.java
// public interface VoteService {
//
// PostVote createPostVote(PostVote postVote);
//
// CommentVote createCommentVote(CommentVote commentVote);
//
// PostVote upVotePostById(Long id);
//
// PostVote downVotePostById(Long id);
//
// CommentVote upVoteCommentById(Long id);
//
// CommentVote downVoteCommentById(Long id);
//
// boolean isPostVotedByCurrentUser(Post post);
//
// boolean isCommentVotedByCurrentUser(Comment comment);
//
// Collection<Post> getPostsVotedByCurrentUser();
//
// Collection<Comment> getCommentsVotedByCurrentUser();
//
// }
| import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.service.VoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream; | package com.yyqian.imagine.utility;
/**
* Created by yyqian on 12/5/15.
* runs in dev env
*/
@Component
@Profile(value = {"dev", "debug"})
public class RockAndRoll implements CommandLineRunner {
@Autowired
private PostService postService;
@Autowired
private UserService userService;
@Autowired | // Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/VoteService.java
// public interface VoteService {
//
// PostVote createPostVote(PostVote postVote);
//
// CommentVote createCommentVote(CommentVote commentVote);
//
// PostVote upVotePostById(Long id);
//
// PostVote downVotePostById(Long id);
//
// CommentVote upVoteCommentById(Long id);
//
// CommentVote downVoteCommentById(Long id);
//
// boolean isPostVotedByCurrentUser(Post post);
//
// boolean isCommentVotedByCurrentUser(Comment comment);
//
// Collection<Post> getPostsVotedByCurrentUser();
//
// Collection<Comment> getCommentsVotedByCurrentUser();
//
// }
// Path: src/main/java/com/yyqian/imagine/utility/RockAndRoll.java
import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.service.VoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
package com.yyqian.imagine.utility;
/**
* Created by yyqian on 12/5/15.
* runs in dev env
*/
@Component
@Profile(value = {"dev", "debug"})
public class RockAndRoll implements CommandLineRunner {
@Autowired
private PostService postService;
@Autowired
private UserService userService;
@Autowired | private CommentService commentService; |
yyqian/imagine | src/main/java/com/yyqian/imagine/utility/RockAndRoll.java | // Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/VoteService.java
// public interface VoteService {
//
// PostVote createPostVote(PostVote postVote);
//
// CommentVote createCommentVote(CommentVote commentVote);
//
// PostVote upVotePostById(Long id);
//
// PostVote downVotePostById(Long id);
//
// CommentVote upVoteCommentById(Long id);
//
// CommentVote downVoteCommentById(Long id);
//
// boolean isPostVotedByCurrentUser(Post post);
//
// boolean isCommentVotedByCurrentUser(Comment comment);
//
// Collection<Post> getPostsVotedByCurrentUser();
//
// Collection<Comment> getCommentsVotedByCurrentUser();
//
// }
| import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.service.VoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream; | package com.yyqian.imagine.utility;
/**
* Created by yyqian on 12/5/15.
* runs in dev env
*/
@Component
@Profile(value = {"dev", "debug"})
public class RockAndRoll implements CommandLineRunner {
@Autowired
private PostService postService;
@Autowired
private UserService userService;
@Autowired
private CommentService commentService;
@Autowired | // Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/VoteService.java
// public interface VoteService {
//
// PostVote createPostVote(PostVote postVote);
//
// CommentVote createCommentVote(CommentVote commentVote);
//
// PostVote upVotePostById(Long id);
//
// PostVote downVotePostById(Long id);
//
// CommentVote upVoteCommentById(Long id);
//
// CommentVote downVoteCommentById(Long id);
//
// boolean isPostVotedByCurrentUser(Post post);
//
// boolean isCommentVotedByCurrentUser(Comment comment);
//
// Collection<Post> getPostsVotedByCurrentUser();
//
// Collection<Comment> getCommentsVotedByCurrentUser();
//
// }
// Path: src/main/java/com/yyqian/imagine/utility/RockAndRoll.java
import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.service.VoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
package com.yyqian.imagine.utility;
/**
* Created by yyqian on 12/5/15.
* runs in dev env
*/
@Component
@Profile(value = {"dev", "debug"})
public class RockAndRoll implements CommandLineRunner {
@Autowired
private PostService postService;
@Autowired
private UserService userService;
@Autowired
private CommentService commentService;
@Autowired | private VoteService voteService; |
yyqian/imagine | src/main/java/com/yyqian/imagine/utility/RockAndRoll.java | // Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/VoteService.java
// public interface VoteService {
//
// PostVote createPostVote(PostVote postVote);
//
// CommentVote createCommentVote(CommentVote commentVote);
//
// PostVote upVotePostById(Long id);
//
// PostVote downVotePostById(Long id);
//
// CommentVote upVoteCommentById(Long id);
//
// CommentVote downVoteCommentById(Long id);
//
// boolean isPostVotedByCurrentUser(Post post);
//
// boolean isCommentVotedByCurrentUser(Comment comment);
//
// Collection<Post> getPostsVotedByCurrentUser();
//
// Collection<Comment> getCommentsVotedByCurrentUser();
//
// }
| import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.service.VoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream; | package com.yyqian.imagine.utility;
/**
* Created by yyqian on 12/5/15.
* runs in dev env
*/
@Component
@Profile(value = {"dev", "debug"})
public class RockAndRoll implements CommandLineRunner {
@Autowired
private PostService postService;
@Autowired
private UserService userService;
@Autowired
private CommentService commentService;
@Autowired
private VoteService voteService;
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
private List<User> users = new ArrayList<>();
private List<Post> posts = new ArrayList<>();
private List<Comment> comments = new ArrayList<>();
private final int userLength = 10;
private final int postHalfLength = 25;
private final int postLength = postHalfLength * 2;
private final int commentQuarterLength = 100;
private final int commentLength = commentQuarterLength * 4;
public void run(String... args) {
logger.info("Generating sample-data");
genUsers();
genPosts();
genComments();
genVotes();
logger.info("Data generated. Let's Rock!");
}
private void genUsers() { | // Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/VoteService.java
// public interface VoteService {
//
// PostVote createPostVote(PostVote postVote);
//
// CommentVote createCommentVote(CommentVote commentVote);
//
// PostVote upVotePostById(Long id);
//
// PostVote downVotePostById(Long id);
//
// CommentVote upVoteCommentById(Long id);
//
// CommentVote downVoteCommentById(Long id);
//
// boolean isPostVotedByCurrentUser(Post post);
//
// boolean isCommentVotedByCurrentUser(Comment comment);
//
// Collection<Post> getPostsVotedByCurrentUser();
//
// Collection<Comment> getCommentsVotedByCurrentUser();
//
// }
// Path: src/main/java/com/yyqian/imagine/utility/RockAndRoll.java
import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.service.VoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
package com.yyqian.imagine.utility;
/**
* Created by yyqian on 12/5/15.
* runs in dev env
*/
@Component
@Profile(value = {"dev", "debug"})
public class RockAndRoll implements CommandLineRunner {
@Autowired
private PostService postService;
@Autowired
private UserService userService;
@Autowired
private CommentService commentService;
@Autowired
private VoteService voteService;
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
private List<User> users = new ArrayList<>();
private List<Post> posts = new ArrayList<>();
private List<Comment> comments = new ArrayList<>();
private final int userLength = 10;
private final int postHalfLength = 25;
private final int postLength = postHalfLength * 2;
private final int commentQuarterLength = 100;
private final int commentLength = commentQuarterLength * 4;
public void run(String... args) {
logger.info("Generating sample-data");
genUsers();
genPosts();
genComments();
genVotes();
logger.info("Data generated. Let's Rock!");
}
private void genUsers() { | UserCreateForm form = new UserCreateForm(); |
yyqian/imagine | src/main/java/com/yyqian/imagine/dto/validator/UserCreateFormValidator.java | // Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
| import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator; | package com.yyqian.imagine.dto.validator;
/**
* Created by yyqian on 12/15/15.
*/
@Component
public class UserCreateFormValidator implements Validator {
private static final int MINIMUM_USERNAME_LENGTH = 3;
private static final int MINIMUM_PASSWORD_LENGTH = 6; | // Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
// Path: src/main/java/com/yyqian/imagine/dto/validator/UserCreateFormValidator.java
import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
package com.yyqian.imagine.dto.validator;
/**
* Created by yyqian on 12/15/15.
*/
@Component
public class UserCreateFormValidator implements Validator {
private static final int MINIMUM_USERNAME_LENGTH = 3;
private static final int MINIMUM_PASSWORD_LENGTH = 6; | private final UserService userService; |
yyqian/imagine | src/main/java/com/yyqian/imagine/dto/validator/UserCreateFormValidator.java | // Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
| import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator; | package com.yyqian.imagine.dto.validator;
/**
* Created by yyqian on 12/15/15.
*/
@Component
public class UserCreateFormValidator implements Validator {
private static final int MINIMUM_USERNAME_LENGTH = 3;
private static final int MINIMUM_PASSWORD_LENGTH = 6;
private final UserService userService;
@Autowired
public UserCreateFormValidator(UserService userService) {
this.userService = userService;
}
@Override
public boolean supports(Class<?> clazz) { | // Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
// Path: src/main/java/com/yyqian/imagine/dto/validator/UserCreateFormValidator.java
import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
package com.yyqian.imagine.dto.validator;
/**
* Created by yyqian on 12/15/15.
*/
@Component
public class UserCreateFormValidator implements Validator {
private static final int MINIMUM_USERNAME_LENGTH = 3;
private static final int MINIMUM_PASSWORD_LENGTH = 6;
private final UserService userService;
@Autowired
public UserCreateFormValidator(UserService userService) {
this.userService = userService;
}
@Override
public boolean supports(Class<?> clazz) { | return clazz.equals(UserCreateForm.class); |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/impl/MailServiceImpl.java | // Path: src/main/java/com/yyqian/imagine/exception/BadRequestException.java
// public class BadRequestException extends RuntimeException {
// public BadRequestException() {
// }
//
// public BadRequestException(String message) {
// super(message);
// }
//
// public BadRequestException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public BadRequestException(Throwable cause) {
// super(cause);
// }
//
// public BadRequestException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/exception/InternalServerErrorException.java
// public class InternalServerErrorException extends RuntimeException {
// public InternalServerErrorException() {
// }
//
// public InternalServerErrorException(String message) {
// super(message);
// }
//
// public InternalServerErrorException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InternalServerErrorException(Throwable cause) {
// super(cause);
// }
//
// public InternalServerErrorException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/service/MailService.java
// public interface MailService {
//
// void sendHtml(String to, String subject, String templateName, Map<String, Object> model);
//
// void sendRestPasswordEmail(String mailTo, String url);
//
// }
| import com.yyqian.imagine.exception.BadRequestException;
import com.yyqian.imagine.exception.InternalServerErrorException;
import com.yyqian.imagine.service.MailService;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map; | package com.yyqian.imagine.service.impl;
/**
* Created on 12/30/15.
*
* @author Yinyin Qian
*/
@Service
public class MailServiceImpl implements MailService {
@Value("${app.name}")
private String APP_NAME;
@Autowired
private JavaMailSenderImpl mailSender;
@Autowired
private TemplateEngine templateEngine;
@Override
public void sendHtml(String to, String subject, String templateName, Map<String, Object> model) {
if (!EmailValidator.getInstance().isValid(to)) { | // Path: src/main/java/com/yyqian/imagine/exception/BadRequestException.java
// public class BadRequestException extends RuntimeException {
// public BadRequestException() {
// }
//
// public BadRequestException(String message) {
// super(message);
// }
//
// public BadRequestException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public BadRequestException(Throwable cause) {
// super(cause);
// }
//
// public BadRequestException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/exception/InternalServerErrorException.java
// public class InternalServerErrorException extends RuntimeException {
// public InternalServerErrorException() {
// }
//
// public InternalServerErrorException(String message) {
// super(message);
// }
//
// public InternalServerErrorException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InternalServerErrorException(Throwable cause) {
// super(cause);
// }
//
// public InternalServerErrorException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/service/MailService.java
// public interface MailService {
//
// void sendHtml(String to, String subject, String templateName, Map<String, Object> model);
//
// void sendRestPasswordEmail(String mailTo, String url);
//
// }
// Path: src/main/java/com/yyqian/imagine/service/impl/MailServiceImpl.java
import com.yyqian.imagine.exception.BadRequestException;
import com.yyqian.imagine.exception.InternalServerErrorException;
import com.yyqian.imagine.service.MailService;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;
package com.yyqian.imagine.service.impl;
/**
* Created on 12/30/15.
*
* @author Yinyin Qian
*/
@Service
public class MailServiceImpl implements MailService {
@Value("${app.name}")
private String APP_NAME;
@Autowired
private JavaMailSenderImpl mailSender;
@Autowired
private TemplateEngine templateEngine;
@Override
public void sendHtml(String to, String subject, String templateName, Map<String, Object> model) {
if (!EmailValidator.getInstance().isValid(to)) { | throw new BadRequestException("Invalid email address."); |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/impl/MailServiceImpl.java | // Path: src/main/java/com/yyqian/imagine/exception/BadRequestException.java
// public class BadRequestException extends RuntimeException {
// public BadRequestException() {
// }
//
// public BadRequestException(String message) {
// super(message);
// }
//
// public BadRequestException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public BadRequestException(Throwable cause) {
// super(cause);
// }
//
// public BadRequestException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/exception/InternalServerErrorException.java
// public class InternalServerErrorException extends RuntimeException {
// public InternalServerErrorException() {
// }
//
// public InternalServerErrorException(String message) {
// super(message);
// }
//
// public InternalServerErrorException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InternalServerErrorException(Throwable cause) {
// super(cause);
// }
//
// public InternalServerErrorException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/service/MailService.java
// public interface MailService {
//
// void sendHtml(String to, String subject, String templateName, Map<String, Object> model);
//
// void sendRestPasswordEmail(String mailTo, String url);
//
// }
| import com.yyqian.imagine.exception.BadRequestException;
import com.yyqian.imagine.exception.InternalServerErrorException;
import com.yyqian.imagine.service.MailService;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map; | package com.yyqian.imagine.service.impl;
/**
* Created on 12/30/15.
*
* @author Yinyin Qian
*/
@Service
public class MailServiceImpl implements MailService {
@Value("${app.name}")
private String APP_NAME;
@Autowired
private JavaMailSenderImpl mailSender;
@Autowired
private TemplateEngine templateEngine;
@Override
public void sendHtml(String to, String subject, String templateName, Map<String, Object> model) {
if (!EmailValidator.getInstance().isValid(to)) {
throw new BadRequestException("Invalid email address.");
}
final Context ctx = new Context();
ctx.setVariables(model);
final String emailText = templateEngine.process(templateName, ctx);
final MimeMessage msg = mailSender.createMimeMessage();
try {
final MimeMessageHelper helper = new MimeMessageHelper(msg, true);
helper.setFrom(mailSender.getUsername());
helper.setTo(to);
helper.setSubject(subject);
helper.setText(emailText, true);
} catch (MessagingException ex) { | // Path: src/main/java/com/yyqian/imagine/exception/BadRequestException.java
// public class BadRequestException extends RuntimeException {
// public BadRequestException() {
// }
//
// public BadRequestException(String message) {
// super(message);
// }
//
// public BadRequestException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public BadRequestException(Throwable cause) {
// super(cause);
// }
//
// public BadRequestException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/exception/InternalServerErrorException.java
// public class InternalServerErrorException extends RuntimeException {
// public InternalServerErrorException() {
// }
//
// public InternalServerErrorException(String message) {
// super(message);
// }
//
// public InternalServerErrorException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InternalServerErrorException(Throwable cause) {
// super(cause);
// }
//
// public InternalServerErrorException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/service/MailService.java
// public interface MailService {
//
// void sendHtml(String to, String subject, String templateName, Map<String, Object> model);
//
// void sendRestPasswordEmail(String mailTo, String url);
//
// }
// Path: src/main/java/com/yyqian/imagine/service/impl/MailServiceImpl.java
import com.yyqian.imagine.exception.BadRequestException;
import com.yyqian.imagine.exception.InternalServerErrorException;
import com.yyqian.imagine.service.MailService;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;
package com.yyqian.imagine.service.impl;
/**
* Created on 12/30/15.
*
* @author Yinyin Qian
*/
@Service
public class MailServiceImpl implements MailService {
@Value("${app.name}")
private String APP_NAME;
@Autowired
private JavaMailSenderImpl mailSender;
@Autowired
private TemplateEngine templateEngine;
@Override
public void sendHtml(String to, String subject, String templateName, Map<String, Object> model) {
if (!EmailValidator.getInstance().isValid(to)) {
throw new BadRequestException("Invalid email address.");
}
final Context ctx = new Context();
ctx.setVariables(model);
final String emailText = templateEngine.process(templateName, ctx);
final MimeMessage msg = mailSender.createMimeMessage();
try {
final MimeMessageHelper helper = new MimeMessageHelper(msg, true);
helper.setFrom(mailSender.getUsername());
helper.setTo(to);
helper.setSubject(subject);
helper.setText(emailText, true);
} catch (MessagingException ex) { | throw new InternalServerErrorException(ex.getMessage()); |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/impl/SecurityServiceImpl.java | // Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long> {
// Optional<User> findOneByUsername(String username);
// }
//
// Path: src/main/java/com/yyqian/imagine/service/SecurityService.java
// public interface SecurityService {
//
// String getUsername();
//
// String getAuthorities();
//
// User getUser();
//
// boolean isLoggedIn();
//
// }
| import com.yyqian.imagine.po.User;
import com.yyqian.imagine.repository.UserRepository;
import com.yyqian.imagine.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import java.util.NoSuchElementException; | package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class SecurityServiceImpl implements SecurityService {
@Autowired | // Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long> {
// Optional<User> findOneByUsername(String username);
// }
//
// Path: src/main/java/com/yyqian/imagine/service/SecurityService.java
// public interface SecurityService {
//
// String getUsername();
//
// String getAuthorities();
//
// User getUser();
//
// boolean isLoggedIn();
//
// }
// Path: src/main/java/com/yyqian/imagine/service/impl/SecurityServiceImpl.java
import com.yyqian.imagine.po.User;
import com.yyqian.imagine.repository.UserRepository;
import com.yyqian.imagine.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import java.util.NoSuchElementException;
package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class SecurityServiceImpl implements SecurityService {
@Autowired | private UserRepository userRepository; |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/impl/SecurityServiceImpl.java | // Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long> {
// Optional<User> findOneByUsername(String username);
// }
//
// Path: src/main/java/com/yyqian/imagine/service/SecurityService.java
// public interface SecurityService {
//
// String getUsername();
//
// String getAuthorities();
//
// User getUser();
//
// boolean isLoggedIn();
//
// }
| import com.yyqian.imagine.po.User;
import com.yyqian.imagine.repository.UserRepository;
import com.yyqian.imagine.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import java.util.NoSuchElementException; | package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class SecurityServiceImpl implements SecurityService {
@Autowired
private UserRepository userRepository;
@Override
public String getUsername() {
String username;
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
username = ((UserDetails)principal).getUsername();
} else {
username = principal.toString();
}
return username;
}
@Override | // Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long> {
// Optional<User> findOneByUsername(String username);
// }
//
// Path: src/main/java/com/yyqian/imagine/service/SecurityService.java
// public interface SecurityService {
//
// String getUsername();
//
// String getAuthorities();
//
// User getUser();
//
// boolean isLoggedIn();
//
// }
// Path: src/main/java/com/yyqian/imagine/service/impl/SecurityServiceImpl.java
import com.yyqian.imagine.po.User;
import com.yyqian.imagine.repository.UserRepository;
import com.yyqian.imagine.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import java.util.NoSuchElementException;
package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class SecurityServiceImpl implements SecurityService {
@Autowired
private UserRepository userRepository;
@Override
public String getUsername() {
String username;
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
username = ((UserDetails)principal).getUsername();
} else {
username = principal.toString();
}
return username;
}
@Override | public User getUser() { |
yyqian/imagine | src/main/java/com/yyqian/imagine/controller/VoteController.java | // Path: src/main/java/com/yyqian/imagine/service/VoteService.java
// public interface VoteService {
//
// PostVote createPostVote(PostVote postVote);
//
// CommentVote createCommentVote(CommentVote commentVote);
//
// PostVote upVotePostById(Long id);
//
// PostVote downVotePostById(Long id);
//
// CommentVote upVoteCommentById(Long id);
//
// CommentVote downVoteCommentById(Long id);
//
// boolean isPostVotedByCurrentUser(Post post);
//
// boolean isCommentVotedByCurrentUser(Comment comment);
//
// Collection<Post> getPostsVotedByCurrentUser();
//
// Collection<Comment> getCommentsVotedByCurrentUser();
//
// }
| import com.yyqian.imagine.service.VoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.web.bind.annotation.RequestMethod.POST; | package com.yyqian.imagine.controller;
/**
* Created on 12/16/15.
*
* @author Yinyin Qian
*/
@RestController
public class VoteController {
| // Path: src/main/java/com/yyqian/imagine/service/VoteService.java
// public interface VoteService {
//
// PostVote createPostVote(PostVote postVote);
//
// CommentVote createCommentVote(CommentVote commentVote);
//
// PostVote upVotePostById(Long id);
//
// PostVote downVotePostById(Long id);
//
// CommentVote upVoteCommentById(Long id);
//
// CommentVote downVoteCommentById(Long id);
//
// boolean isPostVotedByCurrentUser(Post post);
//
// boolean isCommentVotedByCurrentUser(Comment comment);
//
// Collection<Post> getPostsVotedByCurrentUser();
//
// Collection<Comment> getCommentsVotedByCurrentUser();
//
// }
// Path: src/main/java/com/yyqian/imagine/controller/VoteController.java
import com.yyqian.imagine.service.VoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
package com.yyqian.imagine.controller;
/**
* Created on 12/16/15.
*
* @author Yinyin Qian
*/
@RestController
public class VoteController {
| private final VoteService voteService; |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/impl/VoteServiceImpl.java | // Path: src/main/java/com/yyqian/imagine/exception/BadRequestException.java
// public class BadRequestException extends RuntimeException {
// public BadRequestException() {
// }
//
// public BadRequestException(String message) {
// super(message);
// }
//
// public BadRequestException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public BadRequestException(Throwable cause) {
// super(cause);
// }
//
// public BadRequestException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/exception/NotFoundException.java
// public class NotFoundException extends RuntimeException {
// public NotFoundException() {
// }
//
// public NotFoundException(String message) {
// super(message);
// }
//
// public NotFoundException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public NotFoundException(Throwable cause) {
// super(cause);
// }
//
// public NotFoundException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/CommentVoteRepository.java
// @Repository
// public interface CommentVoteRepository extends JpaRepository<CommentVote, CommentVotePK> {
// Optional<CommentVote> findOneByUserAndComment(User user, Comment comment);
// Collection<Comment> findCommentsVotedByUser(User user);
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/PostVoteRepository.java
// @Repository
// public interface PostVoteRepository extends JpaRepository<PostVote, PostVotePK> {
// Optional<PostVote> findOneByUserAndPost(User user, Post post);
// Collection<Post> findPostsVotedByUser(User user);
// }
| import com.yyqian.imagine.exception.BadRequestException;
import com.yyqian.imagine.exception.NotFoundException;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.repository.CommentVoteRepository;
import com.yyqian.imagine.repository.PostVoteRepository;
import com.yyqian.imagine.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Collection;
import java.util.NoSuchElementException; | package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class VoteServiceImpl implements VoteService {
@Autowired
private PostService postService;
@Autowired
private CommentService commentService;
@Autowired | // Path: src/main/java/com/yyqian/imagine/exception/BadRequestException.java
// public class BadRequestException extends RuntimeException {
// public BadRequestException() {
// }
//
// public BadRequestException(String message) {
// super(message);
// }
//
// public BadRequestException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public BadRequestException(Throwable cause) {
// super(cause);
// }
//
// public BadRequestException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/exception/NotFoundException.java
// public class NotFoundException extends RuntimeException {
// public NotFoundException() {
// }
//
// public NotFoundException(String message) {
// super(message);
// }
//
// public NotFoundException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public NotFoundException(Throwable cause) {
// super(cause);
// }
//
// public NotFoundException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/CommentVoteRepository.java
// @Repository
// public interface CommentVoteRepository extends JpaRepository<CommentVote, CommentVotePK> {
// Optional<CommentVote> findOneByUserAndComment(User user, Comment comment);
// Collection<Comment> findCommentsVotedByUser(User user);
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/PostVoteRepository.java
// @Repository
// public interface PostVoteRepository extends JpaRepository<PostVote, PostVotePK> {
// Optional<PostVote> findOneByUserAndPost(User user, Post post);
// Collection<Post> findPostsVotedByUser(User user);
// }
// Path: src/main/java/com/yyqian/imagine/service/impl/VoteServiceImpl.java
import com.yyqian.imagine.exception.BadRequestException;
import com.yyqian.imagine.exception.NotFoundException;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.repository.CommentVoteRepository;
import com.yyqian.imagine.repository.PostVoteRepository;
import com.yyqian.imagine.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Collection;
import java.util.NoSuchElementException;
package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class VoteServiceImpl implements VoteService {
@Autowired
private PostService postService;
@Autowired
private CommentService commentService;
@Autowired | private PostVoteRepository postVoteRepository; |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/impl/VoteServiceImpl.java | // Path: src/main/java/com/yyqian/imagine/exception/BadRequestException.java
// public class BadRequestException extends RuntimeException {
// public BadRequestException() {
// }
//
// public BadRequestException(String message) {
// super(message);
// }
//
// public BadRequestException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public BadRequestException(Throwable cause) {
// super(cause);
// }
//
// public BadRequestException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/exception/NotFoundException.java
// public class NotFoundException extends RuntimeException {
// public NotFoundException() {
// }
//
// public NotFoundException(String message) {
// super(message);
// }
//
// public NotFoundException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public NotFoundException(Throwable cause) {
// super(cause);
// }
//
// public NotFoundException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/CommentVoteRepository.java
// @Repository
// public interface CommentVoteRepository extends JpaRepository<CommentVote, CommentVotePK> {
// Optional<CommentVote> findOneByUserAndComment(User user, Comment comment);
// Collection<Comment> findCommentsVotedByUser(User user);
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/PostVoteRepository.java
// @Repository
// public interface PostVoteRepository extends JpaRepository<PostVote, PostVotePK> {
// Optional<PostVote> findOneByUserAndPost(User user, Post post);
// Collection<Post> findPostsVotedByUser(User user);
// }
| import com.yyqian.imagine.exception.BadRequestException;
import com.yyqian.imagine.exception.NotFoundException;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.repository.CommentVoteRepository;
import com.yyqian.imagine.repository.PostVoteRepository;
import com.yyqian.imagine.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Collection;
import java.util.NoSuchElementException; | package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class VoteServiceImpl implements VoteService {
@Autowired
private PostService postService;
@Autowired
private CommentService commentService;
@Autowired
private PostVoteRepository postVoteRepository;
@Autowired | // Path: src/main/java/com/yyqian/imagine/exception/BadRequestException.java
// public class BadRequestException extends RuntimeException {
// public BadRequestException() {
// }
//
// public BadRequestException(String message) {
// super(message);
// }
//
// public BadRequestException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public BadRequestException(Throwable cause) {
// super(cause);
// }
//
// public BadRequestException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/exception/NotFoundException.java
// public class NotFoundException extends RuntimeException {
// public NotFoundException() {
// }
//
// public NotFoundException(String message) {
// super(message);
// }
//
// public NotFoundException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public NotFoundException(Throwable cause) {
// super(cause);
// }
//
// public NotFoundException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/CommentVoteRepository.java
// @Repository
// public interface CommentVoteRepository extends JpaRepository<CommentVote, CommentVotePK> {
// Optional<CommentVote> findOneByUserAndComment(User user, Comment comment);
// Collection<Comment> findCommentsVotedByUser(User user);
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/PostVoteRepository.java
// @Repository
// public interface PostVoteRepository extends JpaRepository<PostVote, PostVotePK> {
// Optional<PostVote> findOneByUserAndPost(User user, Post post);
// Collection<Post> findPostsVotedByUser(User user);
// }
// Path: src/main/java/com/yyqian/imagine/service/impl/VoteServiceImpl.java
import com.yyqian.imagine.exception.BadRequestException;
import com.yyqian.imagine.exception.NotFoundException;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.repository.CommentVoteRepository;
import com.yyqian.imagine.repository.PostVoteRepository;
import com.yyqian.imagine.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Collection;
import java.util.NoSuchElementException;
package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class VoteServiceImpl implements VoteService {
@Autowired
private PostService postService;
@Autowired
private CommentService commentService;
@Autowired
private PostVoteRepository postVoteRepository;
@Autowired | private CommentVoteRepository commentVoteRepository; |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/impl/VoteServiceImpl.java | // Path: src/main/java/com/yyqian/imagine/exception/BadRequestException.java
// public class BadRequestException extends RuntimeException {
// public BadRequestException() {
// }
//
// public BadRequestException(String message) {
// super(message);
// }
//
// public BadRequestException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public BadRequestException(Throwable cause) {
// super(cause);
// }
//
// public BadRequestException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/exception/NotFoundException.java
// public class NotFoundException extends RuntimeException {
// public NotFoundException() {
// }
//
// public NotFoundException(String message) {
// super(message);
// }
//
// public NotFoundException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public NotFoundException(Throwable cause) {
// super(cause);
// }
//
// public NotFoundException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/CommentVoteRepository.java
// @Repository
// public interface CommentVoteRepository extends JpaRepository<CommentVote, CommentVotePK> {
// Optional<CommentVote> findOneByUserAndComment(User user, Comment comment);
// Collection<Comment> findCommentsVotedByUser(User user);
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/PostVoteRepository.java
// @Repository
// public interface PostVoteRepository extends JpaRepository<PostVote, PostVotePK> {
// Optional<PostVote> findOneByUserAndPost(User user, Post post);
// Collection<Post> findPostsVotedByUser(User user);
// }
| import com.yyqian.imagine.exception.BadRequestException;
import com.yyqian.imagine.exception.NotFoundException;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.repository.CommentVoteRepository;
import com.yyqian.imagine.repository.PostVoteRepository;
import com.yyqian.imagine.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Collection;
import java.util.NoSuchElementException; | package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class VoteServiceImpl implements VoteService {
@Autowired
private PostService postService;
@Autowired
private CommentService commentService;
@Autowired
private PostVoteRepository postVoteRepository;
@Autowired
private CommentVoteRepository commentVoteRepository;
@Autowired
private SecurityService securityService;
@Autowired
private UserService userService;
@Transactional
@Override
public PostVote createPostVote(PostVote postVote) {
Post post = postService.getPostById(postVote.getPost().getId()).orElseThrow( | // Path: src/main/java/com/yyqian/imagine/exception/BadRequestException.java
// public class BadRequestException extends RuntimeException {
// public BadRequestException() {
// }
//
// public BadRequestException(String message) {
// super(message);
// }
//
// public BadRequestException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public BadRequestException(Throwable cause) {
// super(cause);
// }
//
// public BadRequestException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/exception/NotFoundException.java
// public class NotFoundException extends RuntimeException {
// public NotFoundException() {
// }
//
// public NotFoundException(String message) {
// super(message);
// }
//
// public NotFoundException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public NotFoundException(Throwable cause) {
// super(cause);
// }
//
// public NotFoundException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/CommentVoteRepository.java
// @Repository
// public interface CommentVoteRepository extends JpaRepository<CommentVote, CommentVotePK> {
// Optional<CommentVote> findOneByUserAndComment(User user, Comment comment);
// Collection<Comment> findCommentsVotedByUser(User user);
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/PostVoteRepository.java
// @Repository
// public interface PostVoteRepository extends JpaRepository<PostVote, PostVotePK> {
// Optional<PostVote> findOneByUserAndPost(User user, Post post);
// Collection<Post> findPostsVotedByUser(User user);
// }
// Path: src/main/java/com/yyqian/imagine/service/impl/VoteServiceImpl.java
import com.yyqian.imagine.exception.BadRequestException;
import com.yyqian.imagine.exception.NotFoundException;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.repository.CommentVoteRepository;
import com.yyqian.imagine.repository.PostVoteRepository;
import com.yyqian.imagine.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Collection;
import java.util.NoSuchElementException;
package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class VoteServiceImpl implements VoteService {
@Autowired
private PostService postService;
@Autowired
private CommentService commentService;
@Autowired
private PostVoteRepository postVoteRepository;
@Autowired
private CommentVoteRepository commentVoteRepository;
@Autowired
private SecurityService securityService;
@Autowired
private UserService userService;
@Transactional
@Override
public PostVote createPostVote(PostVote postVote) {
Post post = postService.getPostById(postVote.getPost().getId()).orElseThrow( | () -> new NotFoundException("Cannot find the post.")); |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/impl/VoteServiceImpl.java | // Path: src/main/java/com/yyqian/imagine/exception/BadRequestException.java
// public class BadRequestException extends RuntimeException {
// public BadRequestException() {
// }
//
// public BadRequestException(String message) {
// super(message);
// }
//
// public BadRequestException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public BadRequestException(Throwable cause) {
// super(cause);
// }
//
// public BadRequestException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/exception/NotFoundException.java
// public class NotFoundException extends RuntimeException {
// public NotFoundException() {
// }
//
// public NotFoundException(String message) {
// super(message);
// }
//
// public NotFoundException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public NotFoundException(Throwable cause) {
// super(cause);
// }
//
// public NotFoundException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/CommentVoteRepository.java
// @Repository
// public interface CommentVoteRepository extends JpaRepository<CommentVote, CommentVotePK> {
// Optional<CommentVote> findOneByUserAndComment(User user, Comment comment);
// Collection<Comment> findCommentsVotedByUser(User user);
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/PostVoteRepository.java
// @Repository
// public interface PostVoteRepository extends JpaRepository<PostVote, PostVotePK> {
// Optional<PostVote> findOneByUserAndPost(User user, Post post);
// Collection<Post> findPostsVotedByUser(User user);
// }
| import com.yyqian.imagine.exception.BadRequestException;
import com.yyqian.imagine.exception.NotFoundException;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.repository.CommentVoteRepository;
import com.yyqian.imagine.repository.PostVoteRepository;
import com.yyqian.imagine.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Collection;
import java.util.NoSuchElementException; | public Collection<Comment> getCommentsVotedByCurrentUser() {
return commentVoteRepository.findCommentsVotedByUser(securityService.getUser());
}
@Override
public PostVote upVotePostById(Long id) {
return votePostById(id, 1);
}
@Override
public PostVote downVotePostById(Long id) {
return votePostById(id, -1);
}
@Override
public CommentVote upVoteCommentById(Long id) {
return voteCommentById(id, 1);
}
@Override
public CommentVote downVoteCommentById(Long id) {
return voteCommentById(id, -1);
}
@Transactional
public PostVote votePostById(Long id, int score) {
Post post = postService.getPostById(id).orElseThrow(
() -> new NoSuchElementException("Cannot find the post."));
User user = securityService.getUser();
if (postVoteRepository.findOneByUserAndPost(user, post).isPresent()) { | // Path: src/main/java/com/yyqian/imagine/exception/BadRequestException.java
// public class BadRequestException extends RuntimeException {
// public BadRequestException() {
// }
//
// public BadRequestException(String message) {
// super(message);
// }
//
// public BadRequestException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public BadRequestException(Throwable cause) {
// super(cause);
// }
//
// public BadRequestException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/exception/NotFoundException.java
// public class NotFoundException extends RuntimeException {
// public NotFoundException() {
// }
//
// public NotFoundException(String message) {
// super(message);
// }
//
// public NotFoundException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public NotFoundException(Throwable cause) {
// super(cause);
// }
//
// public NotFoundException(String message, Throwable cause, boolean enableSuppression,
// boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/CommentVoteRepository.java
// @Repository
// public interface CommentVoteRepository extends JpaRepository<CommentVote, CommentVotePK> {
// Optional<CommentVote> findOneByUserAndComment(User user, Comment comment);
// Collection<Comment> findCommentsVotedByUser(User user);
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/PostVoteRepository.java
// @Repository
// public interface PostVoteRepository extends JpaRepository<PostVote, PostVotePK> {
// Optional<PostVote> findOneByUserAndPost(User user, Post post);
// Collection<Post> findPostsVotedByUser(User user);
// }
// Path: src/main/java/com/yyqian/imagine/service/impl/VoteServiceImpl.java
import com.yyqian.imagine.exception.BadRequestException;
import com.yyqian.imagine.exception.NotFoundException;
import com.yyqian.imagine.po.*;
import com.yyqian.imagine.repository.CommentVoteRepository;
import com.yyqian.imagine.repository.PostVoteRepository;
import com.yyqian.imagine.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Collection;
import java.util.NoSuchElementException;
public Collection<Comment> getCommentsVotedByCurrentUser() {
return commentVoteRepository.findCommentsVotedByUser(securityService.getUser());
}
@Override
public PostVote upVotePostById(Long id) {
return votePostById(id, 1);
}
@Override
public PostVote downVotePostById(Long id) {
return votePostById(id, -1);
}
@Override
public CommentVote upVoteCommentById(Long id) {
return voteCommentById(id, 1);
}
@Override
public CommentVote downVoteCommentById(Long id) {
return voteCommentById(id, -1);
}
@Transactional
public PostVote votePostById(Long id, int score) {
Post post = postService.getPostById(id).orElseThrow(
() -> new NoSuchElementException("Cannot find the post."));
User user = securityService.getUser();
if (postVoteRepository.findOneByUserAndPost(user, post).isPresent()) { | throw new BadRequestException("You already voted."); |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/PostService.java | // Path: src/main/java/com/yyqian/imagine/dto/PostCreateForm.java
// public class PostCreateForm {
//
// @NotEmpty
// private String title = "";
//
// private String url;
//
// private String text;
//
// public PostCreateForm() {
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title.trim();
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url.trim();
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/po/Post.java
// @Entity
// @Table(name = "post")
// public class Post extends BaseUGC {
//
// @Column(name = "title", nullable = false)
// private String title;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "kind", nullable = false)
// private Kind kind;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "category")
// private Category category;
//
// // map to comment, bidirectional
// // @OneToMany tells the persistence provider this is an association and not an attribute.
// @OneToMany(mappedBy = "post", fetch = FetchType.EAGER, orphanRemoval = true, cascade =
// {CascadeType.PERSIST, CascadeType.MERGE})
// @JsonIgnore
// private List<Comment> comments = new ArrayList<Comment>();
//
// @Column(name = "comment_count", nullable = false)
// private int commentCount = 0;
//
// @Column(name = "site")
// private String site;
//
// // The default constructor only exists for the sake of JPA. You won’t use it directly, so it is
// // designated as protected.
// public Post() {
// }
//
// public Post(String title, String content, User user, Kind kind) {
// super(content, user);
// this.title = title;
// this.kind = kind;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public static enum Kind {PLAIN, LINK}
//
// public static enum Category {SHOW, ASK}
//
// public String getTitle() {
// return title;
// }
//
// public Kind getKind() {
// return kind;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public List<Comment> getComments() {
// return comments;
// }
//
// public int getCommentCount() {
// return commentCount;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public void setKind(Kind kind) {
// this.kind = kind;
// }
//
// public void setCategory(Category category) {
// this.category = category;
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// public void increaseCommentCount() {
// commentCount = commentCount + 1;
// }
//
// public void decreaseCommentCount() {
// if (commentCount > 0) {
// commentCount = commentCount - 1;
// }
// }
//
// public String getSite() {
// return site;
// }
//
// public void setSite(String site) {
// this.site = site;
// }
// }
| import com.yyqian.imagine.dto.PostCreateForm;
import com.yyqian.imagine.po.Post;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.Collection;
import java.util.Optional; | package com.yyqian.imagine.service;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
public interface PostService {
Optional<Post> getPostById(long id);
Page<Post> getPostListByPage(Pageable pageable);
Collection<Post> getPostListBySite(String site);
Collection<Post> getPostListByCurrentUser();
Post create(Post post);
| // Path: src/main/java/com/yyqian/imagine/dto/PostCreateForm.java
// public class PostCreateForm {
//
// @NotEmpty
// private String title = "";
//
// private String url;
//
// private String text;
//
// public PostCreateForm() {
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title.trim();
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url.trim();
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/po/Post.java
// @Entity
// @Table(name = "post")
// public class Post extends BaseUGC {
//
// @Column(name = "title", nullable = false)
// private String title;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "kind", nullable = false)
// private Kind kind;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "category")
// private Category category;
//
// // map to comment, bidirectional
// // @OneToMany tells the persistence provider this is an association and not an attribute.
// @OneToMany(mappedBy = "post", fetch = FetchType.EAGER, orphanRemoval = true, cascade =
// {CascadeType.PERSIST, CascadeType.MERGE})
// @JsonIgnore
// private List<Comment> comments = new ArrayList<Comment>();
//
// @Column(name = "comment_count", nullable = false)
// private int commentCount = 0;
//
// @Column(name = "site")
// private String site;
//
// // The default constructor only exists for the sake of JPA. You won’t use it directly, so it is
// // designated as protected.
// public Post() {
// }
//
// public Post(String title, String content, User user, Kind kind) {
// super(content, user);
// this.title = title;
// this.kind = kind;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public static enum Kind {PLAIN, LINK}
//
// public static enum Category {SHOW, ASK}
//
// public String getTitle() {
// return title;
// }
//
// public Kind getKind() {
// return kind;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public List<Comment> getComments() {
// return comments;
// }
//
// public int getCommentCount() {
// return commentCount;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public void setKind(Kind kind) {
// this.kind = kind;
// }
//
// public void setCategory(Category category) {
// this.category = category;
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// public void increaseCommentCount() {
// commentCount = commentCount + 1;
// }
//
// public void decreaseCommentCount() {
// if (commentCount > 0) {
// commentCount = commentCount - 1;
// }
// }
//
// public String getSite() {
// return site;
// }
//
// public void setSite(String site) {
// this.site = site;
// }
// }
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
import com.yyqian.imagine.dto.PostCreateForm;
import com.yyqian.imagine.po.Post;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.Collection;
import java.util.Optional;
package com.yyqian.imagine.service;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
public interface PostService {
Optional<Post> getPostById(long id);
Page<Post> getPostListByPage(Pageable pageable);
Collection<Post> getPostListBySite(String site);
Collection<Post> getPostListByCurrentUser();
Post create(Post post);
| Post create(PostCreateForm form); |
yyqian/imagine | src/main/java/com/yyqian/imagine/dto/validator/UserUpdateFormValidator.java | // Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
| import com.yyqian.imagine.dto.UserUpdateForm;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator; | package com.yyqian.imagine.dto.validator;
/**
* Created by yyqian on 1/8/16.
*/
@Component
public class UserUpdateFormValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) { | // Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
// Path: src/main/java/com/yyqian/imagine/dto/validator/UserUpdateFormValidator.java
import com.yyqian.imagine.dto.UserUpdateForm;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
package com.yyqian.imagine.dto.validator;
/**
* Created by yyqian on 1/8/16.
*/
@Component
public class UserUpdateFormValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) { | return clazz.equals(UserUpdateForm.class); |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/SecurityService.java | // Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
| import com.yyqian.imagine.po.User; | package com.yyqian.imagine.service;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
public interface SecurityService {
String getUsername();
String getAuthorities();
| // Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
// Path: src/main/java/com/yyqian/imagine/service/SecurityService.java
import com.yyqian.imagine.po.User;
package com.yyqian.imagine.service;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
public interface SecurityService {
String getUsername();
String getAuthorities();
| User getUser(); |
yyqian/imagine | src/main/java/com/yyqian/imagine/controller/PageController.java | // Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/PasswordRestForm.java
// public class PasswordRestForm {
//
// @NotEmpty
// @Size(min = 6, max = 20)
// private String password = "";
//
// public PasswordRestForm() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/utility/ControllerUtil.java
// @Component
// public class ControllerUtil {
// @Autowired
// private SecurityService securityService;
//
// public void addLoginInfo(Model model) {
// boolean isLoggedIn = securityService.isLoggedIn();
// model.addAttribute("isLoggedIn", isLoggedIn);
// if (isLoggedIn) {
// model.addAttribute("username", securityService.getUsername());
// }
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
| import com.yyqian.imagine.constant.UriConstant;
import com.yyqian.imagine.dto.PasswordRestForm;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.utility.ControllerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
import static com.yyqian.imagine.constant.UriConstant.*;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST; | package com.yyqian.imagine.controller;
/**
* Created by yyqian on 12/4/15.
* Control all pages
*/
@Controller
public class PageController {
| // Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/PasswordRestForm.java
// public class PasswordRestForm {
//
// @NotEmpty
// @Size(min = 6, max = 20)
// private String password = "";
//
// public PasswordRestForm() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/utility/ControllerUtil.java
// @Component
// public class ControllerUtil {
// @Autowired
// private SecurityService securityService;
//
// public void addLoginInfo(Model model) {
// boolean isLoggedIn = securityService.isLoggedIn();
// model.addAttribute("isLoggedIn", isLoggedIn);
// if (isLoggedIn) {
// model.addAttribute("username", securityService.getUsername());
// }
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
// Path: src/main/java/com/yyqian/imagine/controller/PageController.java
import com.yyqian.imagine.constant.UriConstant;
import com.yyqian.imagine.dto.PasswordRestForm;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.utility.ControllerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
import static com.yyqian.imagine.constant.UriConstant.*;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
package com.yyqian.imagine.controller;
/**
* Created by yyqian on 12/4/15.
* Control all pages
*/
@Controller
public class PageController {
| private final UserService userService; |
yyqian/imagine | src/main/java/com/yyqian/imagine/controller/PageController.java | // Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/PasswordRestForm.java
// public class PasswordRestForm {
//
// @NotEmpty
// @Size(min = 6, max = 20)
// private String password = "";
//
// public PasswordRestForm() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/utility/ControllerUtil.java
// @Component
// public class ControllerUtil {
// @Autowired
// private SecurityService securityService;
//
// public void addLoginInfo(Model model) {
// boolean isLoggedIn = securityService.isLoggedIn();
// model.addAttribute("isLoggedIn", isLoggedIn);
// if (isLoggedIn) {
// model.addAttribute("username", securityService.getUsername());
// }
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
| import com.yyqian.imagine.constant.UriConstant;
import com.yyqian.imagine.dto.PasswordRestForm;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.utility.ControllerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
import static com.yyqian.imagine.constant.UriConstant.*;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST; | package com.yyqian.imagine.controller;
/**
* Created by yyqian on 12/4/15.
* Control all pages
*/
@Controller
public class PageController {
private final UserService userService; | // Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/PasswordRestForm.java
// public class PasswordRestForm {
//
// @NotEmpty
// @Size(min = 6, max = 20)
// private String password = "";
//
// public PasswordRestForm() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/utility/ControllerUtil.java
// @Component
// public class ControllerUtil {
// @Autowired
// private SecurityService securityService;
//
// public void addLoginInfo(Model model) {
// boolean isLoggedIn = securityService.isLoggedIn();
// model.addAttribute("isLoggedIn", isLoggedIn);
// if (isLoggedIn) {
// model.addAttribute("username", securityService.getUsername());
// }
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
// Path: src/main/java/com/yyqian/imagine/controller/PageController.java
import com.yyqian.imagine.constant.UriConstant;
import com.yyqian.imagine.dto.PasswordRestForm;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.utility.ControllerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
import static com.yyqian.imagine.constant.UriConstant.*;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
package com.yyqian.imagine.controller;
/**
* Created by yyqian on 12/4/15.
* Control all pages
*/
@Controller
public class PageController {
private final UserService userService; | private final ControllerUtil controllerUtil; |
yyqian/imagine | src/main/java/com/yyqian/imagine/controller/PageController.java | // Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/PasswordRestForm.java
// public class PasswordRestForm {
//
// @NotEmpty
// @Size(min = 6, max = 20)
// private String password = "";
//
// public PasswordRestForm() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/utility/ControllerUtil.java
// @Component
// public class ControllerUtil {
// @Autowired
// private SecurityService securityService;
//
// public void addLoginInfo(Model model) {
// boolean isLoggedIn = securityService.isLoggedIn();
// model.addAttribute("isLoggedIn", isLoggedIn);
// if (isLoggedIn) {
// model.addAttribute("username", securityService.getUsername());
// }
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
| import com.yyqian.imagine.constant.UriConstant;
import com.yyqian.imagine.dto.PasswordRestForm;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.utility.ControllerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
import static com.yyqian.imagine.constant.UriConstant.*;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST; | package com.yyqian.imagine.controller;
/**
* Created by yyqian on 12/4/15.
* Control all pages
*/
@Controller
public class PageController {
private final UserService userService;
private final ControllerUtil controllerUtil;
@Autowired
public PageController(UserService userService, ControllerUtil controllerUtil) {
this.userService = userService;
this.controllerUtil = controllerUtil;
}
@RequestMapping(value = "/", method = GET)
public String index() { | // Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/PasswordRestForm.java
// public class PasswordRestForm {
//
// @NotEmpty
// @Size(min = 6, max = 20)
// private String password = "";
//
// public PasswordRestForm() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/utility/ControllerUtil.java
// @Component
// public class ControllerUtil {
// @Autowired
// private SecurityService securityService;
//
// public void addLoginInfo(Model model) {
// boolean isLoggedIn = securityService.isLoggedIn();
// model.addAttribute("isLoggedIn", isLoggedIn);
// if (isLoggedIn) {
// model.addAttribute("username", securityService.getUsername());
// }
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
// Path: src/main/java/com/yyqian/imagine/controller/PageController.java
import com.yyqian.imagine.constant.UriConstant;
import com.yyqian.imagine.dto.PasswordRestForm;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.utility.ControllerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
import static com.yyqian.imagine.constant.UriConstant.*;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
package com.yyqian.imagine.controller;
/**
* Created by yyqian on 12/4/15.
* Control all pages
*/
@Controller
public class PageController {
private final UserService userService;
private final ControllerUtil controllerUtil;
@Autowired
public PageController(UserService userService, ControllerUtil controllerUtil) {
this.userService = userService;
this.controllerUtil = controllerUtil;
}
@RequestMapping(value = "/", method = GET)
public String index() { | return "redirect:" + UriConstant.POST; |
yyqian/imagine | src/main/java/com/yyqian/imagine/controller/PageController.java | // Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/PasswordRestForm.java
// public class PasswordRestForm {
//
// @NotEmpty
// @Size(min = 6, max = 20)
// private String password = "";
//
// public PasswordRestForm() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/utility/ControllerUtil.java
// @Component
// public class ControllerUtil {
// @Autowired
// private SecurityService securityService;
//
// public void addLoginInfo(Model model) {
// boolean isLoggedIn = securityService.isLoggedIn();
// model.addAttribute("isLoggedIn", isLoggedIn);
// if (isLoggedIn) {
// model.addAttribute("username", securityService.getUsername());
// }
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
| import com.yyqian.imagine.constant.UriConstant;
import com.yyqian.imagine.dto.PasswordRestForm;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.utility.ControllerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
import static com.yyqian.imagine.constant.UriConstant.*;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST; | if (error != null) {
model.addAttribute("error", error);
}
return "login";
}
@RequestMapping(value = FORGOT, method = GET)
public String forgot() {
return "forgot";
}
@RequestMapping(value = RESETPW, method = GET)
public String resetSelfPassword(Model model) {
controllerUtil.addLoginInfo(model);
return "resetpw";
}
@RequestMapping(value = RESETPW + "/{token}", method = GET)
public String resetpw(@PathVariable("token") String token) {
userService.authUserByToken(token);
return "resetpw";
}
@RequestMapping(value = FORGOT, method = POST)
public String forgotHandler(@RequestParam(value = "username") String username) {
userService.sendRestPasswordEmail(username);
return "password-reset-sent";
}
@RequestMapping(value = RESETPW, method = POST) | // Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/PasswordRestForm.java
// public class PasswordRestForm {
//
// @NotEmpty
// @Size(min = 6, max = 20)
// private String password = "";
//
// public PasswordRestForm() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
// public interface UserService {
//
// Optional<User> getUserById(long id);
//
// Optional<User> getUserByUsername(String username);
//
// Collection<User> getAllUsers();
//
// User create(UserCreateForm form);
//
// int increasePointByUserId(Long id);
//
// User update(UserUpdateForm form);
//
// User resetPassword(PasswordRestForm form);
//
// void sendRestPasswordEmail(String username);
//
// void authUserByToken(String token);
//
// }
//
// Path: src/main/java/com/yyqian/imagine/utility/ControllerUtil.java
// @Component
// public class ControllerUtil {
// @Autowired
// private SecurityService securityService;
//
// public void addLoginInfo(Model model) {
// boolean isLoggedIn = securityService.isLoggedIn();
// model.addAttribute("isLoggedIn", isLoggedIn);
// if (isLoggedIn) {
// model.addAttribute("username", securityService.getUsername());
// }
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/constant/UriConstant.java
// public final class UriConstant {
//
// private UriConstant() {
// }
//
// public static final String ABOUT = "/about";
// public static final String LOGIN = "/login";
// public static final String LOGIN_ERROR = LOGIN + "?error";
// public static final String LOGOUT = "/logout";
// public static final String FORGOT = "/forgot";
// public static final String RESETPW = "/resetpw";
//
// public static final String POST = "/post";
// public static final String POST_EDITOR = POST + "/new/editor";
// public static final String COMMENT = "/comment";
// public static final String USER = "/user";
// public static final String USER_SELF = USER + "/self";
// }
// Path: src/main/java/com/yyqian/imagine/controller/PageController.java
import com.yyqian.imagine.constant.UriConstant;
import com.yyqian.imagine.dto.PasswordRestForm;
import com.yyqian.imagine.service.UserService;
import com.yyqian.imagine.utility.ControllerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
import static com.yyqian.imagine.constant.UriConstant.*;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
if (error != null) {
model.addAttribute("error", error);
}
return "login";
}
@RequestMapping(value = FORGOT, method = GET)
public String forgot() {
return "forgot";
}
@RequestMapping(value = RESETPW, method = GET)
public String resetSelfPassword(Model model) {
controllerUtil.addLoginInfo(model);
return "resetpw";
}
@RequestMapping(value = RESETPW + "/{token}", method = GET)
public String resetpw(@PathVariable("token") String token) {
userService.authUserByToken(token);
return "resetpw";
}
@RequestMapping(value = FORGOT, method = POST)
public String forgotHandler(@RequestParam(value = "username") String username) {
userService.sendRestPasswordEmail(username);
return "password-reset-sent";
}
@RequestMapping(value = RESETPW, method = POST) | public String resetpwHandler(@Valid PasswordRestForm form) { |
yyqian/imagine | src/main/java/com/yyqian/imagine/dto/validator/CommentCreateFormValidator.java | // Path: src/main/java/com/yyqian/imagine/dto/CommentCreateForm.java
// public class CommentCreateForm {
//
// @NotNull
// private Long postId;
//
// @NotEmpty
// private String content = "";
//
// private Long parentId;
//
// public CommentCreateForm() {
// }
//
// public Long getPostId() {
// return postId;
// }
//
// public void setPostId(Long postId) {
// this.postId = postId;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content.trim();
// }
//
// public Long getParentId() {
// return parentId;
// }
//
// public void setParentId(Long parentId) {
// this.parentId = parentId;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
| import com.yyqian.imagine.dto.CommentCreateForm;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator; | package com.yyqian.imagine.dto.validator;
/**
* Created on 1/8/16.
*
* @author Yinyin Qian
*/
@Component
public class CommentCreateFormValidator implements Validator {
@Autowired | // Path: src/main/java/com/yyqian/imagine/dto/CommentCreateForm.java
// public class CommentCreateForm {
//
// @NotNull
// private Long postId;
//
// @NotEmpty
// private String content = "";
//
// private Long parentId;
//
// public CommentCreateForm() {
// }
//
// public Long getPostId() {
// return postId;
// }
//
// public void setPostId(Long postId) {
// this.postId = postId;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content.trim();
// }
//
// public Long getParentId() {
// return parentId;
// }
//
// public void setParentId(Long parentId) {
// this.parentId = parentId;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
// Path: src/main/java/com/yyqian/imagine/dto/validator/CommentCreateFormValidator.java
import com.yyqian.imagine.dto.CommentCreateForm;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
package com.yyqian.imagine.dto.validator;
/**
* Created on 1/8/16.
*
* @author Yinyin Qian
*/
@Component
public class CommentCreateFormValidator implements Validator {
@Autowired | private PostService postService; |
yyqian/imagine | src/main/java/com/yyqian/imagine/dto/validator/CommentCreateFormValidator.java | // Path: src/main/java/com/yyqian/imagine/dto/CommentCreateForm.java
// public class CommentCreateForm {
//
// @NotNull
// private Long postId;
//
// @NotEmpty
// private String content = "";
//
// private Long parentId;
//
// public CommentCreateForm() {
// }
//
// public Long getPostId() {
// return postId;
// }
//
// public void setPostId(Long postId) {
// this.postId = postId;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content.trim();
// }
//
// public Long getParentId() {
// return parentId;
// }
//
// public void setParentId(Long parentId) {
// this.parentId = parentId;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
| import com.yyqian.imagine.dto.CommentCreateForm;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator; | package com.yyqian.imagine.dto.validator;
/**
* Created on 1/8/16.
*
* @author Yinyin Qian
*/
@Component
public class CommentCreateFormValidator implements Validator {
@Autowired
private PostService postService;
@Autowired | // Path: src/main/java/com/yyqian/imagine/dto/CommentCreateForm.java
// public class CommentCreateForm {
//
// @NotNull
// private Long postId;
//
// @NotEmpty
// private String content = "";
//
// private Long parentId;
//
// public CommentCreateForm() {
// }
//
// public Long getPostId() {
// return postId;
// }
//
// public void setPostId(Long postId) {
// this.postId = postId;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content.trim();
// }
//
// public Long getParentId() {
// return parentId;
// }
//
// public void setParentId(Long parentId) {
// this.parentId = parentId;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
// Path: src/main/java/com/yyqian/imagine/dto/validator/CommentCreateFormValidator.java
import com.yyqian.imagine.dto.CommentCreateForm;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
package com.yyqian.imagine.dto.validator;
/**
* Created on 1/8/16.
*
* @author Yinyin Qian
*/
@Component
public class CommentCreateFormValidator implements Validator {
@Autowired
private PostService postService;
@Autowired | private CommentService commentService; |
yyqian/imagine | src/main/java/com/yyqian/imagine/dto/validator/CommentCreateFormValidator.java | // Path: src/main/java/com/yyqian/imagine/dto/CommentCreateForm.java
// public class CommentCreateForm {
//
// @NotNull
// private Long postId;
//
// @NotEmpty
// private String content = "";
//
// private Long parentId;
//
// public CommentCreateForm() {
// }
//
// public Long getPostId() {
// return postId;
// }
//
// public void setPostId(Long postId) {
// this.postId = postId;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content.trim();
// }
//
// public Long getParentId() {
// return parentId;
// }
//
// public void setParentId(Long parentId) {
// this.parentId = parentId;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
| import com.yyqian.imagine.dto.CommentCreateForm;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator; | package com.yyqian.imagine.dto.validator;
/**
* Created on 1/8/16.
*
* @author Yinyin Qian
*/
@Component
public class CommentCreateFormValidator implements Validator {
@Autowired
private PostService postService;
@Autowired
private CommentService commentService;
@Override
public boolean supports(Class<?> clazz) { | // Path: src/main/java/com/yyqian/imagine/dto/CommentCreateForm.java
// public class CommentCreateForm {
//
// @NotNull
// private Long postId;
//
// @NotEmpty
// private String content = "";
//
// private Long parentId;
//
// public CommentCreateForm() {
// }
//
// public Long getPostId() {
// return postId;
// }
//
// public void setPostId(Long postId) {
// this.postId = postId;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content.trim();
// }
//
// public Long getParentId() {
// return parentId;
// }
//
// public void setParentId(Long parentId) {
// this.parentId = parentId;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/CommentService.java
// public interface CommentService {
//
// Comment create(Comment comment);
//
// Comment create(CommentCreateForm form);
//
// Comment update(Comment comment);
//
// Optional<Comment> getCommentById(long id);
//
// Collection<Comment> getCommentTreeByPost(Post post);
//
// Page<Comment> getCommentListByPage(Pageable pageable);
//
// Collection<Comment> getCommentListByCurrentUser();
//
// }
//
// Path: src/main/java/com/yyqian/imagine/service/PostService.java
// public interface PostService {
// Optional<Post> getPostById(long id);
//
// Page<Post> getPostListByPage(Pageable pageable);
//
// Collection<Post> getPostListBySite(String site);
//
// Collection<Post> getPostListByCurrentUser();
//
// Post create(Post post);
//
// Post create(PostCreateForm form);
//
// Post update(Post post);
//
// }
// Path: src/main/java/com/yyqian/imagine/dto/validator/CommentCreateFormValidator.java
import com.yyqian.imagine.dto.CommentCreateForm;
import com.yyqian.imagine.service.CommentService;
import com.yyqian.imagine.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
package com.yyqian.imagine.dto.validator;
/**
* Created on 1/8/16.
*
* @author Yinyin Qian
*/
@Component
public class CommentCreateFormValidator implements Validator {
@Autowired
private PostService postService;
@Autowired
private CommentService commentService;
@Override
public boolean supports(Class<?> clazz) { | return clazz.equals(CommentCreateForm.class); |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/UserService.java | // Path: src/main/java/com/yyqian/imagine/dto/PasswordRestForm.java
// public class PasswordRestForm {
//
// @NotEmpty
// @Size(min = 6, max = 20)
// private String password = "";
//
// public PasswordRestForm() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
| import com.yyqian.imagine.dto.PasswordRestForm;
import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.User;
import java.util.Collection;
import java.util.Optional; | package com.yyqian.imagine.service;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
public interface UserService {
Optional<User> getUserById(long id);
Optional<User> getUserByUsername(String username);
Collection<User> getAllUsers();
| // Path: src/main/java/com/yyqian/imagine/dto/PasswordRestForm.java
// public class PasswordRestForm {
//
// @NotEmpty
// @Size(min = 6, max = 20)
// private String password = "";
//
// public PasswordRestForm() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
import com.yyqian.imagine.dto.PasswordRestForm;
import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.User;
import java.util.Collection;
import java.util.Optional;
package com.yyqian.imagine.service;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
public interface UserService {
Optional<User> getUserById(long id);
Optional<User> getUserByUsername(String username);
Collection<User> getAllUsers();
| User create(UserCreateForm form); |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/UserService.java | // Path: src/main/java/com/yyqian/imagine/dto/PasswordRestForm.java
// public class PasswordRestForm {
//
// @NotEmpty
// @Size(min = 6, max = 20)
// private String password = "";
//
// public PasswordRestForm() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
| import com.yyqian.imagine.dto.PasswordRestForm;
import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.User;
import java.util.Collection;
import java.util.Optional; | package com.yyqian.imagine.service;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
public interface UserService {
Optional<User> getUserById(long id);
Optional<User> getUserByUsername(String username);
Collection<User> getAllUsers();
User create(UserCreateForm form);
int increasePointByUserId(Long id);
| // Path: src/main/java/com/yyqian/imagine/dto/PasswordRestForm.java
// public class PasswordRestForm {
//
// @NotEmpty
// @Size(min = 6, max = 20)
// private String password = "";
//
// public PasswordRestForm() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
import com.yyqian.imagine.dto.PasswordRestForm;
import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.User;
import java.util.Collection;
import java.util.Optional;
package com.yyqian.imagine.service;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
public interface UserService {
Optional<User> getUserById(long id);
Optional<User> getUserByUsername(String username);
Collection<User> getAllUsers();
User create(UserCreateForm form);
int increasePointByUserId(Long id);
| User update(UserUpdateForm form); |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/UserService.java | // Path: src/main/java/com/yyqian/imagine/dto/PasswordRestForm.java
// public class PasswordRestForm {
//
// @NotEmpty
// @Size(min = 6, max = 20)
// private String password = "";
//
// public PasswordRestForm() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
| import com.yyqian.imagine.dto.PasswordRestForm;
import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.User;
import java.util.Collection;
import java.util.Optional; | package com.yyqian.imagine.service;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
public interface UserService {
Optional<User> getUserById(long id);
Optional<User> getUserByUsername(String username);
Collection<User> getAllUsers();
User create(UserCreateForm form);
int increasePointByUserId(Long id);
User update(UserUpdateForm form);
| // Path: src/main/java/com/yyqian/imagine/dto/PasswordRestForm.java
// public class PasswordRestForm {
//
// @NotEmpty
// @Size(min = 6, max = 20)
// private String password = "";
//
// public PasswordRestForm() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserCreateForm.java
// public class UserCreateForm {
//
// @NotEmpty
// private String username = "";
//
// @NotEmpty
// private String password = "";
//
// @NotEmpty
// private String passwordRepeated = "";
//
// public UserCreateForm() {
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username.trim();
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password.trim();
// }
//
// public String getPasswordRepeated() {
// return passwordRepeated;
// }
//
// public void setPasswordRepeated(String passwordRepeated) {
// this.passwordRepeated = passwordRepeated.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/dto/UserUpdateForm.java
// public class UserUpdateForm {
//
// private String email = "";
//
// private String about = "";
//
// public UserUpdateForm() {
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email.trim();
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about.trim();
// }
//
// }
//
// Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
// Path: src/main/java/com/yyqian/imagine/service/UserService.java
import com.yyqian.imagine.dto.PasswordRestForm;
import com.yyqian.imagine.dto.UserCreateForm;
import com.yyqian.imagine.dto.UserUpdateForm;
import com.yyqian.imagine.po.User;
import java.util.Collection;
import java.util.Optional;
package com.yyqian.imagine.service;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
public interface UserService {
Optional<User> getUserById(long id);
Optional<User> getUserByUsername(String username);
Collection<User> getAllUsers();
User create(UserCreateForm form);
int increasePointByUserId(Long id);
User update(UserUpdateForm form);
| User resetPassword(PasswordRestForm form); |
yyqian/imagine | src/main/java/com/yyqian/imagine/utility/ControllerUtil.java | // Path: src/main/java/com/yyqian/imagine/service/SecurityService.java
// public interface SecurityService {
//
// String getUsername();
//
// String getAuthorities();
//
// User getUser();
//
// boolean isLoggedIn();
//
// }
| import com.yyqian.imagine.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model; | package com.yyqian.imagine.utility;
/**
* Created on 10/10/2016.
*
* @author Yinyin Qian
*/
@Component
public class ControllerUtil {
@Autowired | // Path: src/main/java/com/yyqian/imagine/service/SecurityService.java
// public interface SecurityService {
//
// String getUsername();
//
// String getAuthorities();
//
// User getUser();
//
// boolean isLoggedIn();
//
// }
// Path: src/main/java/com/yyqian/imagine/utility/ControllerUtil.java
import com.yyqian.imagine.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
package com.yyqian.imagine.utility;
/**
* Created on 10/10/2016.
*
* @author Yinyin Qian
*/
@Component
public class ControllerUtil {
@Autowired | private SecurityService securityService; |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/impl/UserDetailsServiceImpl.java | // Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long> {
// Optional<User> findOneByUsername(String username);
// }
//
// Path: src/main/java/com/yyqian/imagine/vo/CurrentUser.java
// public class CurrentUser extends org.springframework.security.core.userdetails.User {
//
// private User user;
//
// public CurrentUser(User user) {
// super(user.getUsername(), user.getPasswordHash(),
// AuthorityUtils.createAuthorityList(user.getRole().toString()));
// this.user = user;
// }
//
// public User getUser() {
// return user;
// }
//
// public Long getId() {
// return user.getId();
// }
//
// public User.Role getRole() {
// return user.getRole();
// }
// }
| import com.yyqian.imagine.po.User;
import com.yyqian.imagine.repository.UserRepository;
import com.yyqian.imagine.vo.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service; | package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
| // Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long> {
// Optional<User> findOneByUsername(String username);
// }
//
// Path: src/main/java/com/yyqian/imagine/vo/CurrentUser.java
// public class CurrentUser extends org.springframework.security.core.userdetails.User {
//
// private User user;
//
// public CurrentUser(User user) {
// super(user.getUsername(), user.getPasswordHash(),
// AuthorityUtils.createAuthorityList(user.getRole().toString()));
// this.user = user;
// }
//
// public User getUser() {
// return user;
// }
//
// public Long getId() {
// return user.getId();
// }
//
// public User.Role getRole() {
// return user.getRole();
// }
// }
// Path: src/main/java/com/yyqian/imagine/service/impl/UserDetailsServiceImpl.java
import com.yyqian.imagine.po.User;
import com.yyqian.imagine.repository.UserRepository;
import com.yyqian.imagine.vo.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
| private final UserRepository userRepository; |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/impl/UserDetailsServiceImpl.java | // Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long> {
// Optional<User> findOneByUsername(String username);
// }
//
// Path: src/main/java/com/yyqian/imagine/vo/CurrentUser.java
// public class CurrentUser extends org.springframework.security.core.userdetails.User {
//
// private User user;
//
// public CurrentUser(User user) {
// super(user.getUsername(), user.getPasswordHash(),
// AuthorityUtils.createAuthorityList(user.getRole().toString()));
// this.user = user;
// }
//
// public User getUser() {
// return user;
// }
//
// public Long getId() {
// return user.getId();
// }
//
// public User.Role getRole() {
// return user.getRole();
// }
// }
| import com.yyqian.imagine.po.User;
import com.yyqian.imagine.repository.UserRepository;
import com.yyqian.imagine.vo.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service; | package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepository;
@Autowired
public UserDetailsServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override | // Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long> {
// Optional<User> findOneByUsername(String username);
// }
//
// Path: src/main/java/com/yyqian/imagine/vo/CurrentUser.java
// public class CurrentUser extends org.springframework.security.core.userdetails.User {
//
// private User user;
//
// public CurrentUser(User user) {
// super(user.getUsername(), user.getPasswordHash(),
// AuthorityUtils.createAuthorityList(user.getRole().toString()));
// this.user = user;
// }
//
// public User getUser() {
// return user;
// }
//
// public Long getId() {
// return user.getId();
// }
//
// public User.Role getRole() {
// return user.getRole();
// }
// }
// Path: src/main/java/com/yyqian/imagine/service/impl/UserDetailsServiceImpl.java
import com.yyqian.imagine.po.User;
import com.yyqian.imagine.repository.UserRepository;
import com.yyqian.imagine.vo.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepository;
@Autowired
public UserDetailsServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override | public CurrentUser loadUserByUsername(String username) throws UsernameNotFoundException { |
yyqian/imagine | src/main/java/com/yyqian/imagine/service/impl/UserDetailsServiceImpl.java | // Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long> {
// Optional<User> findOneByUsername(String username);
// }
//
// Path: src/main/java/com/yyqian/imagine/vo/CurrentUser.java
// public class CurrentUser extends org.springframework.security.core.userdetails.User {
//
// private User user;
//
// public CurrentUser(User user) {
// super(user.getUsername(), user.getPasswordHash(),
// AuthorityUtils.createAuthorityList(user.getRole().toString()));
// this.user = user;
// }
//
// public User getUser() {
// return user;
// }
//
// public Long getId() {
// return user.getId();
// }
//
// public User.Role getRole() {
// return user.getRole();
// }
// }
| import com.yyqian.imagine.po.User;
import com.yyqian.imagine.repository.UserRepository;
import com.yyqian.imagine.vo.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service; | package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepository;
@Autowired
public UserDetailsServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public CurrentUser loadUserByUsername(String username) throws UsernameNotFoundException { | // Path: src/main/java/com/yyqian/imagine/po/User.java
// @Entity
// @Table(name = "user")
// public class User extends Base {
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password_hash", nullable = false)
// private String passwordHash;
//
// @Column(name = "email", unique = true)
// private String email;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role = Role.USER;
//
// @Lob
// @Column(name = "about")
// private String about;
//
// @Column(name = "point", nullable = false)
// private Integer point = 0;
//
// public enum Role {
// USER, ADMIN
// }
//
// public User() {
// }
//
// public User(String username, String passwordHash) {
// this.username = username;
// this.passwordHash = passwordHash;
// }
//
// @Override
// public String toString() {
// return id.toString();
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public Role getRole() {
// return role;
// }
//
// public String getPasswordHash() {
// return passwordHash;
// }
//
// public void setPasswordHash(String passwordHash) {
// this.passwordHash = passwordHash;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAbout() {
// return about;
// }
//
// public void setAbout(String about) {
// this.about = about;
// }
//
// public Integer getPoint() {
// return point;
// }
//
// public void setPoint(Integer point) {
// this.point = point;
// }
// }
//
// Path: src/main/java/com/yyqian/imagine/repository/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long> {
// Optional<User> findOneByUsername(String username);
// }
//
// Path: src/main/java/com/yyqian/imagine/vo/CurrentUser.java
// public class CurrentUser extends org.springframework.security.core.userdetails.User {
//
// private User user;
//
// public CurrentUser(User user) {
// super(user.getUsername(), user.getPasswordHash(),
// AuthorityUtils.createAuthorityList(user.getRole().toString()));
// this.user = user;
// }
//
// public User getUser() {
// return user;
// }
//
// public Long getId() {
// return user.getId();
// }
//
// public User.Role getRole() {
// return user.getRole();
// }
// }
// Path: src/main/java/com/yyqian/imagine/service/impl/UserDetailsServiceImpl.java
import com.yyqian.imagine.po.User;
import com.yyqian.imagine.repository.UserRepository;
import com.yyqian.imagine.vo.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
package com.yyqian.imagine.service.impl;
/**
* Created on 12/15/15.
*
* @author Yinyin Qian
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepository;
@Autowired
public UserDetailsServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public CurrentUser loadUserByUsername(String username) throws UsernameNotFoundException { | User user = userRepository.findOneByUsername(username).orElseThrow( |
lvanyal/directly | app/src/prod/java/com/iph/directly/domain/rest/ToiletApi.java | // Path: app/src/prod/java/com/iph/directly/domain/apimodel/CityToiletsResponse.java
// public class CityToiletsResponse {
//
// public static final CityToiletsResponse EMPTY = new CityToiletsResponse();
//
// private boolean success;
//
// private Result result;
//
// private class Result {
// List<InnerResult> results;
// }
//
// private class InnerResult {
// private List<Resources> resources;
// }
//
// private class Resources {
// String format;
// String url;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public String getResourceUrl() {
// return result.results.get(0).resources.get(0).url;
// }
//
// public String getResourceFormat() {
// return result.results.get(0).resources.get(0).format;
// }
// }
| import com.iph.directly.domain.apimodel.CityToiletsResponse;
import okhttp3.ResponseBody;
import retrofit2.Response;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.Url;
import rx.Observable; | package com.iph.directly.domain.rest;
/**
* Created by vanya on 10/15/2016.
*/
public interface ToiletApi {
@GET("api/action/package_search") | // Path: app/src/prod/java/com/iph/directly/domain/apimodel/CityToiletsResponse.java
// public class CityToiletsResponse {
//
// public static final CityToiletsResponse EMPTY = new CityToiletsResponse();
//
// private boolean success;
//
// private Result result;
//
// private class Result {
// List<InnerResult> results;
// }
//
// private class InnerResult {
// private List<Resources> resources;
// }
//
// private class Resources {
// String format;
// String url;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public String getResourceUrl() {
// return result.results.get(0).resources.get(0).url;
// }
//
// public String getResourceFormat() {
// return result.results.get(0).resources.get(0).format;
// }
// }
// Path: app/src/prod/java/com/iph/directly/domain/rest/ToiletApi.java
import com.iph.directly.domain.apimodel.CityToiletsResponse;
import okhttp3.ResponseBody;
import retrofit2.Response;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.Url;
import rx.Observable;
package com.iph.directly.domain.rest;
/**
* Created by vanya on 10/15/2016.
*/
public interface ToiletApi {
@GET("api/action/package_search") | Observable<CityToiletsResponse> toiletList(@Query("q") String city); |
lvanyal/directly | app/src/main/java/com/iph/directly/presenter/LoadingPresenter.java | // Path: app/src/main/java/com/iph/directly/domain/LocationRepository.java
// public interface LocationRepository {
// Observable<Location> getCurrentLocation();
//
// Observable<Location> getLocationFromLatLng(double latitude, double longitude);
//
// Observable<Toilet> initPlaceId(Location currentLocation, Toilet toilet);
// Observable<String> getCurrentLocationText();
//
// class LocationNotEnabledException extends RuntimeException {
// private Status status;
//
// public LocationNotEnabledException(Status status) {
// this.status = status;
// }
//
// public Status getStatus() {
// return status;
// }
// }
// }
//
// Path: app/src/main/java/com/iph/directly/domain/model/Location.java
// public class Location implements Parcelable{
// private LatLng latLng;
//
// private String city;
// private String country;
// private String street;
// private String buildingNumber;
//
// public Location(double latitude, double longitude, String city, String country) {
// this.latLng = new LatLng(latitude, longitude);
// this.city = city;
// this.country = country;
// }
//
// public Location(double latitude, double longitude, String city, String country, String street, String buildingNumber) {
// this.latLng = new LatLng(latitude, longitude);
// this.city = city;
// this.country = country;
// this.street = street;
// this.buildingNumber = buildingNumber;
// }
//
// protected Location(Parcel in) {
// latLng = in.readParcelable(LatLng.class.getClassLoader());
// city = in.readString();
// country = in.readString();
// this.street = in.readString();
// this.buildingNumber = in.readString();
// }
//
// public static final Creator<Location> CREATOR = new Creator<Location>() {
// @Override
// public Location createFromParcel(Parcel in) {
// return new Location(in);
// }
//
// @Override
// public Location[] newArray(int size) {
// return new Location[size];
// }
// };
//
// public LatLng getLatLng() {
// return latLng;
// }
//
// public void setLatLng(LatLng latLng) {
// this.latLng = latLng;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeParcelable(latLng, flags);
// dest.writeString(city);
// dest.writeString(country);
// dest.writeString(street);
// dest.writeString(buildingNumber);
// }
//
// public String getCountry() {
// return country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getStreet() {
// return street;
// }
//
// public String getBuildingNumber() {
// return buildingNumber;
// }
// }
//
// Path: app/src/main/java/com/iph/directly/view/LoadingView.java
// public interface LoadingView {
// void showProgress();
//
// void navigateToToilets(Location location);
//
// void showRequestLocationPermission();
// }
| import com.iph.directly.domain.LocationRepository;
import com.iph.directly.domain.model.Location;
import com.iph.directly.view.LoadingView;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import timber.log.Timber; | package com.iph.directly.presenter;
/**
* Created by vanya on 10/8/2016.
*/
public class LoadingPresenter {
private LoadingView loadingView;
| // Path: app/src/main/java/com/iph/directly/domain/LocationRepository.java
// public interface LocationRepository {
// Observable<Location> getCurrentLocation();
//
// Observable<Location> getLocationFromLatLng(double latitude, double longitude);
//
// Observable<Toilet> initPlaceId(Location currentLocation, Toilet toilet);
// Observable<String> getCurrentLocationText();
//
// class LocationNotEnabledException extends RuntimeException {
// private Status status;
//
// public LocationNotEnabledException(Status status) {
// this.status = status;
// }
//
// public Status getStatus() {
// return status;
// }
// }
// }
//
// Path: app/src/main/java/com/iph/directly/domain/model/Location.java
// public class Location implements Parcelable{
// private LatLng latLng;
//
// private String city;
// private String country;
// private String street;
// private String buildingNumber;
//
// public Location(double latitude, double longitude, String city, String country) {
// this.latLng = new LatLng(latitude, longitude);
// this.city = city;
// this.country = country;
// }
//
// public Location(double latitude, double longitude, String city, String country, String street, String buildingNumber) {
// this.latLng = new LatLng(latitude, longitude);
// this.city = city;
// this.country = country;
// this.street = street;
// this.buildingNumber = buildingNumber;
// }
//
// protected Location(Parcel in) {
// latLng = in.readParcelable(LatLng.class.getClassLoader());
// city = in.readString();
// country = in.readString();
// this.street = in.readString();
// this.buildingNumber = in.readString();
// }
//
// public static final Creator<Location> CREATOR = new Creator<Location>() {
// @Override
// public Location createFromParcel(Parcel in) {
// return new Location(in);
// }
//
// @Override
// public Location[] newArray(int size) {
// return new Location[size];
// }
// };
//
// public LatLng getLatLng() {
// return latLng;
// }
//
// public void setLatLng(LatLng latLng) {
// this.latLng = latLng;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeParcelable(latLng, flags);
// dest.writeString(city);
// dest.writeString(country);
// dest.writeString(street);
// dest.writeString(buildingNumber);
// }
//
// public String getCountry() {
// return country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getStreet() {
// return street;
// }
//
// public String getBuildingNumber() {
// return buildingNumber;
// }
// }
//
// Path: app/src/main/java/com/iph/directly/view/LoadingView.java
// public interface LoadingView {
// void showProgress();
//
// void navigateToToilets(Location location);
//
// void showRequestLocationPermission();
// }
// Path: app/src/main/java/com/iph/directly/presenter/LoadingPresenter.java
import com.iph.directly.domain.LocationRepository;
import com.iph.directly.domain.model.Location;
import com.iph.directly.view.LoadingView;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import timber.log.Timber;
package com.iph.directly.presenter;
/**
* Created by vanya on 10/8/2016.
*/
public class LoadingPresenter {
private LoadingView loadingView;
| private LocationRepository locationRepository; |
lvanyal/directly | app/src/prod/java/com/iph/directly/domain/rest/DirectionApi.java | // Path: app/src/prod/java/com/iph/directly/domain/apimodel/RouteResponse.java
// public class RouteResponse {
//
// private List<Route> routes;
//
// public int getDistance() {
// return this.routes.get(0).legs.get(0).distance.value;
// }
//
// public int getDuration() {
// return this.routes.get(0).legs.get(0).duration.value;
// }
//
// public String getPoints() {
// return this.routes.get(0).overview_polyline.points;
// }
//
// public boolean hasPoints() {
// return !routes.isEmpty();
// }
//
// private class Route {
// private OverviewPolyline overview_polyline;
// private List<Leg> legs;
// }
//
// private class OverviewPolyline {
// String points;
// }
//
// private class Leg {
// private Distance distance;
// private Duration duration;
// }
//
// private class Distance {
// private int value;
// }
//
// private class Duration {
// private int value;
// }
// }
| import com.iph.directly.domain.apimodel.RouteResponse;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable; | package com.iph.directly.domain.rest;
/**
* Created by vanya on 10/17/2016.
*/
public interface DirectionApi {
@GET("/maps/api/directions/json") | // Path: app/src/prod/java/com/iph/directly/domain/apimodel/RouteResponse.java
// public class RouteResponse {
//
// private List<Route> routes;
//
// public int getDistance() {
// return this.routes.get(0).legs.get(0).distance.value;
// }
//
// public int getDuration() {
// return this.routes.get(0).legs.get(0).duration.value;
// }
//
// public String getPoints() {
// return this.routes.get(0).overview_polyline.points;
// }
//
// public boolean hasPoints() {
// return !routes.isEmpty();
// }
//
// private class Route {
// private OverviewPolyline overview_polyline;
// private List<Leg> legs;
// }
//
// private class OverviewPolyline {
// String points;
// }
//
// private class Leg {
// private Distance distance;
// private Duration duration;
// }
//
// private class Distance {
// private int value;
// }
//
// private class Duration {
// private int value;
// }
// }
// Path: app/src/prod/java/com/iph/directly/domain/rest/DirectionApi.java
import com.iph.directly.domain.apimodel.RouteResponse;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;
package com.iph.directly.domain.rest;
/**
* Created by vanya on 10/17/2016.
*/
public interface DirectionApi {
@GET("/maps/api/directions/json") | Observable<RouteResponse> getRoute( |
lvanyal/directly | app/src/main/java/com/iph/directly/view/LoadingView.java | // Path: app/src/main/java/com/iph/directly/domain/model/Location.java
// public class Location implements Parcelable{
// private LatLng latLng;
//
// private String city;
// private String country;
// private String street;
// private String buildingNumber;
//
// public Location(double latitude, double longitude, String city, String country) {
// this.latLng = new LatLng(latitude, longitude);
// this.city = city;
// this.country = country;
// }
//
// public Location(double latitude, double longitude, String city, String country, String street, String buildingNumber) {
// this.latLng = new LatLng(latitude, longitude);
// this.city = city;
// this.country = country;
// this.street = street;
// this.buildingNumber = buildingNumber;
// }
//
// protected Location(Parcel in) {
// latLng = in.readParcelable(LatLng.class.getClassLoader());
// city = in.readString();
// country = in.readString();
// this.street = in.readString();
// this.buildingNumber = in.readString();
// }
//
// public static final Creator<Location> CREATOR = new Creator<Location>() {
// @Override
// public Location createFromParcel(Parcel in) {
// return new Location(in);
// }
//
// @Override
// public Location[] newArray(int size) {
// return new Location[size];
// }
// };
//
// public LatLng getLatLng() {
// return latLng;
// }
//
// public void setLatLng(LatLng latLng) {
// this.latLng = latLng;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeParcelable(latLng, flags);
// dest.writeString(city);
// dest.writeString(country);
// dest.writeString(street);
// dest.writeString(buildingNumber);
// }
//
// public String getCountry() {
// return country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getStreet() {
// return street;
// }
//
// public String getBuildingNumber() {
// return buildingNumber;
// }
// }
| import android.app.PendingIntent;
import com.google.android.gms.common.api.Status;
import com.iph.directly.domain.model.Location; | package com.iph.directly.view;
/**
* Created by vanya on 10/8/2016.
*/
public interface LoadingView {
void showProgress();
| // Path: app/src/main/java/com/iph/directly/domain/model/Location.java
// public class Location implements Parcelable{
// private LatLng latLng;
//
// private String city;
// private String country;
// private String street;
// private String buildingNumber;
//
// public Location(double latitude, double longitude, String city, String country) {
// this.latLng = new LatLng(latitude, longitude);
// this.city = city;
// this.country = country;
// }
//
// public Location(double latitude, double longitude, String city, String country, String street, String buildingNumber) {
// this.latLng = new LatLng(latitude, longitude);
// this.city = city;
// this.country = country;
// this.street = street;
// this.buildingNumber = buildingNumber;
// }
//
// protected Location(Parcel in) {
// latLng = in.readParcelable(LatLng.class.getClassLoader());
// city = in.readString();
// country = in.readString();
// this.street = in.readString();
// this.buildingNumber = in.readString();
// }
//
// public static final Creator<Location> CREATOR = new Creator<Location>() {
// @Override
// public Location createFromParcel(Parcel in) {
// return new Location(in);
// }
//
// @Override
// public Location[] newArray(int size) {
// return new Location[size];
// }
// };
//
// public LatLng getLatLng() {
// return latLng;
// }
//
// public void setLatLng(LatLng latLng) {
// this.latLng = latLng;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeParcelable(latLng, flags);
// dest.writeString(city);
// dest.writeString(country);
// dest.writeString(street);
// dest.writeString(buildingNumber);
// }
//
// public String getCountry() {
// return country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getStreet() {
// return street;
// }
//
// public String getBuildingNumber() {
// return buildingNumber;
// }
// }
// Path: app/src/main/java/com/iph/directly/view/LoadingView.java
import android.app.PendingIntent;
import com.google.android.gms.common.api.Status;
import com.iph.directly.domain.model.Location;
package com.iph.directly.view;
/**
* Created by vanya on 10/8/2016.
*/
public interface LoadingView {
void showProgress();
| void navigateToToilets(Location location); |
lvanyal/directly | app/src/prod/java/com/iph/directly/domain/FeedbackRepositoryImpl.java | // Path: app/src/main/java/com/iph/directly/domain/model/Feedback.java
// public class Feedback {
// private String text;
//
// public Feedback(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
// }
| import android.support.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.iph.directly.domain.model.Feedback;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import rx.Observable; | package com.iph.directly.domain;
/**
* Created by vanya on 11/5/2016.
*/
public class FeedbackRepositoryImpl implements FeedbackRepository {
private static final String FEEDBACK_TREE = "feedbacks";
private DatabaseReference databaseReference;
private SimpleDateFormat dateFormat;
public FeedbackRepositoryImpl() {
databaseReference = FirebaseDatabase.getInstance().getReference();
dateFormat = new SimpleDateFormat("dd MM yyyy HH:mm:ss", Locale.getDefault());
}
@Override | // Path: app/src/main/java/com/iph/directly/domain/model/Feedback.java
// public class Feedback {
// private String text;
//
// public Feedback(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
// }
// Path: app/src/prod/java/com/iph/directly/domain/FeedbackRepositoryImpl.java
import android.support.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.iph.directly.domain.model.Feedback;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import rx.Observable;
package com.iph.directly.domain;
/**
* Created by vanya on 11/5/2016.
*/
public class FeedbackRepositoryImpl implements FeedbackRepository {
private static final String FEEDBACK_TREE = "feedbacks";
private DatabaseReference databaseReference;
private SimpleDateFormat dateFormat;
public FeedbackRepositoryImpl() {
databaseReference = FirebaseDatabase.getInstance().getReference();
dateFormat = new SimpleDateFormat("dd MM yyyy HH:mm:ss", Locale.getDefault());
}
@Override | public Observable<Feedback> putFeedback(String userId, String text) { |
lvanyal/directly | app/src/prod/java/com/iph/directly/domain/StrikeRepositoryImpl.java | // Path: app/src/main/java/com/iph/directly/domain/model/Strike.java
// public class Strike {
// @Expose
// private String userId;
//
// public String getUserId() {
// return userId;
// }
//
// public Strike(String userId) {
// this.userId = userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
// }
| import android.support.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.iph.directly.domain.model.Strike;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers; | package com.iph.directly.domain;
/**
* Created by vanya on 11/3/2016.
*/
public class StrikeRepositoryImpl implements StrikeRepository {
private static final String STRIKES_TREE = "strikes";
private DatabaseReference databaseReference;
public StrikeRepositoryImpl() {
databaseReference = FirebaseDatabase.getInstance().getReference();
}
public Observable<Boolean> isToiletStrikedByUser(String toiletId, String userId) {
return Observable.<Boolean>create(subscriber -> {
databaseReference.child(STRIKES_TREE).child(toiletId).child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
boolean exists = dataSnapshot.exists();
subscriber.onNext(exists);
subscriber.onCompleted();
}
@Override
public void onCancelled(DatabaseError databaseError) {
subscriber.onError(databaseError.toException());
}
});
}).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread());
}
@Override
public Observable<Integer> putStrike(String toiletId, String userId) {
return Observable.create(new Observable.OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) { | // Path: app/src/main/java/com/iph/directly/domain/model/Strike.java
// public class Strike {
// @Expose
// private String userId;
//
// public String getUserId() {
// return userId;
// }
//
// public Strike(String userId) {
// this.userId = userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
// }
// Path: app/src/prod/java/com/iph/directly/domain/StrikeRepositoryImpl.java
import android.support.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.iph.directly.domain.model.Strike;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
package com.iph.directly.domain;
/**
* Created by vanya on 11/3/2016.
*/
public class StrikeRepositoryImpl implements StrikeRepository {
private static final String STRIKES_TREE = "strikes";
private DatabaseReference databaseReference;
public StrikeRepositoryImpl() {
databaseReference = FirebaseDatabase.getInstance().getReference();
}
public Observable<Boolean> isToiletStrikedByUser(String toiletId, String userId) {
return Observable.<Boolean>create(subscriber -> {
databaseReference.child(STRIKES_TREE).child(toiletId).child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
boolean exists = dataSnapshot.exists();
subscriber.onNext(exists);
subscriber.onCompleted();
}
@Override
public void onCancelled(DatabaseError databaseError) {
subscriber.onError(databaseError.toException());
}
});
}).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread());
}
@Override
public Observable<Integer> putStrike(String toiletId, String userId) {
return Observable.create(new Observable.OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) { | Strike strike = new Strike(userId); |
lvanyal/directly | app/src/main/java/com/iph/directly/fragment/LoadingFragment.java | // Path: app/src/prod/java/com/iph/directly/domain/Injector.java
// public class Injector {
// public static LocationRepository provideLocationRepository(Fragment fragment, Activity activity, int requestCode) {
// return new LocationRepositoryImpl(fragment, activity, requestCode);
// }
//
// public static ToiletRepository provideToiletRepository(Activity activity) {
// return new ToiletRepositoryImpl(activity);
// }
//
// public static DirectionRepository provideDirectionRepository(Context activity) {
// return new DirectionRepositoryImpl(activity);
// }
//
// public static DeviceInfo provideDeviceInfo(Context context) {
// return new DeviceInfoImpl(context);
// }
//
// public static StrikeRepository provideStrikeRepository() {
// return new StrikeRepositoryImpl();
// }
//
// public static FeedbackRepository provideFeedbackRepository(){
// return new FeedbackRepositoryImpl();
// }
// }
//
// Path: app/src/main/java/com/iph/directly/domain/model/Location.java
// public class Location implements Parcelable{
// private LatLng latLng;
//
// private String city;
// private String country;
// private String street;
// private String buildingNumber;
//
// public Location(double latitude, double longitude, String city, String country) {
// this.latLng = new LatLng(latitude, longitude);
// this.city = city;
// this.country = country;
// }
//
// public Location(double latitude, double longitude, String city, String country, String street, String buildingNumber) {
// this.latLng = new LatLng(latitude, longitude);
// this.city = city;
// this.country = country;
// this.street = street;
// this.buildingNumber = buildingNumber;
// }
//
// protected Location(Parcel in) {
// latLng = in.readParcelable(LatLng.class.getClassLoader());
// city = in.readString();
// country = in.readString();
// this.street = in.readString();
// this.buildingNumber = in.readString();
// }
//
// public static final Creator<Location> CREATOR = new Creator<Location>() {
// @Override
// public Location createFromParcel(Parcel in) {
// return new Location(in);
// }
//
// @Override
// public Location[] newArray(int size) {
// return new Location[size];
// }
// };
//
// public LatLng getLatLng() {
// return latLng;
// }
//
// public void setLatLng(LatLng latLng) {
// this.latLng = latLng;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeParcelable(latLng, flags);
// dest.writeString(city);
// dest.writeString(country);
// dest.writeString(street);
// dest.writeString(buildingNumber);
// }
//
// public String getCountry() {
// return country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getStreet() {
// return street;
// }
//
// public String getBuildingNumber() {
// return buildingNumber;
// }
// }
//
// Path: app/src/main/java/com/iph/directly/presenter/LoadingPresenter.java
// public class LoadingPresenter {
// private LoadingView loadingView;
//
// private LocationRepository locationRepository;
//
// private Subscription currentSubscription;
//
// public LoadingPresenter(LoadingView loadingView, LocationRepository locationRepository) {
// this.loadingView = loadingView;
// this.locationRepository = locationRepository;
// }
//
// public void start() {
// loadingView.showProgress();
// currentSubscription = locationRepository.getCurrentLocation().subscribe(location -> {
// loadingView.navigateToToilets(location);
// }, throwable -> {
// if (throwable instanceof SecurityException) {
// loadingView.showRequestLocationPermission();
// } else {
// Timber.e(throwable, throwable.getMessage());
// }
// });
// }
//
// public void stop() {
// if (currentSubscription != null) {
// currentSubscription.unsubscribe();
// currentSubscription = null;
// }
// }
//
// public void locationPermissionSuccess() {
// start();
// }
//
// public void locationPermissionFailed() {
// loadingView.navigateToToilets(null);
// }
//
// public void locationEnabledSuccess() {
// start();
// }
//
// public void locationEnabledFailed() {
// loadingView.navigateToToilets(null);
// }
// }
//
// Path: app/src/main/java/com/iph/directly/view/LoadingView.java
// public interface LoadingView {
// void showProgress();
//
// void navigateToToilets(Location location);
//
// void showRequestLocationPermission();
// }
| import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.directly.iph.directly.R;
import com.google.android.gms.common.api.Status;
import com.iph.directly.domain.Injector;
import com.iph.directly.domain.model.Location;
import com.iph.directly.presenter.LoadingPresenter;
import com.iph.directly.view.LoadingView;
import timber.log.Timber; | package com.iph.directly.fragment;
/**
* Created by vanya on 10/8/2016.
*/
public class LoadingFragment extends Fragment implements LoadingView {
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;
private static final int LOCATION_ENABLE_REQUEST_CODE = 1002; | // Path: app/src/prod/java/com/iph/directly/domain/Injector.java
// public class Injector {
// public static LocationRepository provideLocationRepository(Fragment fragment, Activity activity, int requestCode) {
// return new LocationRepositoryImpl(fragment, activity, requestCode);
// }
//
// public static ToiletRepository provideToiletRepository(Activity activity) {
// return new ToiletRepositoryImpl(activity);
// }
//
// public static DirectionRepository provideDirectionRepository(Context activity) {
// return new DirectionRepositoryImpl(activity);
// }
//
// public static DeviceInfo provideDeviceInfo(Context context) {
// return new DeviceInfoImpl(context);
// }
//
// public static StrikeRepository provideStrikeRepository() {
// return new StrikeRepositoryImpl();
// }
//
// public static FeedbackRepository provideFeedbackRepository(){
// return new FeedbackRepositoryImpl();
// }
// }
//
// Path: app/src/main/java/com/iph/directly/domain/model/Location.java
// public class Location implements Parcelable{
// private LatLng latLng;
//
// private String city;
// private String country;
// private String street;
// private String buildingNumber;
//
// public Location(double latitude, double longitude, String city, String country) {
// this.latLng = new LatLng(latitude, longitude);
// this.city = city;
// this.country = country;
// }
//
// public Location(double latitude, double longitude, String city, String country, String street, String buildingNumber) {
// this.latLng = new LatLng(latitude, longitude);
// this.city = city;
// this.country = country;
// this.street = street;
// this.buildingNumber = buildingNumber;
// }
//
// protected Location(Parcel in) {
// latLng = in.readParcelable(LatLng.class.getClassLoader());
// city = in.readString();
// country = in.readString();
// this.street = in.readString();
// this.buildingNumber = in.readString();
// }
//
// public static final Creator<Location> CREATOR = new Creator<Location>() {
// @Override
// public Location createFromParcel(Parcel in) {
// return new Location(in);
// }
//
// @Override
// public Location[] newArray(int size) {
// return new Location[size];
// }
// };
//
// public LatLng getLatLng() {
// return latLng;
// }
//
// public void setLatLng(LatLng latLng) {
// this.latLng = latLng;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeParcelable(latLng, flags);
// dest.writeString(city);
// dest.writeString(country);
// dest.writeString(street);
// dest.writeString(buildingNumber);
// }
//
// public String getCountry() {
// return country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getStreet() {
// return street;
// }
//
// public String getBuildingNumber() {
// return buildingNumber;
// }
// }
//
// Path: app/src/main/java/com/iph/directly/presenter/LoadingPresenter.java
// public class LoadingPresenter {
// private LoadingView loadingView;
//
// private LocationRepository locationRepository;
//
// private Subscription currentSubscription;
//
// public LoadingPresenter(LoadingView loadingView, LocationRepository locationRepository) {
// this.loadingView = loadingView;
// this.locationRepository = locationRepository;
// }
//
// public void start() {
// loadingView.showProgress();
// currentSubscription = locationRepository.getCurrentLocation().subscribe(location -> {
// loadingView.navigateToToilets(location);
// }, throwable -> {
// if (throwable instanceof SecurityException) {
// loadingView.showRequestLocationPermission();
// } else {
// Timber.e(throwable, throwable.getMessage());
// }
// });
// }
//
// public void stop() {
// if (currentSubscription != null) {
// currentSubscription.unsubscribe();
// currentSubscription = null;
// }
// }
//
// public void locationPermissionSuccess() {
// start();
// }
//
// public void locationPermissionFailed() {
// loadingView.navigateToToilets(null);
// }
//
// public void locationEnabledSuccess() {
// start();
// }
//
// public void locationEnabledFailed() {
// loadingView.navigateToToilets(null);
// }
// }
//
// Path: app/src/main/java/com/iph/directly/view/LoadingView.java
// public interface LoadingView {
// void showProgress();
//
// void navigateToToilets(Location location);
//
// void showRequestLocationPermission();
// }
// Path: app/src/main/java/com/iph/directly/fragment/LoadingFragment.java
import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.directly.iph.directly.R;
import com.google.android.gms.common.api.Status;
import com.iph.directly.domain.Injector;
import com.iph.directly.domain.model.Location;
import com.iph.directly.presenter.LoadingPresenter;
import com.iph.directly.view.LoadingView;
import timber.log.Timber;
package com.iph.directly.fragment;
/**
* Created by vanya on 10/8/2016.
*/
public class LoadingFragment extends Fragment implements LoadingView {
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;
private static final int LOCATION_ENABLE_REQUEST_CODE = 1002; | private LoadingPresenter loadingPresenter; |
chemouna/Decor | samples/src/main/java/com/mounacheikhna/decor/samples/SampleActivity.java | // Path: decor/src/main/java/com/mounacheikhna/decor/DecorContextWrapper.java
// public class DecorContextWrapper extends ContextWrapper {
//
// private DecorLayoutInflater mInflater;
// private List<Decorator> mDecorators;
//
// /**
// * @param base ContextBase to Wrap.
// */
// public DecorContextWrapper(Context base) {
// super(base);
// mDecorators = new ArrayList<>();
// }
//
// /**
// * wrap the context
// * @param base ContextBase to Wrap.
// * @return ContextWrapper to pass back to the activity.
// */
// public static DecorContextWrapper wrap(Context base) {
// return new DecorContextWrapper(base);
// }
//
// public ContextWrapper with(Decorator... decorators) {
// Collections.addAll(mDecorators, decorators);
// return this;
// }
//
// @Override
// public Object getSystemService(String name) {
// if(LAYOUT_INFLATER_SERVICE.equals(name)) {
// if(mInflater == null) {
// mInflater = new DecorLayoutInflater(LayoutInflater.from(getBaseContext()), this, mDecorators, false);
// }
// return mInflater;
// }
// return super.getSystemService(name);
// }
//
// }
//
// Path: decorators/src/main/java/com/mounacheikhna/decorators/Decorators.java
// public final class Decorators {
//
// /**
// * Get all the decorators already defined
// * @return available decorators
// */
// public static Decorator[] getAll() {
// return new Decorator[] {
// new AutofitDecorator(),
// new BlurDecorator(),
// new ColorFilterDecorator(),
// new ErrorDecorator(),
// new FontDecorator(),
// new ReloadTextDecorator()
// };
// }
//
// }
| import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import com.mounacheikhna.decor.DecorContextWrapper;
import com.mounacheikhna.decorators.Decorators; | package com.mounacheikhna.decor.samples;
public class SampleActivity extends FragmentActivity /*ActionBarActivity*/ /*Activity*/ {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onIvTouch() {
Toast.makeText(this, " Touch detected ", Toast.LENGTH_SHORT).show();
}
public void onRobotLongClick() {
Toast.makeText(this, " Long click detected ", Toast.LENGTH_SHORT).show();
}
@Override
protected void attachBaseContext(Context newBase) { | // Path: decor/src/main/java/com/mounacheikhna/decor/DecorContextWrapper.java
// public class DecorContextWrapper extends ContextWrapper {
//
// private DecorLayoutInflater mInflater;
// private List<Decorator> mDecorators;
//
// /**
// * @param base ContextBase to Wrap.
// */
// public DecorContextWrapper(Context base) {
// super(base);
// mDecorators = new ArrayList<>();
// }
//
// /**
// * wrap the context
// * @param base ContextBase to Wrap.
// * @return ContextWrapper to pass back to the activity.
// */
// public static DecorContextWrapper wrap(Context base) {
// return new DecorContextWrapper(base);
// }
//
// public ContextWrapper with(Decorator... decorators) {
// Collections.addAll(mDecorators, decorators);
// return this;
// }
//
// @Override
// public Object getSystemService(String name) {
// if(LAYOUT_INFLATER_SERVICE.equals(name)) {
// if(mInflater == null) {
// mInflater = new DecorLayoutInflater(LayoutInflater.from(getBaseContext()), this, mDecorators, false);
// }
// return mInflater;
// }
// return super.getSystemService(name);
// }
//
// }
//
// Path: decorators/src/main/java/com/mounacheikhna/decorators/Decorators.java
// public final class Decorators {
//
// /**
// * Get all the decorators already defined
// * @return available decorators
// */
// public static Decorator[] getAll() {
// return new Decorator[] {
// new AutofitDecorator(),
// new BlurDecorator(),
// new ColorFilterDecorator(),
// new ErrorDecorator(),
// new FontDecorator(),
// new ReloadTextDecorator()
// };
// }
//
// }
// Path: samples/src/main/java/com/mounacheikhna/decor/samples/SampleActivity.java
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import com.mounacheikhna.decor.DecorContextWrapper;
import com.mounacheikhna.decorators.Decorators;
package com.mounacheikhna.decor.samples;
public class SampleActivity extends FragmentActivity /*ActionBarActivity*/ /*Activity*/ {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onIvTouch() {
Toast.makeText(this, " Touch detected ", Toast.LENGTH_SHORT).show();
}
public void onRobotLongClick() {
Toast.makeText(this, " Long click detected ", Toast.LENGTH_SHORT).show();
}
@Override
protected void attachBaseContext(Context newBase) { | super.attachBaseContext(DecorContextWrapper.wrap(newBase) |
chemouna/Decor | samples/src/main/java/com/mounacheikhna/decor/samples/SampleActivity.java | // Path: decor/src/main/java/com/mounacheikhna/decor/DecorContextWrapper.java
// public class DecorContextWrapper extends ContextWrapper {
//
// private DecorLayoutInflater mInflater;
// private List<Decorator> mDecorators;
//
// /**
// * @param base ContextBase to Wrap.
// */
// public DecorContextWrapper(Context base) {
// super(base);
// mDecorators = new ArrayList<>();
// }
//
// /**
// * wrap the context
// * @param base ContextBase to Wrap.
// * @return ContextWrapper to pass back to the activity.
// */
// public static DecorContextWrapper wrap(Context base) {
// return new DecorContextWrapper(base);
// }
//
// public ContextWrapper with(Decorator... decorators) {
// Collections.addAll(mDecorators, decorators);
// return this;
// }
//
// @Override
// public Object getSystemService(String name) {
// if(LAYOUT_INFLATER_SERVICE.equals(name)) {
// if(mInflater == null) {
// mInflater = new DecorLayoutInflater(LayoutInflater.from(getBaseContext()), this, mDecorators, false);
// }
// return mInflater;
// }
// return super.getSystemService(name);
// }
//
// }
//
// Path: decorators/src/main/java/com/mounacheikhna/decorators/Decorators.java
// public final class Decorators {
//
// /**
// * Get all the decorators already defined
// * @return available decorators
// */
// public static Decorator[] getAll() {
// return new Decorator[] {
// new AutofitDecorator(),
// new BlurDecorator(),
// new ColorFilterDecorator(),
// new ErrorDecorator(),
// new FontDecorator(),
// new ReloadTextDecorator()
// };
// }
//
// }
| import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import com.mounacheikhna.decor.DecorContextWrapper;
import com.mounacheikhna.decorators.Decorators; | package com.mounacheikhna.decor.samples;
public class SampleActivity extends FragmentActivity /*ActionBarActivity*/ /*Activity*/ {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onIvTouch() {
Toast.makeText(this, " Touch detected ", Toast.LENGTH_SHORT).show();
}
public void onRobotLongClick() {
Toast.makeText(this, " Long click detected ", Toast.LENGTH_SHORT).show();
}
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(DecorContextWrapper.wrap(newBase) | // Path: decor/src/main/java/com/mounacheikhna/decor/DecorContextWrapper.java
// public class DecorContextWrapper extends ContextWrapper {
//
// private DecorLayoutInflater mInflater;
// private List<Decorator> mDecorators;
//
// /**
// * @param base ContextBase to Wrap.
// */
// public DecorContextWrapper(Context base) {
// super(base);
// mDecorators = new ArrayList<>();
// }
//
// /**
// * wrap the context
// * @param base ContextBase to Wrap.
// * @return ContextWrapper to pass back to the activity.
// */
// public static DecorContextWrapper wrap(Context base) {
// return new DecorContextWrapper(base);
// }
//
// public ContextWrapper with(Decorator... decorators) {
// Collections.addAll(mDecorators, decorators);
// return this;
// }
//
// @Override
// public Object getSystemService(String name) {
// if(LAYOUT_INFLATER_SERVICE.equals(name)) {
// if(mInflater == null) {
// mInflater = new DecorLayoutInflater(LayoutInflater.from(getBaseContext()), this, mDecorators, false);
// }
// return mInflater;
// }
// return super.getSystemService(name);
// }
//
// }
//
// Path: decorators/src/main/java/com/mounacheikhna/decorators/Decorators.java
// public final class Decorators {
//
// /**
// * Get all the decorators already defined
// * @return available decorators
// */
// public static Decorator[] getAll() {
// return new Decorator[] {
// new AutofitDecorator(),
// new BlurDecorator(),
// new ColorFilterDecorator(),
// new ErrorDecorator(),
// new FontDecorator(),
// new ReloadTextDecorator()
// };
// }
//
// }
// Path: samples/src/main/java/com/mounacheikhna/decor/samples/SampleActivity.java
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import com.mounacheikhna.decor.DecorContextWrapper;
import com.mounacheikhna.decorators.Decorators;
package com.mounacheikhna.decor.samples;
public class SampleActivity extends FragmentActivity /*ActionBarActivity*/ /*Activity*/ {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onIvTouch() {
Toast.makeText(this, " Touch detected ", Toast.LENGTH_SHORT).show();
}
public void onRobotLongClick() {
Toast.makeText(this, " Long click detected ", Toast.LENGTH_SHORT).show();
}
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(DecorContextWrapper.wrap(newBase) | .with(Decorators.getAll())); |
chemouna/Decor | decorators/src/main/java/com/mounacheikhna/decorators/BlurDecorator.java | // Path: decor/src/main/java/com/mounacheikhna/decor/AttrsDecorator.java
// public abstract class AttrsDecorator<T extends View> implements Decorator {
//
// TypedArray values;
//
// @Override
// public void apply(View view, View parent, String name, Context context, AttributeSet attributeSet) {
// if (!clazz().isAssignableFrom(view.getClass())) {
// return;
// }
//
// values = obtainAttributes(context, attributeSet);
// if(values == null || values.length() == 0) return;
//
// try {
// for (int i = 0; i < values.length(); i++) {
// TypedValue buf = new TypedValue();
// if (values.hasValue(i) && values.getValue(i, buf)) {
// apply((T) view, values);
// break;
// }
// }
// } finally {
// values.recycle();
// }
// }
//
// TypedArray obtainAttributes(Context context, AttributeSet attributeSet) {
// //TODO: instead of always passing 0 here for defStyleAttr : make it accept theme setted attribute
// return context.getTheme().obtainStyledAttributes(attributeSet, styleable(), defStyleAttr(), 0);
// }
//
// protected abstract int[] styleable();
//
// protected int defStyleAttr() {
// return 0;
// }
//
// /**
// * The class for the given viewtype. Please be kind and just return the right class here :)
// *
// * @return The class/typetoken for T
// */
// protected abstract Class<T> clazz();
//
// /**
// * This method will be called if a View of type T was inflated and it had one of the attributes
// * specified by {@link AttrsDecorator#styleable()} set.
// * @param view The view object that is being decorated.
// * @param typedArray A {@link TypedArray} for attributes.
// *
// */
// protected abstract void apply(T view, TypedArray typedArray);
//
// }
//
// Path: decorators/src/main/java/com/mounacheikhna/decorators/utils/BlurUtils.java
// public class BlurUtils {
// private static final float SCALE_RATIO = 5f;
// private static final float DEFAULT_BLUR_RADIUS = 5.f;
//
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// public static Bitmap blurBitmap(Bitmap bitmap, Context context){
// int width = bitmap.getWidth(), height = bitmap.getHeight();
// Bitmap b = Bitmap.createScaledBitmap(Bitmap.createScaledBitmap(bitmap,(int)(width/SCALE_RATIO), (int)(height/SCALE_RATIO), false), width, height, false);
// return blurBitmap(b, DEFAULT_BLUR_RADIUS, context);
// }
//
//
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// private static Bitmap blurBitmap(Bitmap src, float blurRadius, Context context) {
// RenderScript rs = RenderScript.create(context);
// Bitmap.Config conf = Bitmap.Config.ARGB_8888;
// Bitmap blurredBitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(), conf);
//
// final Allocation input = Allocation.createFromBitmap(rs, src, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
// final Allocation output = Allocation.createTyped(rs, input.getType());
//
// final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// script.setRadius(blurRadius);
// script.setInput(input);
// script.forEach(output);
// output.copyTo(blurredBitmap);
// return blurredBitmap;
// }
//
// }
| import android.content.res.TypedArray;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.mounacheikhna.decor.AttrsDecorator;
import com.mounacheikhna.decorators.utils.BlurUtils; | package com.mounacheikhna.decorators;
/**
* Created by cheikhna on 03/04/2015.
*/
public class BlurDecorator extends AttrsDecorator<View> {
@Override
protected int[] styleable() {
return R.styleable.BlurDecorator;
}
@Override
protected Class<View> clazz() {
return View.class;
}
@Override
protected void apply(View view, TypedArray typedArray) {
boolean isBlur = typedArray.getBoolean(R.styleable.BlurDecorator_decorBlur, false);
if(!isBlur || Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) return;
//i'm guessing this part here doesn't work because i'm using the same blur as ngAndroid and they are
//doing their injection in a different point in the inflation
ViewGroup parent = (ViewGroup) view.getParent();
FrameLayout layout = new FrameLayout(view.getContext());
layout.setLayoutParams(view.getLayoutParams());
int index = parent.indexOfChild(view);
parent.removeViewAt(index);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
view.setLayoutParams(layoutParams);
layout.addView(view);
parent.addView(layout, index);
final ImageView imageView = new ImageView(view.getContext());
imageView.setLayoutParams(layoutParams);
imageView.setVisibility(View.GONE);
layout.addView(imageView);
view.setVisibility(View.GONE);
view.setDrawingCacheEnabled(true); | // Path: decor/src/main/java/com/mounacheikhna/decor/AttrsDecorator.java
// public abstract class AttrsDecorator<T extends View> implements Decorator {
//
// TypedArray values;
//
// @Override
// public void apply(View view, View parent, String name, Context context, AttributeSet attributeSet) {
// if (!clazz().isAssignableFrom(view.getClass())) {
// return;
// }
//
// values = obtainAttributes(context, attributeSet);
// if(values == null || values.length() == 0) return;
//
// try {
// for (int i = 0; i < values.length(); i++) {
// TypedValue buf = new TypedValue();
// if (values.hasValue(i) && values.getValue(i, buf)) {
// apply((T) view, values);
// break;
// }
// }
// } finally {
// values.recycle();
// }
// }
//
// TypedArray obtainAttributes(Context context, AttributeSet attributeSet) {
// //TODO: instead of always passing 0 here for defStyleAttr : make it accept theme setted attribute
// return context.getTheme().obtainStyledAttributes(attributeSet, styleable(), defStyleAttr(), 0);
// }
//
// protected abstract int[] styleable();
//
// protected int defStyleAttr() {
// return 0;
// }
//
// /**
// * The class for the given viewtype. Please be kind and just return the right class here :)
// *
// * @return The class/typetoken for T
// */
// protected abstract Class<T> clazz();
//
// /**
// * This method will be called if a View of type T was inflated and it had one of the attributes
// * specified by {@link AttrsDecorator#styleable()} set.
// * @param view The view object that is being decorated.
// * @param typedArray A {@link TypedArray} for attributes.
// *
// */
// protected abstract void apply(T view, TypedArray typedArray);
//
// }
//
// Path: decorators/src/main/java/com/mounacheikhna/decorators/utils/BlurUtils.java
// public class BlurUtils {
// private static final float SCALE_RATIO = 5f;
// private static final float DEFAULT_BLUR_RADIUS = 5.f;
//
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// public static Bitmap blurBitmap(Bitmap bitmap, Context context){
// int width = bitmap.getWidth(), height = bitmap.getHeight();
// Bitmap b = Bitmap.createScaledBitmap(Bitmap.createScaledBitmap(bitmap,(int)(width/SCALE_RATIO), (int)(height/SCALE_RATIO), false), width, height, false);
// return blurBitmap(b, DEFAULT_BLUR_RADIUS, context);
// }
//
//
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// private static Bitmap blurBitmap(Bitmap src, float blurRadius, Context context) {
// RenderScript rs = RenderScript.create(context);
// Bitmap.Config conf = Bitmap.Config.ARGB_8888;
// Bitmap blurredBitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(), conf);
//
// final Allocation input = Allocation.createFromBitmap(rs, src, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
// final Allocation output = Allocation.createTyped(rs, input.getType());
//
// final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// script.setRadius(blurRadius);
// script.setInput(input);
// script.forEach(output);
// output.copyTo(blurredBitmap);
// return blurredBitmap;
// }
//
// }
// Path: decorators/src/main/java/com/mounacheikhna/decorators/BlurDecorator.java
import android.content.res.TypedArray;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.mounacheikhna.decor.AttrsDecorator;
import com.mounacheikhna.decorators.utils.BlurUtils;
package com.mounacheikhna.decorators;
/**
* Created by cheikhna on 03/04/2015.
*/
public class BlurDecorator extends AttrsDecorator<View> {
@Override
protected int[] styleable() {
return R.styleable.BlurDecorator;
}
@Override
protected Class<View> clazz() {
return View.class;
}
@Override
protected void apply(View view, TypedArray typedArray) {
boolean isBlur = typedArray.getBoolean(R.styleable.BlurDecorator_decorBlur, false);
if(!isBlur || Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) return;
//i'm guessing this part here doesn't work because i'm using the same blur as ngAndroid and they are
//doing their injection in a different point in the inflation
ViewGroup parent = (ViewGroup) view.getParent();
FrameLayout layout = new FrameLayout(view.getContext());
layout.setLayoutParams(view.getLayoutParams());
int index = parent.indexOfChild(view);
parent.removeViewAt(index);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
view.setLayoutParams(layoutParams);
layout.addView(view);
parent.addView(layout, index);
final ImageView imageView = new ImageView(view.getContext());
imageView.setLayoutParams(layoutParams);
imageView.setVisibility(View.GONE);
layout.addView(imageView);
view.setVisibility(View.GONE);
view.setDrawingCacheEnabled(true); | imageView.setImageBitmap(BlurUtils.blurBitmap(view.getDrawingCache(), view.getContext())); |
chemouna/Decor | samples/src/main/java/com/mounacheikhna/decor/samples/SampleApp.java | // Path: decor/src/main/java/com/mounacheikhna/decor/DecorContextWrapper.java
// public class DecorContextWrapper extends ContextWrapper {
//
// private DecorLayoutInflater mInflater;
// private List<Decorator> mDecorators;
//
// /**
// * @param base ContextBase to Wrap.
// */
// public DecorContextWrapper(Context base) {
// super(base);
// mDecorators = new ArrayList<>();
// }
//
// /**
// * wrap the context
// * @param base ContextBase to Wrap.
// * @return ContextWrapper to pass back to the activity.
// */
// public static DecorContextWrapper wrap(Context base) {
// return new DecorContextWrapper(base);
// }
//
// public ContextWrapper with(Decorator... decorators) {
// Collections.addAll(mDecorators, decorators);
// return this;
// }
//
// @Override
// public Object getSystemService(String name) {
// if(LAYOUT_INFLATER_SERVICE.equals(name)) {
// if(mInflater == null) {
// mInflater = new DecorLayoutInflater(LayoutInflater.from(getBaseContext()), this, mDecorators, false);
// }
// return mInflater;
// }
// return super.getSystemService(name);
// }
//
// }
//
// Path: decorators/src/main/java/com/mounacheikhna/decorators/Decorators.java
// public final class Decorators {
//
// /**
// * Get all the decorators already defined
// * @return available decorators
// */
// public static Decorator[] getAll() {
// return new Decorator[] {
// new AutofitDecorator(),
// new BlurDecorator(),
// new ColorFilterDecorator(),
// new ErrorDecorator(),
// new FontDecorator(),
// new ReloadTextDecorator()
// };
// }
//
// }
| import android.app.Application;
import android.content.Context;
import com.mounacheikhna.decor.DecorContextWrapper;
import com.mounacheikhna.decorators.Decorators; | package com.mounacheikhna.decor.samples;
public class SampleApp extends Application {
@Override
protected void attachBaseContext(Context newBase) { | // Path: decor/src/main/java/com/mounacheikhna/decor/DecorContextWrapper.java
// public class DecorContextWrapper extends ContextWrapper {
//
// private DecorLayoutInflater mInflater;
// private List<Decorator> mDecorators;
//
// /**
// * @param base ContextBase to Wrap.
// */
// public DecorContextWrapper(Context base) {
// super(base);
// mDecorators = new ArrayList<>();
// }
//
// /**
// * wrap the context
// * @param base ContextBase to Wrap.
// * @return ContextWrapper to pass back to the activity.
// */
// public static DecorContextWrapper wrap(Context base) {
// return new DecorContextWrapper(base);
// }
//
// public ContextWrapper with(Decorator... decorators) {
// Collections.addAll(mDecorators, decorators);
// return this;
// }
//
// @Override
// public Object getSystemService(String name) {
// if(LAYOUT_INFLATER_SERVICE.equals(name)) {
// if(mInflater == null) {
// mInflater = new DecorLayoutInflater(LayoutInflater.from(getBaseContext()), this, mDecorators, false);
// }
// return mInflater;
// }
// return super.getSystemService(name);
// }
//
// }
//
// Path: decorators/src/main/java/com/mounacheikhna/decorators/Decorators.java
// public final class Decorators {
//
// /**
// * Get all the decorators already defined
// * @return available decorators
// */
// public static Decorator[] getAll() {
// return new Decorator[] {
// new AutofitDecorator(),
// new BlurDecorator(),
// new ColorFilterDecorator(),
// new ErrorDecorator(),
// new FontDecorator(),
// new ReloadTextDecorator()
// };
// }
//
// }
// Path: samples/src/main/java/com/mounacheikhna/decor/samples/SampleApp.java
import android.app.Application;
import android.content.Context;
import com.mounacheikhna.decor.DecorContextWrapper;
import com.mounacheikhna.decorators.Decorators;
package com.mounacheikhna.decor.samples;
public class SampleApp extends Application {
@Override
protected void attachBaseContext(Context newBase) { | super.attachBaseContext(DecorContextWrapper.wrap(newBase) |
chemouna/Decor | samples/src/main/java/com/mounacheikhna/decor/samples/SampleApp.java | // Path: decor/src/main/java/com/mounacheikhna/decor/DecorContextWrapper.java
// public class DecorContextWrapper extends ContextWrapper {
//
// private DecorLayoutInflater mInflater;
// private List<Decorator> mDecorators;
//
// /**
// * @param base ContextBase to Wrap.
// */
// public DecorContextWrapper(Context base) {
// super(base);
// mDecorators = new ArrayList<>();
// }
//
// /**
// * wrap the context
// * @param base ContextBase to Wrap.
// * @return ContextWrapper to pass back to the activity.
// */
// public static DecorContextWrapper wrap(Context base) {
// return new DecorContextWrapper(base);
// }
//
// public ContextWrapper with(Decorator... decorators) {
// Collections.addAll(mDecorators, decorators);
// return this;
// }
//
// @Override
// public Object getSystemService(String name) {
// if(LAYOUT_INFLATER_SERVICE.equals(name)) {
// if(mInflater == null) {
// mInflater = new DecorLayoutInflater(LayoutInflater.from(getBaseContext()), this, mDecorators, false);
// }
// return mInflater;
// }
// return super.getSystemService(name);
// }
//
// }
//
// Path: decorators/src/main/java/com/mounacheikhna/decorators/Decorators.java
// public final class Decorators {
//
// /**
// * Get all the decorators already defined
// * @return available decorators
// */
// public static Decorator[] getAll() {
// return new Decorator[] {
// new AutofitDecorator(),
// new BlurDecorator(),
// new ColorFilterDecorator(),
// new ErrorDecorator(),
// new FontDecorator(),
// new ReloadTextDecorator()
// };
// }
//
// }
| import android.app.Application;
import android.content.Context;
import com.mounacheikhna.decor.DecorContextWrapper;
import com.mounacheikhna.decorators.Decorators; | package com.mounacheikhna.decor.samples;
public class SampleApp extends Application {
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(DecorContextWrapper.wrap(newBase) | // Path: decor/src/main/java/com/mounacheikhna/decor/DecorContextWrapper.java
// public class DecorContextWrapper extends ContextWrapper {
//
// private DecorLayoutInflater mInflater;
// private List<Decorator> mDecorators;
//
// /**
// * @param base ContextBase to Wrap.
// */
// public DecorContextWrapper(Context base) {
// super(base);
// mDecorators = new ArrayList<>();
// }
//
// /**
// * wrap the context
// * @param base ContextBase to Wrap.
// * @return ContextWrapper to pass back to the activity.
// */
// public static DecorContextWrapper wrap(Context base) {
// return new DecorContextWrapper(base);
// }
//
// public ContextWrapper with(Decorator... decorators) {
// Collections.addAll(mDecorators, decorators);
// return this;
// }
//
// @Override
// public Object getSystemService(String name) {
// if(LAYOUT_INFLATER_SERVICE.equals(name)) {
// if(mInflater == null) {
// mInflater = new DecorLayoutInflater(LayoutInflater.from(getBaseContext()), this, mDecorators, false);
// }
// return mInflater;
// }
// return super.getSystemService(name);
// }
//
// }
//
// Path: decorators/src/main/java/com/mounacheikhna/decorators/Decorators.java
// public final class Decorators {
//
// /**
// * Get all the decorators already defined
// * @return available decorators
// */
// public static Decorator[] getAll() {
// return new Decorator[] {
// new AutofitDecorator(),
// new BlurDecorator(),
// new ColorFilterDecorator(),
// new ErrorDecorator(),
// new FontDecorator(),
// new ReloadTextDecorator()
// };
// }
//
// }
// Path: samples/src/main/java/com/mounacheikhna/decor/samples/SampleApp.java
import android.app.Application;
import android.content.Context;
import com.mounacheikhna.decor.DecorContextWrapper;
import com.mounacheikhna.decorators.Decorators;
package com.mounacheikhna.decor.samples;
public class SampleApp extends Application {
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(DecorContextWrapper.wrap(newBase) | .with(Decorators.getAll())); |
szmg/grafana-dashboard-generator-java | grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/Utils.java | // Path: domain/src/main/java/uk/co/szmg/grafana/domain/SelectedTemplate.java
// public class SelectedTemplate {
//
// private String text;
// private String value;
//
// public SelectedTemplate() { }
//
// public SelectedTemplate(String text, String value) {
// this.text = text;
// this.value = value;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
| import static uk.co.szmg.grafana.domain.DomainFactories.newTemplateOption;
import static uk.co.szmg.grafana.domain.DomainFactories.newText;
import uk.co.szmg.grafana.domain.Dashboard;
import uk.co.szmg.grafana.domain.SelectedTemplate;
import static uk.co.szmg.grafana.domain.DomainFactories.newAlertAnnotation;
import static uk.co.szmg.grafana.domain.DomainFactories.newAnnotationList;
import static uk.co.szmg.grafana.domain.DomainFactories.newDashboard;
import static uk.co.szmg.grafana.domain.DomainFactories.newGraphiteAnnotation;
import static uk.co.szmg.grafana.domain.DomainFactories.newRow;
import static uk.co.szmg.grafana.domain.DomainFactories.newTemplate;
import static uk.co.szmg.grafana.domain.DomainFactories.newTemplateList; | package uk.co.szmg.grafana.example.dashboards;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
public class Utils {
public static Dashboard createSimpleDashboard(String title, Class<?> clazz) {
return newDashboard()
.withTitle(title)
.addRow(newRow()
.addPanel(newText()
.withSpan(12).withContent("This was created by " + clazz.getSimpleName())))
.addRow(newRow()
.withHeight("95px")
.addPanel(newText()
.withSpan(12).withContent("Selected env: $env")))
.withAnnotations(newAnnotationList()
.addList(newAlertAnnotation()
.withName("alert")
.withLimit(300)
.withEnable(true))
.addList(newGraphiteAnnotation()
.withName("deployment")
.withDatasource("graphite")
.withTarget("app.deployment")
.withIconColor("green")))
.withTemplating(newTemplateList()
.addList(newTemplate()
.withName("env")
.withLabel("Environment")
.withType("custom")
.withQuery("staging,canary,production,perf")
// options have to be added... templating support should be revised...
.addOption(newTemplateOption().withValue("staging").withText("staging"))
.addOption(newTemplateOption().withValue("production").withText("production")) | // Path: domain/src/main/java/uk/co/szmg/grafana/domain/SelectedTemplate.java
// public class SelectedTemplate {
//
// private String text;
// private String value;
//
// public SelectedTemplate() { }
//
// public SelectedTemplate(String text, String value) {
// this.text = text;
// this.value = value;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
// Path: grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/Utils.java
import static uk.co.szmg.grafana.domain.DomainFactories.newTemplateOption;
import static uk.co.szmg.grafana.domain.DomainFactories.newText;
import uk.co.szmg.grafana.domain.Dashboard;
import uk.co.szmg.grafana.domain.SelectedTemplate;
import static uk.co.szmg.grafana.domain.DomainFactories.newAlertAnnotation;
import static uk.co.szmg.grafana.domain.DomainFactories.newAnnotationList;
import static uk.co.szmg.grafana.domain.DomainFactories.newDashboard;
import static uk.co.szmg.grafana.domain.DomainFactories.newGraphiteAnnotation;
import static uk.co.szmg.grafana.domain.DomainFactories.newRow;
import static uk.co.szmg.grafana.domain.DomainFactories.newTemplate;
import static uk.co.szmg.grafana.domain.DomainFactories.newTemplateList;
package uk.co.szmg.grafana.example.dashboards;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
public class Utils {
public static Dashboard createSimpleDashboard(String title, Class<?> clazz) {
return newDashboard()
.withTitle(title)
.addRow(newRow()
.addPanel(newText()
.withSpan(12).withContent("This was created by " + clazz.getSimpleName())))
.addRow(newRow()
.withHeight("95px")
.addPanel(newText()
.withSpan(12).withContent("Selected env: $env")))
.withAnnotations(newAnnotationList()
.addList(newAlertAnnotation()
.withName("alert")
.withLimit(300)
.withEnable(true))
.addList(newGraphiteAnnotation()
.withName("deployment")
.withDatasource("graphite")
.withTarget("app.deployment")
.withIconColor("green")))
.withTemplating(newTemplateList()
.addList(newTemplate()
.withName("env")
.withLabel("Environment")
.withType("custom")
.withQuery("staging,canary,production,perf")
// options have to be added... templating support should be revised...
.addOption(newTemplateOption().withValue("staging").withText("staging"))
.addOption(newTemplateOption().withValue("production").withText("production")) | .withCurrent(new SelectedTemplate("staging", "staging")))); |
szmg/grafana-dashboard-generator-java | grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/stores/GrafanaEndpointParser.java | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/GrafanaEndpoint.java
// public class GrafanaEndpoint {
//
// private String baseUrl;
// private String apiKey;
// private String sessionCookie;
// private boolean skipSSLValidation;
//
// /**
// * Gets Grafana base URL.
// * @return base URL
// */
// public String getBaseUrl() {
// return baseUrl;
// }
//
// /**
// * Sets Grafana base URL.
// * @param baseUrl Grafana base URL
// */
// public void setBaseUrl(String baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// /**
// * Gets API key.
// * @return API key
// */
// public String getApiKey() {
// return apiKey;
// }
//
// /**
// * True if SSL cert check should be forced to pass.
// * @return value of skipSSLValidation
// */
// public boolean isSkipSSLValidation() {
// return skipSSLValidation;
// }
//
// /**
// * Sets API gey.
// *
// * http://docs.grafana.org/http_api/auth/
// *
// * You need either this or the sessionCookie for authentication.
// *
// * @param apiKey API key
// */
// public void setApiKey(String apiKey) {
// this.apiKey = apiKey;
// }
//
// /**
// * Gets session cookie.
// * @return session cookie
// */
// public String getSessionCookie() {
// return sessionCookie;
// }
//
// /**
// * Sets session cookie.
// *
// * To get the value log in and copy the value of the "grafana_sess" cookie.
// *
// * You need either this or the apiKey for authentication.
// *
// * @param sessionCookie session cookie
// */
// public void setSessionCookie(String sessionCookie) {
// this.sessionCookie = sessionCookie;
// }
//
// /**
// * Set to true if you don't want SSL cert validation.
// * @param skipSSLCertValidation true if SSL cert validation should be skipped
// */
// public void setSkipSSLValidation(boolean skipSSLCertValidation) {
// this.skipSSLValidation = skipSSLCertValidation;
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.MapType;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import uk.co.szmg.grafana.GrafanaEndpoint;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map; | package uk.co.szmg.grafana.stores;
/*-
* #%L
* grafana-dashboard-generator-cli
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
/**
* Example in test/resources/test-endpoints.yaml
*/
public class GrafanaEndpointParser {
private ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/GrafanaEndpoint.java
// public class GrafanaEndpoint {
//
// private String baseUrl;
// private String apiKey;
// private String sessionCookie;
// private boolean skipSSLValidation;
//
// /**
// * Gets Grafana base URL.
// * @return base URL
// */
// public String getBaseUrl() {
// return baseUrl;
// }
//
// /**
// * Sets Grafana base URL.
// * @param baseUrl Grafana base URL
// */
// public void setBaseUrl(String baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// /**
// * Gets API key.
// * @return API key
// */
// public String getApiKey() {
// return apiKey;
// }
//
// /**
// * True if SSL cert check should be forced to pass.
// * @return value of skipSSLValidation
// */
// public boolean isSkipSSLValidation() {
// return skipSSLValidation;
// }
//
// /**
// * Sets API gey.
// *
// * http://docs.grafana.org/http_api/auth/
// *
// * You need either this or the sessionCookie for authentication.
// *
// * @param apiKey API key
// */
// public void setApiKey(String apiKey) {
// this.apiKey = apiKey;
// }
//
// /**
// * Gets session cookie.
// * @return session cookie
// */
// public String getSessionCookie() {
// return sessionCookie;
// }
//
// /**
// * Sets session cookie.
// *
// * To get the value log in and copy the value of the "grafana_sess" cookie.
// *
// * You need either this or the apiKey for authentication.
// *
// * @param sessionCookie session cookie
// */
// public void setSessionCookie(String sessionCookie) {
// this.sessionCookie = sessionCookie;
// }
//
// /**
// * Set to true if you don't want SSL cert validation.
// * @param skipSSLCertValidation true if SSL cert validation should be skipped
// */
// public void setSkipSSLValidation(boolean skipSSLCertValidation) {
// this.skipSSLValidation = skipSSLCertValidation;
// }
// }
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/stores/GrafanaEndpointParser.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.MapType;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import uk.co.szmg.grafana.GrafanaEndpoint;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;
package uk.co.szmg.grafana.stores;
/*-
* #%L
* grafana-dashboard-generator-cli
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
/**
* Example in test/resources/test-endpoints.yaml
*/
public class GrafanaEndpointParser {
private ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); | private MapType mapOfStringAndEndpointType = mapper.getTypeFactory().constructMapType(LinkedHashMap.class, String.class, GrafanaEndpoint.class); |
szmg/grafana-dashboard-generator-java | grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/ManyDashboards.java | // Path: grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/Utils.java
// public static Dashboard createSimpleDashboard(String title, Class<?> clazz) {
// return newDashboard()
// .withTitle(title)
// .addRow(newRow()
// .addPanel(newText()
// .withSpan(12).withContent("This was created by " + clazz.getSimpleName())))
// .addRow(newRow()
// .withHeight("95px")
// .addPanel(newText()
// .withSpan(12).withContent("Selected env: $env")))
// .withAnnotations(newAnnotationList()
// .addList(newAlertAnnotation()
// .withName("alert")
// .withLimit(300)
// .withEnable(true))
// .addList(newGraphiteAnnotation()
// .withName("deployment")
// .withDatasource("graphite")
// .withTarget("app.deployment")
// .withIconColor("green")))
// .withTemplating(newTemplateList()
// .addList(newTemplate()
// .withName("env")
// .withLabel("Environment")
// .withType("custom")
// .withQuery("staging,canary,production,perf")
// // options have to be added... templating support should be revised...
// .addOption(newTemplateOption().withValue("staging").withText("staging"))
// .addOption(newTemplateOption().withValue("production").withText("production"))
// .withCurrent(new SelectedTemplate("staging", "staging"))));
// }
| import uk.co.szmg.grafana.domain.Dashboard;
import static uk.co.szmg.grafana.example.dashboards.Utils.createSimpleDashboard;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; | package uk.co.szmg.grafana.example.dashboards;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
@Configuration
public class ManyDashboards {
@Bean
public Dashboard oneDashboard() { | // Path: grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/Utils.java
// public static Dashboard createSimpleDashboard(String title, Class<?> clazz) {
// return newDashboard()
// .withTitle(title)
// .addRow(newRow()
// .addPanel(newText()
// .withSpan(12).withContent("This was created by " + clazz.getSimpleName())))
// .addRow(newRow()
// .withHeight("95px")
// .addPanel(newText()
// .withSpan(12).withContent("Selected env: $env")))
// .withAnnotations(newAnnotationList()
// .addList(newAlertAnnotation()
// .withName("alert")
// .withLimit(300)
// .withEnable(true))
// .addList(newGraphiteAnnotation()
// .withName("deployment")
// .withDatasource("graphite")
// .withTarget("app.deployment")
// .withIconColor("green")))
// .withTemplating(newTemplateList()
// .addList(newTemplate()
// .withName("env")
// .withLabel("Environment")
// .withType("custom")
// .withQuery("staging,canary,production,perf")
// // options have to be added... templating support should be revised...
// .addOption(newTemplateOption().withValue("staging").withText("staging"))
// .addOption(newTemplateOption().withValue("production").withText("production"))
// .withCurrent(new SelectedTemplate("staging", "staging"))));
// }
// Path: grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/ManyDashboards.java
import uk.co.szmg.grafana.domain.Dashboard;
import static uk.co.szmg.grafana.example.dashboards.Utils.createSimpleDashboard;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
package uk.co.szmg.grafana.example.dashboards;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
@Configuration
public class ManyDashboards {
@Bean
public Dashboard oneDashboard() { | return createSimpleDashboard("Some fancy dashboard", ManyDashboards.class); |
szmg/grafana-dashboard-generator-java | grafana-dashboard-generator-cli/src/test/java/uk/co/szmg/grafana/cli/DashboardStoreTest.java | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/stores/DashboardStore.java
// public class DashboardStore {
//
// private String rootPackage;
//
// private List<Dashboard> dashboards;
//
// /**
// * Creates a DashboardStore.
// * @param rootPackage root package of the annotation based spring context to be searched
// */
// public DashboardStore(String rootPackage) {
// this.rootPackage = rootPackage;
// }
//
// /**
// * Loads dashboards.
// *
// * <p>This will create the Spring context and look for
// * {@link DashboardFactory} and {@link Dashboard} implementations.
// */
// public void load() {
// List<Dashboard> dashboards = new ArrayList<>();
// ApplicationContext applicationContext = new AnnotationConfigApplicationContext(rootPackage);
// Map<String, DashboardFactory> factories = applicationContext.getBeansOfType(DashboardFactory.class);
//
// for (DashboardFactory dashboardFactory : factories.values()) {
// dashboards.addAll(dashboardFactory.create());
// }
//
// Map<String, Dashboard> dashboardBeans = applicationContext.getBeansOfType(Dashboard.class);
// dashboards.addAll(dashboardBeans.values());
//
// this.dashboards = unmodifiableList(dashboards);
// }
//
// /**
// * Gets a list of dashboard titles that presents
// * more than once among the dashboards.
// *
// * <p>Grafana treats them as equal, so there is no point
// * uploading them twice.
// *
// * @return list of dashboard titles
// */
// public Collection<String> getDuplicates() {
// Set<String> all = new HashSet<>();
// Set<String> dupes = new HashSet<>();
//
// for (Dashboard dashboard : dashboards) {
// String title = dashboard.getTitle();
// if (all.contains(title)) {
// dupes.add(title);
// } else {
// all.add(title);
// }
// }
//
// return dupes;
// }
//
// /**
// * Gets an error message with the list of duplicated dashboards if any.
// * @return an error message if there are duplicates, otherwise {@code Optional.empty()}
// */
// public Optional<String> getDuplicatesErrorMessage() {
// Collection<String> duplicates = getDuplicates();
// String message = null;
// if (!duplicates.isEmpty()) {
// message = String.format("%d duplicates found among dashboards:", duplicates.size());
//
// message += duplicates.stream().collect(Collectors.joining(", "));
// }
// return Optional.ofNullable(message);
// }
//
// /**
// * Gets all dashboards.
// * @return list of dashboards
// */
// public List<Dashboard> getDashboards() {
// return dashboards;
// }
// }
| import org.junit.Test;
import uk.co.szmg.grafana.stores.DashboardStore;
import uk.co.szmg.grafana.domain.Dashboard;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; | package uk.co.szmg.grafana.cli;
/*-
* #%L
* grafana-dashboard-generator-cli
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
public class DashboardStoreTest {
@Test
public void shouldFindDashboards() { | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/stores/DashboardStore.java
// public class DashboardStore {
//
// private String rootPackage;
//
// private List<Dashboard> dashboards;
//
// /**
// * Creates a DashboardStore.
// * @param rootPackage root package of the annotation based spring context to be searched
// */
// public DashboardStore(String rootPackage) {
// this.rootPackage = rootPackage;
// }
//
// /**
// * Loads dashboards.
// *
// * <p>This will create the Spring context and look for
// * {@link DashboardFactory} and {@link Dashboard} implementations.
// */
// public void load() {
// List<Dashboard> dashboards = new ArrayList<>();
// ApplicationContext applicationContext = new AnnotationConfigApplicationContext(rootPackage);
// Map<String, DashboardFactory> factories = applicationContext.getBeansOfType(DashboardFactory.class);
//
// for (DashboardFactory dashboardFactory : factories.values()) {
// dashboards.addAll(dashboardFactory.create());
// }
//
// Map<String, Dashboard> dashboardBeans = applicationContext.getBeansOfType(Dashboard.class);
// dashboards.addAll(dashboardBeans.values());
//
// this.dashboards = unmodifiableList(dashboards);
// }
//
// /**
// * Gets a list of dashboard titles that presents
// * more than once among the dashboards.
// *
// * <p>Grafana treats them as equal, so there is no point
// * uploading them twice.
// *
// * @return list of dashboard titles
// */
// public Collection<String> getDuplicates() {
// Set<String> all = new HashSet<>();
// Set<String> dupes = new HashSet<>();
//
// for (Dashboard dashboard : dashboards) {
// String title = dashboard.getTitle();
// if (all.contains(title)) {
// dupes.add(title);
// } else {
// all.add(title);
// }
// }
//
// return dupes;
// }
//
// /**
// * Gets an error message with the list of duplicated dashboards if any.
// * @return an error message if there are duplicates, otherwise {@code Optional.empty()}
// */
// public Optional<String> getDuplicatesErrorMessage() {
// Collection<String> duplicates = getDuplicates();
// String message = null;
// if (!duplicates.isEmpty()) {
// message = String.format("%d duplicates found among dashboards:", duplicates.size());
//
// message += duplicates.stream().collect(Collectors.joining(", "));
// }
// return Optional.ofNullable(message);
// }
//
// /**
// * Gets all dashboards.
// * @return list of dashboards
// */
// public List<Dashboard> getDashboards() {
// return dashboards;
// }
// }
// Path: grafana-dashboard-generator-cli/src/test/java/uk/co/szmg/grafana/cli/DashboardStoreTest.java
import org.junit.Test;
import uk.co.szmg.grafana.stores.DashboardStore;
import uk.co.szmg.grafana.domain.Dashboard;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
package uk.co.szmg.grafana.cli;
/*-
* #%L
* grafana-dashboard-generator-cli
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
public class DashboardStoreTest {
@Test
public void shouldFindDashboards() { | DashboardStore store = new DashboardStore("uk.co.szmg.grafana.cli.example"); |
szmg/grafana-dashboard-generator-java | grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/Main.java | // Path: grafana-dashboard-generator-cli/src/main/java/uk/co/szmg/grafana/cli/DashboardGeneratorApplication.java
// public class DashboardGeneratorApplication {
//
// private String rootPackage;
//
// public DashboardGeneratorApplication(String rootPackage) {
// this.rootPackage = rootPackage;
// }
//
// public int main(String[] args) throws IOException {
// try {
// return safeMain(args);
// } catch (ExitPlease ex) {
// return ex.getReturnCode();
// }
// }
//
// private int safeMain(String[] args) throws IOException, ExitPlease {
// AnsiConsole.systemInstall();
//
// // welcome
// System.out.println(ansi().render("\n@|blue Welcome to Grafana Dashboard Builder|@\n"));
//
// UploaderConfig config = new UploaderConfig();
//
// CommandLineArgs commandLineArgs = new CommandLineArgs();
// commandLineArgs.parse(args, config);
// initStores(config);
// commandLineArgs.apply(config);
// loadDefaults(config);
//
// Interaction.askUserForDetails(config);
//
// if (config.getEndpoint().isPresent()) {
// upload(config);
// } else {
// writeToFile(config);
// }
//
// return 0;
// }
//
// private void initStores(UploaderConfig config) {
// // dashboard
// config.setDashboardStore(new DashboardStore(rootPackage));
// DashboardStore dashboardStore = config.getDashboardStore();
// dashboardStore.load();
//
// // check duplicates
// dashboardStore.getDuplicatesErrorMessage().ifPresent(msg -> {
// System.err.println(msg);
// throw new ExitPlease(-1);
// });
//
// // endpoint
// GrafanaEndpointStore endpointStore = config.getEndpointStore();
// if (endpointStore == null) {
// endpointStore = new ClasspathGrafanaEndpointStore("/endpoints.yaml");
// config.setEndpointStore(endpointStore);
// }
//
// try {
// endpointStore.load();
// } catch (IOException e) {
// System.err.println("Could not load endpoint store; " + e.getMessage());
// throw new ExitPlease(-2);
// }
//
// }
//
// private void loadDefaults(UploaderConfig config) {
// List<Dashboard> dashboards = config.getDashboardStore().getDashboards();
// if (config.getDashboards() == null && dashboards.size() == 1) {
// config.setDashboards(dashboards);
// }
//
// if (config.getEndpointStore().getEndpoints().isEmpty()) {
// config.setEndpoint(Optional.empty());
// }
//
// if (config.getOutputDirectory() == null) {
// config.setOutputDirectory(new File("./output"));
// }
//
// if (config.isBatchMode() && config.getOverwrite() == null) {
// config.setOverwrite(false);
// }
// }
//
// private void upload(UploaderConfig config) {
// boolean overwrite = config.getOverwrite();
// DashboardUploader dashboardUploader = new DashboardUploader(config.getEndpoint().get());
// for (Dashboard dashboard : config.getDashboards()) {
// System.out.printf("%s: ", dashboard.getTitle());
//
// try {
// dashboardUploader.upload(dashboard, overwrite);
// System.out.println(ansi().render("@|green done|@"));
// } catch (RuntimeException e) {
// boolean alreadyExists = false;
// if (e.getCause() instanceof GrafanaClient.UnexpectedGrafanaResponseException) {
// GrafanaClient.UnexpectedGrafanaResponseException ex = (GrafanaClient.UnexpectedGrafanaResponseException) e.getCause();
// alreadyExists = ex.getResponseCode() == 412;
// }
//
// if (alreadyExists && !overwrite) {
// System.out.println(ansi().render("@|red already exists|@"));
// } else {
// throw e;
// }
// }
// }
// }
//
// private void writeToFile(UploaderConfig config) throws IOException {
// DashboardSerializer dashboardSerializer = new DashboardSerializer();
// File outputDirectory = config.getOutputDirectory();
// outputDirectory.mkdirs();
// for (Dashboard dashboard : config.getDashboards()) {
// System.out.printf("%s: ", dashboard.getTitle());
//
// File f = new File(outputDirectory, filenameFor(dashboard));
// if (f.exists() && !config.getOverwrite()) {
// System.out.println(ansi().render("@|red already exists|@"));
// } else {
// try (FileOutputStream stream = new FileOutputStream(f)) {
// dashboardSerializer.write(dashboard, stream);
// }
// System.out.println(ansi().render("@|green done|@"));
// }
//
// }
//
// }
//
// private String filenameFor(Dashboard dashboard) {
// return dashboard.getTitle().replaceAll("[\\s:/\\\\]+", "-") + ".json";
// }
//
// }
| import java.io.IOException;
import uk.co.szmg.grafana.cli.DashboardGeneratorApplication; | package uk.co.szmg.grafana.example;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
public class Main {
public static void main(String[] args) throws IOException { | // Path: grafana-dashboard-generator-cli/src/main/java/uk/co/szmg/grafana/cli/DashboardGeneratorApplication.java
// public class DashboardGeneratorApplication {
//
// private String rootPackage;
//
// public DashboardGeneratorApplication(String rootPackage) {
// this.rootPackage = rootPackage;
// }
//
// public int main(String[] args) throws IOException {
// try {
// return safeMain(args);
// } catch (ExitPlease ex) {
// return ex.getReturnCode();
// }
// }
//
// private int safeMain(String[] args) throws IOException, ExitPlease {
// AnsiConsole.systemInstall();
//
// // welcome
// System.out.println(ansi().render("\n@|blue Welcome to Grafana Dashboard Builder|@\n"));
//
// UploaderConfig config = new UploaderConfig();
//
// CommandLineArgs commandLineArgs = new CommandLineArgs();
// commandLineArgs.parse(args, config);
// initStores(config);
// commandLineArgs.apply(config);
// loadDefaults(config);
//
// Interaction.askUserForDetails(config);
//
// if (config.getEndpoint().isPresent()) {
// upload(config);
// } else {
// writeToFile(config);
// }
//
// return 0;
// }
//
// private void initStores(UploaderConfig config) {
// // dashboard
// config.setDashboardStore(new DashboardStore(rootPackage));
// DashboardStore dashboardStore = config.getDashboardStore();
// dashboardStore.load();
//
// // check duplicates
// dashboardStore.getDuplicatesErrorMessage().ifPresent(msg -> {
// System.err.println(msg);
// throw new ExitPlease(-1);
// });
//
// // endpoint
// GrafanaEndpointStore endpointStore = config.getEndpointStore();
// if (endpointStore == null) {
// endpointStore = new ClasspathGrafanaEndpointStore("/endpoints.yaml");
// config.setEndpointStore(endpointStore);
// }
//
// try {
// endpointStore.load();
// } catch (IOException e) {
// System.err.println("Could not load endpoint store; " + e.getMessage());
// throw new ExitPlease(-2);
// }
//
// }
//
// private void loadDefaults(UploaderConfig config) {
// List<Dashboard> dashboards = config.getDashboardStore().getDashboards();
// if (config.getDashboards() == null && dashboards.size() == 1) {
// config.setDashboards(dashboards);
// }
//
// if (config.getEndpointStore().getEndpoints().isEmpty()) {
// config.setEndpoint(Optional.empty());
// }
//
// if (config.getOutputDirectory() == null) {
// config.setOutputDirectory(new File("./output"));
// }
//
// if (config.isBatchMode() && config.getOverwrite() == null) {
// config.setOverwrite(false);
// }
// }
//
// private void upload(UploaderConfig config) {
// boolean overwrite = config.getOverwrite();
// DashboardUploader dashboardUploader = new DashboardUploader(config.getEndpoint().get());
// for (Dashboard dashboard : config.getDashboards()) {
// System.out.printf("%s: ", dashboard.getTitle());
//
// try {
// dashboardUploader.upload(dashboard, overwrite);
// System.out.println(ansi().render("@|green done|@"));
// } catch (RuntimeException e) {
// boolean alreadyExists = false;
// if (e.getCause() instanceof GrafanaClient.UnexpectedGrafanaResponseException) {
// GrafanaClient.UnexpectedGrafanaResponseException ex = (GrafanaClient.UnexpectedGrafanaResponseException) e.getCause();
// alreadyExists = ex.getResponseCode() == 412;
// }
//
// if (alreadyExists && !overwrite) {
// System.out.println(ansi().render("@|red already exists|@"));
// } else {
// throw e;
// }
// }
// }
// }
//
// private void writeToFile(UploaderConfig config) throws IOException {
// DashboardSerializer dashboardSerializer = new DashboardSerializer();
// File outputDirectory = config.getOutputDirectory();
// outputDirectory.mkdirs();
// for (Dashboard dashboard : config.getDashboards()) {
// System.out.printf("%s: ", dashboard.getTitle());
//
// File f = new File(outputDirectory, filenameFor(dashboard));
// if (f.exists() && !config.getOverwrite()) {
// System.out.println(ansi().render("@|red already exists|@"));
// } else {
// try (FileOutputStream stream = new FileOutputStream(f)) {
// dashboardSerializer.write(dashboard, stream);
// }
// System.out.println(ansi().render("@|green done|@"));
// }
//
// }
//
// }
//
// private String filenameFor(Dashboard dashboard) {
// return dashboard.getTitle().replaceAll("[\\s:/\\\\]+", "-") + ".json";
// }
//
// }
// Path: grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/Main.java
import java.io.IOException;
import uk.co.szmg.grafana.cli.DashboardGeneratorApplication;
package uk.co.szmg.grafana.example;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
public class Main {
public static void main(String[] args) throws IOException { | new DashboardGeneratorApplication("uk.co.szmg.grafana.example.dashboards").main(args); |
szmg/grafana-dashboard-generator-java | grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/stores/DashboardStore.java | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/DashboardFactory.java
// public interface DashboardFactory {
//
// /**
// * Creates dashboards.
// * @return a list of dashboards created, should not be {@code null}
// */
// List<Dashboard> create();
//
// }
| import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static java.util.Collections.unmodifiableList;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import uk.co.szmg.grafana.DashboardFactory;
import uk.co.szmg.grafana.domain.Dashboard;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map; | package uk.co.szmg.grafana.stores;
/*-
* #%L
* grafana-dashboard-generator-cli
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
/**
* Loads and provides dashboards.
*
* <p>First, an annotation based Spring context is built
* in {@code rootPackage}. Then every {@link DashboardFactory}
* beans are looked up and invoked to create dashboards.
* Finally, all {@link Dashboard} beans are read.
*
* <p>This class can also return the duplicated dashboards.
* Two dashboards are duplicated if their titles are equal.
*/
public class DashboardStore {
private String rootPackage;
private List<Dashboard> dashboards;
/**
* Creates a DashboardStore.
* @param rootPackage root package of the annotation based spring context to be searched
*/
public DashboardStore(String rootPackage) {
this.rootPackage = rootPackage;
}
/**
* Loads dashboards.
*
* <p>This will create the Spring context and look for
* {@link DashboardFactory} and {@link Dashboard} implementations.
*/
public void load() {
List<Dashboard> dashboards = new ArrayList<>();
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(rootPackage); | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/DashboardFactory.java
// public interface DashboardFactory {
//
// /**
// * Creates dashboards.
// * @return a list of dashboards created, should not be {@code null}
// */
// List<Dashboard> create();
//
// }
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/stores/DashboardStore.java
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static java.util.Collections.unmodifiableList;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import uk.co.szmg.grafana.DashboardFactory;
import uk.co.szmg.grafana.domain.Dashboard;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
package uk.co.szmg.grafana.stores;
/*-
* #%L
* grafana-dashboard-generator-cli
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
/**
* Loads and provides dashboards.
*
* <p>First, an annotation based Spring context is built
* in {@code rootPackage}. Then every {@link DashboardFactory}
* beans are looked up and invoked to create dashboards.
* Finally, all {@link Dashboard} beans are read.
*
* <p>This class can also return the duplicated dashboards.
* Two dashboards are duplicated if their titles are equal.
*/
public class DashboardStore {
private String rootPackage;
private List<Dashboard> dashboards;
/**
* Creates a DashboardStore.
* @param rootPackage root package of the annotation based spring context to be searched
*/
public DashboardStore(String rootPackage) {
this.rootPackage = rootPackage;
}
/**
* Loads dashboards.
*
* <p>This will create the Spring context and look for
* {@link DashboardFactory} and {@link Dashboard} implementations.
*/
public void load() {
List<Dashboard> dashboards = new ArrayList<>();
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(rootPackage); | Map<String, DashboardFactory> factories = applicationContext.getBeansOfType(DashboardFactory.class); |
szmg/grafana-dashboard-generator-java | grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/complex/MultiEnvExampleDashboards.java | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/DashboardFactory.java
// public interface DashboardFactory {
//
// /**
// * Creates dashboards.
// * @return a list of dashboards created, should not be {@code null}
// */
// List<Dashboard> create();
//
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/ColorTheme.java
// public class ColorTheme {
//
// /**
// * A simple, red-yellow-green and white theme.
// */
// public static final ColorTheme RED_YELLOW_GREEN = new ColorTheme(
// "white",
// "rgba(50, 172, 45, 0.97)",
// "rgba(237, 129, 40, 0.89)",
// "rgba(245, 54, 54, 0.9)");
//
// private String neutral;
// private String healthy;
// private String warning;
// private String error;
//
// /**
// * Constructor.
// *
// * @param neutral neutral color for texts that are neither good nor bad; e.g., white
// * @param healthy color to mark healthy things, e.g., green
// * @param warning color used for the middle part of the thresholds, e.g., yellow
// * @param error color that marks an error, e.g., red
// */
// public ColorTheme(String neutral, String healthy, String warning, String error) {
// this.neutral = neutral;
// this.healthy = healthy;
// this.warning = warning;
// this.error = error;
// }
//
// /**
// * Gets neutral color.
// * @return neutral color
// */
// public String getNeutral() {
// return neutral;
// }
//
// /**
// * Gets healthy color.
// * @return healthy color
// */
// public String getHealthy() {
// return healthy;
// }
//
// /**
// * Gets warning color.
// * @return warning color
// */
// public String getWarning() {
// return warning;
// }
//
// /**
// * Gets error color.
// * @return error color
// */
// public String getError() {
// return error;
// }
//
// /**
// * Gets a color configuration used in singlestat for when low value is good,
// * e.g., number of errors.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenLowIsHealthy() {
// return new Colors(healthy, warning, error);
// }
//
// /**
// * Gets a color configuration used in singlestat for when high value is good,
// * e.g., number of instances alive.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenHighIsHealthy() {
// return new Colors(error, warning, healthy);
// }
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text placeholder(int span) {
// return newText()
// .withContent("")
// .withTransparent(true)
// .withSpan(span);
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Row thinRow() {
// return newRow().withHeight("95px");
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text title(String title) {
// return newText()
// .withContent("<div class=\"text-center dashboard-header\"><span>" + title + "</span></div>")
// .withMode("html")
// .withTransparent(true);
// }
| import static uk.co.szmg.grafana.dashboard.StaticFactories.placeholder;
import static uk.co.szmg.grafana.dashboard.StaticFactories.thinRow;
import static uk.co.szmg.grafana.dashboard.StaticFactories.title;
import static uk.co.szmg.grafana.domain.DomainFactories.newDashboard;
import static uk.co.szmg.grafana.domain.DomainFactories.newRow;
import uk.co.szmg.grafana.DashboardFactory;
import uk.co.szmg.grafana.dashboard.ColorTheme;
import uk.co.szmg.grafana.domain.Dashboard;
import uk.co.szmg.grafana.domain.Row;
import uk.co.szmg.grafana.domain.SingleStat;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List; | package uk.co.szmg.grafana.example.dashboards.complex;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
@Named
public class MultiEnvExampleDashboards implements DashboardFactory {
private SampleAppEnvironment environments[] =
new SampleAppEnvironment[]{
new SampleAppEnvironment("Staging", "graphite", "MYAPP.stage", 2),
new SampleAppEnvironment("Production", "aws.graphite", "MYAPP.prod", 10)
};
| // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/DashboardFactory.java
// public interface DashboardFactory {
//
// /**
// * Creates dashboards.
// * @return a list of dashboards created, should not be {@code null}
// */
// List<Dashboard> create();
//
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/ColorTheme.java
// public class ColorTheme {
//
// /**
// * A simple, red-yellow-green and white theme.
// */
// public static final ColorTheme RED_YELLOW_GREEN = new ColorTheme(
// "white",
// "rgba(50, 172, 45, 0.97)",
// "rgba(237, 129, 40, 0.89)",
// "rgba(245, 54, 54, 0.9)");
//
// private String neutral;
// private String healthy;
// private String warning;
// private String error;
//
// /**
// * Constructor.
// *
// * @param neutral neutral color for texts that are neither good nor bad; e.g., white
// * @param healthy color to mark healthy things, e.g., green
// * @param warning color used for the middle part of the thresholds, e.g., yellow
// * @param error color that marks an error, e.g., red
// */
// public ColorTheme(String neutral, String healthy, String warning, String error) {
// this.neutral = neutral;
// this.healthy = healthy;
// this.warning = warning;
// this.error = error;
// }
//
// /**
// * Gets neutral color.
// * @return neutral color
// */
// public String getNeutral() {
// return neutral;
// }
//
// /**
// * Gets healthy color.
// * @return healthy color
// */
// public String getHealthy() {
// return healthy;
// }
//
// /**
// * Gets warning color.
// * @return warning color
// */
// public String getWarning() {
// return warning;
// }
//
// /**
// * Gets error color.
// * @return error color
// */
// public String getError() {
// return error;
// }
//
// /**
// * Gets a color configuration used in singlestat for when low value is good,
// * e.g., number of errors.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenLowIsHealthy() {
// return new Colors(healthy, warning, error);
// }
//
// /**
// * Gets a color configuration used in singlestat for when high value is good,
// * e.g., number of instances alive.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenHighIsHealthy() {
// return new Colors(error, warning, healthy);
// }
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text placeholder(int span) {
// return newText()
// .withContent("")
// .withTransparent(true)
// .withSpan(span);
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Row thinRow() {
// return newRow().withHeight("95px");
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text title(String title) {
// return newText()
// .withContent("<div class=\"text-center dashboard-header\"><span>" + title + "</span></div>")
// .withMode("html")
// .withTransparent(true);
// }
// Path: grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/complex/MultiEnvExampleDashboards.java
import static uk.co.szmg.grafana.dashboard.StaticFactories.placeholder;
import static uk.co.szmg.grafana.dashboard.StaticFactories.thinRow;
import static uk.co.szmg.grafana.dashboard.StaticFactories.title;
import static uk.co.szmg.grafana.domain.DomainFactories.newDashboard;
import static uk.co.szmg.grafana.domain.DomainFactories.newRow;
import uk.co.szmg.grafana.DashboardFactory;
import uk.co.szmg.grafana.dashboard.ColorTheme;
import uk.co.szmg.grafana.domain.Dashboard;
import uk.co.szmg.grafana.domain.Row;
import uk.co.szmg.grafana.domain.SingleStat;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;
package uk.co.szmg.grafana.example.dashboards.complex;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
@Named
public class MultiEnvExampleDashboards implements DashboardFactory {
private SampleAppEnvironment environments[] =
new SampleAppEnvironment[]{
new SampleAppEnvironment("Staging", "graphite", "MYAPP.stage", 2),
new SampleAppEnvironment("Production", "aws.graphite", "MYAPP.prod", 10)
};
| private ColorTheme colorTheme = ColorTheme.RED_YELLOW_GREEN; |
szmg/grafana-dashboard-generator-java | grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/complex/MultiEnvExampleDashboards.java | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/DashboardFactory.java
// public interface DashboardFactory {
//
// /**
// * Creates dashboards.
// * @return a list of dashboards created, should not be {@code null}
// */
// List<Dashboard> create();
//
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/ColorTheme.java
// public class ColorTheme {
//
// /**
// * A simple, red-yellow-green and white theme.
// */
// public static final ColorTheme RED_YELLOW_GREEN = new ColorTheme(
// "white",
// "rgba(50, 172, 45, 0.97)",
// "rgba(237, 129, 40, 0.89)",
// "rgba(245, 54, 54, 0.9)");
//
// private String neutral;
// private String healthy;
// private String warning;
// private String error;
//
// /**
// * Constructor.
// *
// * @param neutral neutral color for texts that are neither good nor bad; e.g., white
// * @param healthy color to mark healthy things, e.g., green
// * @param warning color used for the middle part of the thresholds, e.g., yellow
// * @param error color that marks an error, e.g., red
// */
// public ColorTheme(String neutral, String healthy, String warning, String error) {
// this.neutral = neutral;
// this.healthy = healthy;
// this.warning = warning;
// this.error = error;
// }
//
// /**
// * Gets neutral color.
// * @return neutral color
// */
// public String getNeutral() {
// return neutral;
// }
//
// /**
// * Gets healthy color.
// * @return healthy color
// */
// public String getHealthy() {
// return healthy;
// }
//
// /**
// * Gets warning color.
// * @return warning color
// */
// public String getWarning() {
// return warning;
// }
//
// /**
// * Gets error color.
// * @return error color
// */
// public String getError() {
// return error;
// }
//
// /**
// * Gets a color configuration used in singlestat for when low value is good,
// * e.g., number of errors.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenLowIsHealthy() {
// return new Colors(healthy, warning, error);
// }
//
// /**
// * Gets a color configuration used in singlestat for when high value is good,
// * e.g., number of instances alive.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenHighIsHealthy() {
// return new Colors(error, warning, healthy);
// }
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text placeholder(int span) {
// return newText()
// .withContent("")
// .withTransparent(true)
// .withSpan(span);
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Row thinRow() {
// return newRow().withHeight("95px");
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text title(String title) {
// return newText()
// .withContent("<div class=\"text-center dashboard-header\"><span>" + title + "</span></div>")
// .withMode("html")
// .withTransparent(true);
// }
| import static uk.co.szmg.grafana.dashboard.StaticFactories.placeholder;
import static uk.co.szmg.grafana.dashboard.StaticFactories.thinRow;
import static uk.co.szmg.grafana.dashboard.StaticFactories.title;
import static uk.co.szmg.grafana.domain.DomainFactories.newDashboard;
import static uk.co.szmg.grafana.domain.DomainFactories.newRow;
import uk.co.szmg.grafana.DashboardFactory;
import uk.co.szmg.grafana.dashboard.ColorTheme;
import uk.co.szmg.grafana.domain.Dashboard;
import uk.co.szmg.grafana.domain.Row;
import uk.co.szmg.grafana.domain.SingleStat;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List; | package uk.co.szmg.grafana.example.dashboards.complex;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
@Named
public class MultiEnvExampleDashboards implements DashboardFactory {
private SampleAppEnvironment environments[] =
new SampleAppEnvironment[]{
new SampleAppEnvironment("Staging", "graphite", "MYAPP.stage", 2),
new SampleAppEnvironment("Production", "aws.graphite", "MYAPP.prod", 10)
};
private ColorTheme colorTheme = ColorTheme.RED_YELLOW_GREEN;
@Override
public List<Dashboard> create() {
List<Dashboard> dashboards = new ArrayList<>();
for (SampleAppEnvironment environment : environments) {
dashboards.add(create(environment));
}
return dashboards;
}
private Dashboard create(SampleAppEnvironment environment) {
XYComponentFactory factory = new XYComponentFactory(environment, colorTheme);
// might be better off in a factory method
SingleStat e500 = factory
.errorCounter("sumSeries({ROOT}.instrumentedFilter.serverErrors.count)", true)
.withTitle("E500 count");
// row definitions | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/DashboardFactory.java
// public interface DashboardFactory {
//
// /**
// * Creates dashboards.
// * @return a list of dashboards created, should not be {@code null}
// */
// List<Dashboard> create();
//
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/ColorTheme.java
// public class ColorTheme {
//
// /**
// * A simple, red-yellow-green and white theme.
// */
// public static final ColorTheme RED_YELLOW_GREEN = new ColorTheme(
// "white",
// "rgba(50, 172, 45, 0.97)",
// "rgba(237, 129, 40, 0.89)",
// "rgba(245, 54, 54, 0.9)");
//
// private String neutral;
// private String healthy;
// private String warning;
// private String error;
//
// /**
// * Constructor.
// *
// * @param neutral neutral color for texts that are neither good nor bad; e.g., white
// * @param healthy color to mark healthy things, e.g., green
// * @param warning color used for the middle part of the thresholds, e.g., yellow
// * @param error color that marks an error, e.g., red
// */
// public ColorTheme(String neutral, String healthy, String warning, String error) {
// this.neutral = neutral;
// this.healthy = healthy;
// this.warning = warning;
// this.error = error;
// }
//
// /**
// * Gets neutral color.
// * @return neutral color
// */
// public String getNeutral() {
// return neutral;
// }
//
// /**
// * Gets healthy color.
// * @return healthy color
// */
// public String getHealthy() {
// return healthy;
// }
//
// /**
// * Gets warning color.
// * @return warning color
// */
// public String getWarning() {
// return warning;
// }
//
// /**
// * Gets error color.
// * @return error color
// */
// public String getError() {
// return error;
// }
//
// /**
// * Gets a color configuration used in singlestat for when low value is good,
// * e.g., number of errors.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenLowIsHealthy() {
// return new Colors(healthy, warning, error);
// }
//
// /**
// * Gets a color configuration used in singlestat for when high value is good,
// * e.g., number of instances alive.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenHighIsHealthy() {
// return new Colors(error, warning, healthy);
// }
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text placeholder(int span) {
// return newText()
// .withContent("")
// .withTransparent(true)
// .withSpan(span);
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Row thinRow() {
// return newRow().withHeight("95px");
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text title(String title) {
// return newText()
// .withContent("<div class=\"text-center dashboard-header\"><span>" + title + "</span></div>")
// .withMode("html")
// .withTransparent(true);
// }
// Path: grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/complex/MultiEnvExampleDashboards.java
import static uk.co.szmg.grafana.dashboard.StaticFactories.placeholder;
import static uk.co.szmg.grafana.dashboard.StaticFactories.thinRow;
import static uk.co.szmg.grafana.dashboard.StaticFactories.title;
import static uk.co.szmg.grafana.domain.DomainFactories.newDashboard;
import static uk.co.szmg.grafana.domain.DomainFactories.newRow;
import uk.co.szmg.grafana.DashboardFactory;
import uk.co.szmg.grafana.dashboard.ColorTheme;
import uk.co.szmg.grafana.domain.Dashboard;
import uk.co.szmg.grafana.domain.Row;
import uk.co.szmg.grafana.domain.SingleStat;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;
package uk.co.szmg.grafana.example.dashboards.complex;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
@Named
public class MultiEnvExampleDashboards implements DashboardFactory {
private SampleAppEnvironment environments[] =
new SampleAppEnvironment[]{
new SampleAppEnvironment("Staging", "graphite", "MYAPP.stage", 2),
new SampleAppEnvironment("Production", "aws.graphite", "MYAPP.prod", 10)
};
private ColorTheme colorTheme = ColorTheme.RED_YELLOW_GREEN;
@Override
public List<Dashboard> create() {
List<Dashboard> dashboards = new ArrayList<>();
for (SampleAppEnvironment environment : environments) {
dashboards.add(create(environment));
}
return dashboards;
}
private Dashboard create(SampleAppEnvironment environment) {
XYComponentFactory factory = new XYComponentFactory(environment, colorTheme);
// might be better off in a factory method
SingleStat e500 = factory
.errorCounter("sumSeries({ROOT}.instrumentedFilter.serverErrors.count)", true)
.withTitle("E500 count");
// row definitions | Row row1 = thinRow() |
szmg/grafana-dashboard-generator-java | grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/complex/MultiEnvExampleDashboards.java | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/DashboardFactory.java
// public interface DashboardFactory {
//
// /**
// * Creates dashboards.
// * @return a list of dashboards created, should not be {@code null}
// */
// List<Dashboard> create();
//
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/ColorTheme.java
// public class ColorTheme {
//
// /**
// * A simple, red-yellow-green and white theme.
// */
// public static final ColorTheme RED_YELLOW_GREEN = new ColorTheme(
// "white",
// "rgba(50, 172, 45, 0.97)",
// "rgba(237, 129, 40, 0.89)",
// "rgba(245, 54, 54, 0.9)");
//
// private String neutral;
// private String healthy;
// private String warning;
// private String error;
//
// /**
// * Constructor.
// *
// * @param neutral neutral color for texts that are neither good nor bad; e.g., white
// * @param healthy color to mark healthy things, e.g., green
// * @param warning color used for the middle part of the thresholds, e.g., yellow
// * @param error color that marks an error, e.g., red
// */
// public ColorTheme(String neutral, String healthy, String warning, String error) {
// this.neutral = neutral;
// this.healthy = healthy;
// this.warning = warning;
// this.error = error;
// }
//
// /**
// * Gets neutral color.
// * @return neutral color
// */
// public String getNeutral() {
// return neutral;
// }
//
// /**
// * Gets healthy color.
// * @return healthy color
// */
// public String getHealthy() {
// return healthy;
// }
//
// /**
// * Gets warning color.
// * @return warning color
// */
// public String getWarning() {
// return warning;
// }
//
// /**
// * Gets error color.
// * @return error color
// */
// public String getError() {
// return error;
// }
//
// /**
// * Gets a color configuration used in singlestat for when low value is good,
// * e.g., number of errors.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenLowIsHealthy() {
// return new Colors(healthy, warning, error);
// }
//
// /**
// * Gets a color configuration used in singlestat for when high value is good,
// * e.g., number of instances alive.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenHighIsHealthy() {
// return new Colors(error, warning, healthy);
// }
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text placeholder(int span) {
// return newText()
// .withContent("")
// .withTransparent(true)
// .withSpan(span);
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Row thinRow() {
// return newRow().withHeight("95px");
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text title(String title) {
// return newText()
// .withContent("<div class=\"text-center dashboard-header\"><span>" + title + "</span></div>")
// .withMode("html")
// .withTransparent(true);
// }
| import static uk.co.szmg.grafana.dashboard.StaticFactories.placeholder;
import static uk.co.szmg.grafana.dashboard.StaticFactories.thinRow;
import static uk.co.szmg.grafana.dashboard.StaticFactories.title;
import static uk.co.szmg.grafana.domain.DomainFactories.newDashboard;
import static uk.co.szmg.grafana.domain.DomainFactories.newRow;
import uk.co.szmg.grafana.DashboardFactory;
import uk.co.szmg.grafana.dashboard.ColorTheme;
import uk.co.szmg.grafana.domain.Dashboard;
import uk.co.szmg.grafana.domain.Row;
import uk.co.szmg.grafana.domain.SingleStat;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List; | package uk.co.szmg.grafana.example.dashboards.complex;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
@Named
public class MultiEnvExampleDashboards implements DashboardFactory {
private SampleAppEnvironment environments[] =
new SampleAppEnvironment[]{
new SampleAppEnvironment("Staging", "graphite", "MYAPP.stage", 2),
new SampleAppEnvironment("Production", "aws.graphite", "MYAPP.prod", 10)
};
private ColorTheme colorTheme = ColorTheme.RED_YELLOW_GREEN;
@Override
public List<Dashboard> create() {
List<Dashboard> dashboards = new ArrayList<>();
for (SampleAppEnvironment environment : environments) {
dashboards.add(create(environment));
}
return dashboards;
}
private Dashboard create(SampleAppEnvironment environment) {
XYComponentFactory factory = new XYComponentFactory(environment, colorTheme);
// might be better off in a factory method
SingleStat e500 = factory
.errorCounter("sumSeries({ROOT}.instrumentedFilter.serverErrors.count)", true)
.withTitle("E500 count");
// row definitions
Row row1 = thinRow() | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/DashboardFactory.java
// public interface DashboardFactory {
//
// /**
// * Creates dashboards.
// * @return a list of dashboards created, should not be {@code null}
// */
// List<Dashboard> create();
//
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/ColorTheme.java
// public class ColorTheme {
//
// /**
// * A simple, red-yellow-green and white theme.
// */
// public static final ColorTheme RED_YELLOW_GREEN = new ColorTheme(
// "white",
// "rgba(50, 172, 45, 0.97)",
// "rgba(237, 129, 40, 0.89)",
// "rgba(245, 54, 54, 0.9)");
//
// private String neutral;
// private String healthy;
// private String warning;
// private String error;
//
// /**
// * Constructor.
// *
// * @param neutral neutral color for texts that are neither good nor bad; e.g., white
// * @param healthy color to mark healthy things, e.g., green
// * @param warning color used for the middle part of the thresholds, e.g., yellow
// * @param error color that marks an error, e.g., red
// */
// public ColorTheme(String neutral, String healthy, String warning, String error) {
// this.neutral = neutral;
// this.healthy = healthy;
// this.warning = warning;
// this.error = error;
// }
//
// /**
// * Gets neutral color.
// * @return neutral color
// */
// public String getNeutral() {
// return neutral;
// }
//
// /**
// * Gets healthy color.
// * @return healthy color
// */
// public String getHealthy() {
// return healthy;
// }
//
// /**
// * Gets warning color.
// * @return warning color
// */
// public String getWarning() {
// return warning;
// }
//
// /**
// * Gets error color.
// * @return error color
// */
// public String getError() {
// return error;
// }
//
// /**
// * Gets a color configuration used in singlestat for when low value is good,
// * e.g., number of errors.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenLowIsHealthy() {
// return new Colors(healthy, warning, error);
// }
//
// /**
// * Gets a color configuration used in singlestat for when high value is good,
// * e.g., number of instances alive.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenHighIsHealthy() {
// return new Colors(error, warning, healthy);
// }
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text placeholder(int span) {
// return newText()
// .withContent("")
// .withTransparent(true)
// .withSpan(span);
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Row thinRow() {
// return newRow().withHeight("95px");
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text title(String title) {
// return newText()
// .withContent("<div class=\"text-center dashboard-header\"><span>" + title + "</span></div>")
// .withMode("html")
// .withTransparent(true);
// }
// Path: grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/complex/MultiEnvExampleDashboards.java
import static uk.co.szmg.grafana.dashboard.StaticFactories.placeholder;
import static uk.co.szmg.grafana.dashboard.StaticFactories.thinRow;
import static uk.co.szmg.grafana.dashboard.StaticFactories.title;
import static uk.co.szmg.grafana.domain.DomainFactories.newDashboard;
import static uk.co.szmg.grafana.domain.DomainFactories.newRow;
import uk.co.szmg.grafana.DashboardFactory;
import uk.co.szmg.grafana.dashboard.ColorTheme;
import uk.co.szmg.grafana.domain.Dashboard;
import uk.co.szmg.grafana.domain.Row;
import uk.co.szmg.grafana.domain.SingleStat;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;
package uk.co.szmg.grafana.example.dashboards.complex;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
@Named
public class MultiEnvExampleDashboards implements DashboardFactory {
private SampleAppEnvironment environments[] =
new SampleAppEnvironment[]{
new SampleAppEnvironment("Staging", "graphite", "MYAPP.stage", 2),
new SampleAppEnvironment("Production", "aws.graphite", "MYAPP.prod", 10)
};
private ColorTheme colorTheme = ColorTheme.RED_YELLOW_GREEN;
@Override
public List<Dashboard> create() {
List<Dashboard> dashboards = new ArrayList<>();
for (SampleAppEnvironment environment : environments) {
dashboards.add(create(environment));
}
return dashboards;
}
private Dashboard create(SampleAppEnvironment environment) {
XYComponentFactory factory = new XYComponentFactory(environment, colorTheme);
// might be better off in a factory method
SingleStat e500 = factory
.errorCounter("sumSeries({ROOT}.instrumentedFilter.serverErrors.count)", true)
.withTitle("E500 count");
// row definitions
Row row1 = thinRow() | .addPanel(title("Overview in " + environment.getName()).withSpan(12)); |
szmg/grafana-dashboard-generator-java | grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/complex/MultiEnvExampleDashboards.java | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/DashboardFactory.java
// public interface DashboardFactory {
//
// /**
// * Creates dashboards.
// * @return a list of dashboards created, should not be {@code null}
// */
// List<Dashboard> create();
//
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/ColorTheme.java
// public class ColorTheme {
//
// /**
// * A simple, red-yellow-green and white theme.
// */
// public static final ColorTheme RED_YELLOW_GREEN = new ColorTheme(
// "white",
// "rgba(50, 172, 45, 0.97)",
// "rgba(237, 129, 40, 0.89)",
// "rgba(245, 54, 54, 0.9)");
//
// private String neutral;
// private String healthy;
// private String warning;
// private String error;
//
// /**
// * Constructor.
// *
// * @param neutral neutral color for texts that are neither good nor bad; e.g., white
// * @param healthy color to mark healthy things, e.g., green
// * @param warning color used for the middle part of the thresholds, e.g., yellow
// * @param error color that marks an error, e.g., red
// */
// public ColorTheme(String neutral, String healthy, String warning, String error) {
// this.neutral = neutral;
// this.healthy = healthy;
// this.warning = warning;
// this.error = error;
// }
//
// /**
// * Gets neutral color.
// * @return neutral color
// */
// public String getNeutral() {
// return neutral;
// }
//
// /**
// * Gets healthy color.
// * @return healthy color
// */
// public String getHealthy() {
// return healthy;
// }
//
// /**
// * Gets warning color.
// * @return warning color
// */
// public String getWarning() {
// return warning;
// }
//
// /**
// * Gets error color.
// * @return error color
// */
// public String getError() {
// return error;
// }
//
// /**
// * Gets a color configuration used in singlestat for when low value is good,
// * e.g., number of errors.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenLowIsHealthy() {
// return new Colors(healthy, warning, error);
// }
//
// /**
// * Gets a color configuration used in singlestat for when high value is good,
// * e.g., number of instances alive.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenHighIsHealthy() {
// return new Colors(error, warning, healthy);
// }
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text placeholder(int span) {
// return newText()
// .withContent("")
// .withTransparent(true)
// .withSpan(span);
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Row thinRow() {
// return newRow().withHeight("95px");
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text title(String title) {
// return newText()
// .withContent("<div class=\"text-center dashboard-header\"><span>" + title + "</span></div>")
// .withMode("html")
// .withTransparent(true);
// }
| import static uk.co.szmg.grafana.dashboard.StaticFactories.placeholder;
import static uk.co.szmg.grafana.dashboard.StaticFactories.thinRow;
import static uk.co.szmg.grafana.dashboard.StaticFactories.title;
import static uk.co.szmg.grafana.domain.DomainFactories.newDashboard;
import static uk.co.szmg.grafana.domain.DomainFactories.newRow;
import uk.co.szmg.grafana.DashboardFactory;
import uk.co.szmg.grafana.dashboard.ColorTheme;
import uk.co.szmg.grafana.domain.Dashboard;
import uk.co.szmg.grafana.domain.Row;
import uk.co.szmg.grafana.domain.SingleStat;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List; | package uk.co.szmg.grafana.example.dashboards.complex;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
@Named
public class MultiEnvExampleDashboards implements DashboardFactory {
private SampleAppEnvironment environments[] =
new SampleAppEnvironment[]{
new SampleAppEnvironment("Staging", "graphite", "MYAPP.stage", 2),
new SampleAppEnvironment("Production", "aws.graphite", "MYAPP.prod", 10)
};
private ColorTheme colorTheme = ColorTheme.RED_YELLOW_GREEN;
@Override
public List<Dashboard> create() {
List<Dashboard> dashboards = new ArrayList<>();
for (SampleAppEnvironment environment : environments) {
dashboards.add(create(environment));
}
return dashboards;
}
private Dashboard create(SampleAppEnvironment environment) {
XYComponentFactory factory = new XYComponentFactory(environment, colorTheme);
// might be better off in a factory method
SingleStat e500 = factory
.errorCounter("sumSeries({ROOT}.instrumentedFilter.serverErrors.count)", true)
.withTitle("E500 count");
// row definitions
Row row1 = thinRow()
.addPanel(title("Overview in " + environment.getName()).withSpan(12));
Row row2 = thinRow()
.addPanel(e500) | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/DashboardFactory.java
// public interface DashboardFactory {
//
// /**
// * Creates dashboards.
// * @return a list of dashboards created, should not be {@code null}
// */
// List<Dashboard> create();
//
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/ColorTheme.java
// public class ColorTheme {
//
// /**
// * A simple, red-yellow-green and white theme.
// */
// public static final ColorTheme RED_YELLOW_GREEN = new ColorTheme(
// "white",
// "rgba(50, 172, 45, 0.97)",
// "rgba(237, 129, 40, 0.89)",
// "rgba(245, 54, 54, 0.9)");
//
// private String neutral;
// private String healthy;
// private String warning;
// private String error;
//
// /**
// * Constructor.
// *
// * @param neutral neutral color for texts that are neither good nor bad; e.g., white
// * @param healthy color to mark healthy things, e.g., green
// * @param warning color used for the middle part of the thresholds, e.g., yellow
// * @param error color that marks an error, e.g., red
// */
// public ColorTheme(String neutral, String healthy, String warning, String error) {
// this.neutral = neutral;
// this.healthy = healthy;
// this.warning = warning;
// this.error = error;
// }
//
// /**
// * Gets neutral color.
// * @return neutral color
// */
// public String getNeutral() {
// return neutral;
// }
//
// /**
// * Gets healthy color.
// * @return healthy color
// */
// public String getHealthy() {
// return healthy;
// }
//
// /**
// * Gets warning color.
// * @return warning color
// */
// public String getWarning() {
// return warning;
// }
//
// /**
// * Gets error color.
// * @return error color
// */
// public String getError() {
// return error;
// }
//
// /**
// * Gets a color configuration used in singlestat for when low value is good,
// * e.g., number of errors.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenLowIsHealthy() {
// return new Colors(healthy, warning, error);
// }
//
// /**
// * Gets a color configuration used in singlestat for when high value is good,
// * e.g., number of instances alive.
// * @return color configuration for singlestat
// */
// public Colors colorsWhenHighIsHealthy() {
// return new Colors(error, warning, healthy);
// }
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text placeholder(int span) {
// return newText()
// .withContent("")
// .withTransparent(true)
// .withSpan(span);
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Row thinRow() {
// return newRow().withHeight("95px");
// }
//
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/StaticFactories.java
// public static Text title(String title) {
// return newText()
// .withContent("<div class=\"text-center dashboard-header\"><span>" + title + "</span></div>")
// .withMode("html")
// .withTransparent(true);
// }
// Path: grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/complex/MultiEnvExampleDashboards.java
import static uk.co.szmg.grafana.dashboard.StaticFactories.placeholder;
import static uk.co.szmg.grafana.dashboard.StaticFactories.thinRow;
import static uk.co.szmg.grafana.dashboard.StaticFactories.title;
import static uk.co.szmg.grafana.domain.DomainFactories.newDashboard;
import static uk.co.szmg.grafana.domain.DomainFactories.newRow;
import uk.co.szmg.grafana.DashboardFactory;
import uk.co.szmg.grafana.dashboard.ColorTheme;
import uk.co.szmg.grafana.domain.Dashboard;
import uk.co.szmg.grafana.domain.Row;
import uk.co.szmg.grafana.domain.SingleStat;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;
package uk.co.szmg.grafana.example.dashboards.complex;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
@Named
public class MultiEnvExampleDashboards implements DashboardFactory {
private SampleAppEnvironment environments[] =
new SampleAppEnvironment[]{
new SampleAppEnvironment("Staging", "graphite", "MYAPP.stage", 2),
new SampleAppEnvironment("Production", "aws.graphite", "MYAPP.prod", 10)
};
private ColorTheme colorTheme = ColorTheme.RED_YELLOW_GREEN;
@Override
public List<Dashboard> create() {
List<Dashboard> dashboards = new ArrayList<>();
for (SampleAppEnvironment environment : environments) {
dashboards.add(create(environment));
}
return dashboards;
}
private Dashboard create(SampleAppEnvironment environment) {
XYComponentFactory factory = new XYComponentFactory(environment, colorTheme);
// might be better off in a factory method
SingleStat e500 = factory
.errorCounter("sumSeries({ROOT}.instrumentedFilter.serverErrors.count)", true)
.withTitle("E500 count");
// row definitions
Row row1 = thinRow()
.addPanel(title("Overview in " + environment.getName()).withSpan(12));
Row row2 = thinRow()
.addPanel(e500) | .addPanel(placeholder(8)) |
szmg/grafana-dashboard-generator-java | grafana-dashboard-generator-cli/src/main/java/uk/co/szmg/grafana/cli/internal/Interaction.java | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/GrafanaEndpoint.java
// public class GrafanaEndpoint {
//
// private String baseUrl;
// private String apiKey;
// private String sessionCookie;
// private boolean skipSSLValidation;
//
// /**
// * Gets Grafana base URL.
// * @return base URL
// */
// public String getBaseUrl() {
// return baseUrl;
// }
//
// /**
// * Sets Grafana base URL.
// * @param baseUrl Grafana base URL
// */
// public void setBaseUrl(String baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// /**
// * Gets API key.
// * @return API key
// */
// public String getApiKey() {
// return apiKey;
// }
//
// /**
// * True if SSL cert check should be forced to pass.
// * @return value of skipSSLValidation
// */
// public boolean isSkipSSLValidation() {
// return skipSSLValidation;
// }
//
// /**
// * Sets API gey.
// *
// * http://docs.grafana.org/http_api/auth/
// *
// * You need either this or the sessionCookie for authentication.
// *
// * @param apiKey API key
// */
// public void setApiKey(String apiKey) {
// this.apiKey = apiKey;
// }
//
// /**
// * Gets session cookie.
// * @return session cookie
// */
// public String getSessionCookie() {
// return sessionCookie;
// }
//
// /**
// * Sets session cookie.
// *
// * To get the value log in and copy the value of the "grafana_sess" cookie.
// *
// * You need either this or the apiKey for authentication.
// *
// * @param sessionCookie session cookie
// */
// public void setSessionCookie(String sessionCookie) {
// this.sessionCookie = sessionCookie;
// }
//
// /**
// * Set to true if you don't want SSL cert validation.
// * @param skipSSLCertValidation true if SSL cert validation should be skipped
// */
// public void setSkipSSLValidation(boolean skipSSLCertValidation) {
// this.skipSSLValidation = skipSSLCertValidation;
// }
// }
| import uk.co.szmg.grafana.GrafanaEndpoint;
import uk.co.szmg.grafana.domain.Dashboard;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import de.codeshelf.consoleui.elements.ConfirmChoice;
import de.codeshelf.consoleui.elements.PromptableElementIF;
import de.codeshelf.consoleui.prompt.CheckboxResult;
import de.codeshelf.consoleui.prompt.ConfirmResult;
import de.codeshelf.consoleui.prompt.ConsolePrompt;
import de.codeshelf.consoleui.prompt.ListResult;
import de.codeshelf.consoleui.prompt.PromtResultItemIF;
import de.codeshelf.consoleui.prompt.builder.CheckboxPromptBuilder;
import de.codeshelf.consoleui.prompt.builder.ListPromptBuilder;
import de.codeshelf.consoleui.prompt.builder.PromptBuilder; | package uk.co.szmg.grafana.cli.internal;
/*-
* #%L
* grafana-dashboard-generator-cli
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
public class Interaction {
public static void askUserForDetails(UploaderConfig config) throws IOException {
List<Dashboard> dashboards = config.getDashboardStore().getDashboards(); | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/GrafanaEndpoint.java
// public class GrafanaEndpoint {
//
// private String baseUrl;
// private String apiKey;
// private String sessionCookie;
// private boolean skipSSLValidation;
//
// /**
// * Gets Grafana base URL.
// * @return base URL
// */
// public String getBaseUrl() {
// return baseUrl;
// }
//
// /**
// * Sets Grafana base URL.
// * @param baseUrl Grafana base URL
// */
// public void setBaseUrl(String baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// /**
// * Gets API key.
// * @return API key
// */
// public String getApiKey() {
// return apiKey;
// }
//
// /**
// * True if SSL cert check should be forced to pass.
// * @return value of skipSSLValidation
// */
// public boolean isSkipSSLValidation() {
// return skipSSLValidation;
// }
//
// /**
// * Sets API gey.
// *
// * http://docs.grafana.org/http_api/auth/
// *
// * You need either this or the sessionCookie for authentication.
// *
// * @param apiKey API key
// */
// public void setApiKey(String apiKey) {
// this.apiKey = apiKey;
// }
//
// /**
// * Gets session cookie.
// * @return session cookie
// */
// public String getSessionCookie() {
// return sessionCookie;
// }
//
// /**
// * Sets session cookie.
// *
// * To get the value log in and copy the value of the "grafana_sess" cookie.
// *
// * You need either this or the apiKey for authentication.
// *
// * @param sessionCookie session cookie
// */
// public void setSessionCookie(String sessionCookie) {
// this.sessionCookie = sessionCookie;
// }
//
// /**
// * Set to true if you don't want SSL cert validation.
// * @param skipSSLCertValidation true if SSL cert validation should be skipped
// */
// public void setSkipSSLValidation(boolean skipSSLCertValidation) {
// this.skipSSLValidation = skipSSLCertValidation;
// }
// }
// Path: grafana-dashboard-generator-cli/src/main/java/uk/co/szmg/grafana/cli/internal/Interaction.java
import uk.co.szmg.grafana.GrafanaEndpoint;
import uk.co.szmg.grafana.domain.Dashboard;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import de.codeshelf.consoleui.elements.ConfirmChoice;
import de.codeshelf.consoleui.elements.PromptableElementIF;
import de.codeshelf.consoleui.prompt.CheckboxResult;
import de.codeshelf.consoleui.prompt.ConfirmResult;
import de.codeshelf.consoleui.prompt.ConsolePrompt;
import de.codeshelf.consoleui.prompt.ListResult;
import de.codeshelf.consoleui.prompt.PromtResultItemIF;
import de.codeshelf.consoleui.prompt.builder.CheckboxPromptBuilder;
import de.codeshelf.consoleui.prompt.builder.ListPromptBuilder;
import de.codeshelf.consoleui.prompt.builder.PromptBuilder;
package uk.co.szmg.grafana.cli.internal;
/*-
* #%L
* grafana-dashboard-generator-cli
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
public class Interaction {
public static void askUserForDetails(UploaderConfig config) throws IOException {
List<Dashboard> dashboards = config.getDashboardStore().getDashboards(); | Map<String, GrafanaEndpoint> endpoints = config.getEndpointStore().getEndpoints(); |
szmg/grafana-dashboard-generator-java | grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/ColorTheme.java | // Path: domain/src/main/java/uk/co/szmg/grafana/domain/Colors.java
// @JsonSerialize(using = Colors.ColorsSerialiser.class)
// public class Colors {
//
// private String low;
// private String mid;
// private String high;
//
// /**
// * Default constructor with default colors: red, yellow, green.
// */
// public Colors() {
// this("rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)");
// }
//
// /**
// * Convenience constructor.
// * @param low color used when the value is low
// * @param mid color used when the value is medium
// * @param high color used when the value is high
// */
// public Colors(String low, String mid, String high) {
// this.low = low;
// this.mid = mid;
// this.high = high;
// }
//
// /**
// * Gets color used when the value is low.
// * @return color
// */
// public String getLow() {
// return low;
// }
//
// /**
// * Sets color used when the value is low.
// * @param low color that's meaningful in HTML
// */
// public void setLow(String low) {
// this.low = low;
// }
//
// /**
// * Gets color used when the value is medium.
// * @return color
// */
// public String getMid() {
// return mid;
// }
//
// /**
// * Sets color used when the value is medium.
// * @param mid color that's meaningful in HTML
// */
// public void setMid(String mid) {
// this.mid = mid;
// }
//
// /**
// * Gets color used when the value is high.
// * @return color
// */
// public String getHigh() {
// return high;
// }
//
// /**
// * Sets color used when the value is high.
// * @param high color that's meaningful in HTML
// */
// public void setHigh(String high) {
// this.high = high;
// }
//
// public static class ColorsSerialiser extends JsonSerializer<Colors> {
//
// @Override
// public void serialize(Colors colors, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
// jsonGenerator.writeStartArray();
// jsonGenerator.writeString(colors.low);
// jsonGenerator.writeString(colors.mid);
// jsonGenerator.writeString(colors.high);
// jsonGenerator.writeEndArray();
// }
// }
// }
| import uk.co.szmg.grafana.domain.Colors; | package uk.co.szmg.grafana.dashboard;
/*-
* #%L
* grafana-dashboard-generator
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
/**
* Most dashboards have a common color palette. This class
* is to store one of that. Extend it in case you'd need
* more colors in your factories.
*
* There are 4 types of color:
* <dl>
* <dt>neutral</dt>
* <dd>color for texts that are neither good nor bad; e.g., white</dd>
* <dt>healthy</dt>
* <dd>color to mark healthy things, e.g., green</dd>
* <dt>warning</dt>
* <dd>color used for the middle part of the thresholds, e.g., yellow</dd>
* <dt>error</dt>
* <dd>color that marks an error, e.g., red</dd>
* </dl>
*
* Colors should be defined as html/css color strings.
*
* @see BasicFactories
* @since 1.1
*/
public class ColorTheme {
/**
* A simple, red-yellow-green and white theme.
*/
public static final ColorTheme RED_YELLOW_GREEN = new ColorTheme(
"white",
"rgba(50, 172, 45, 0.97)",
"rgba(237, 129, 40, 0.89)",
"rgba(245, 54, 54, 0.9)");
private String neutral;
private String healthy;
private String warning;
private String error;
/**
* Constructor.
*
* @param neutral neutral color for texts that are neither good nor bad; e.g., white
* @param healthy color to mark healthy things, e.g., green
* @param warning color used for the middle part of the thresholds, e.g., yellow
* @param error color that marks an error, e.g., red
*/
public ColorTheme(String neutral, String healthy, String warning, String error) {
this.neutral = neutral;
this.healthy = healthy;
this.warning = warning;
this.error = error;
}
/**
* Gets neutral color.
* @return neutral color
*/
public String getNeutral() {
return neutral;
}
/**
* Gets healthy color.
* @return healthy color
*/
public String getHealthy() {
return healthy;
}
/**
* Gets warning color.
* @return warning color
*/
public String getWarning() {
return warning;
}
/**
* Gets error color.
* @return error color
*/
public String getError() {
return error;
}
/**
* Gets a color configuration used in singlestat for when low value is good,
* e.g., number of errors.
* @return color configuration for singlestat
*/ | // Path: domain/src/main/java/uk/co/szmg/grafana/domain/Colors.java
// @JsonSerialize(using = Colors.ColorsSerialiser.class)
// public class Colors {
//
// private String low;
// private String mid;
// private String high;
//
// /**
// * Default constructor with default colors: red, yellow, green.
// */
// public Colors() {
// this("rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)");
// }
//
// /**
// * Convenience constructor.
// * @param low color used when the value is low
// * @param mid color used when the value is medium
// * @param high color used when the value is high
// */
// public Colors(String low, String mid, String high) {
// this.low = low;
// this.mid = mid;
// this.high = high;
// }
//
// /**
// * Gets color used when the value is low.
// * @return color
// */
// public String getLow() {
// return low;
// }
//
// /**
// * Sets color used when the value is low.
// * @param low color that's meaningful in HTML
// */
// public void setLow(String low) {
// this.low = low;
// }
//
// /**
// * Gets color used when the value is medium.
// * @return color
// */
// public String getMid() {
// return mid;
// }
//
// /**
// * Sets color used when the value is medium.
// * @param mid color that's meaningful in HTML
// */
// public void setMid(String mid) {
// this.mid = mid;
// }
//
// /**
// * Gets color used when the value is high.
// * @return color
// */
// public String getHigh() {
// return high;
// }
//
// /**
// * Sets color used when the value is high.
// * @param high color that's meaningful in HTML
// */
// public void setHigh(String high) {
// this.high = high;
// }
//
// public static class ColorsSerialiser extends JsonSerializer<Colors> {
//
// @Override
// public void serialize(Colors colors, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
// jsonGenerator.writeStartArray();
// jsonGenerator.writeString(colors.low);
// jsonGenerator.writeString(colors.mid);
// jsonGenerator.writeString(colors.high);
// jsonGenerator.writeEndArray();
// }
// }
// }
// Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/dashboard/ColorTheme.java
import uk.co.szmg.grafana.domain.Colors;
package uk.co.szmg.grafana.dashboard;
/*-
* #%L
* grafana-dashboard-generator
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
/**
* Most dashboards have a common color palette. This class
* is to store one of that. Extend it in case you'd need
* more colors in your factories.
*
* There are 4 types of color:
* <dl>
* <dt>neutral</dt>
* <dd>color for texts that are neither good nor bad; e.g., white</dd>
* <dt>healthy</dt>
* <dd>color to mark healthy things, e.g., green</dd>
* <dt>warning</dt>
* <dd>color used for the middle part of the thresholds, e.g., yellow</dd>
* <dt>error</dt>
* <dd>color that marks an error, e.g., red</dd>
* </dl>
*
* Colors should be defined as html/css color strings.
*
* @see BasicFactories
* @since 1.1
*/
public class ColorTheme {
/**
* A simple, red-yellow-green and white theme.
*/
public static final ColorTheme RED_YELLOW_GREEN = new ColorTheme(
"white",
"rgba(50, 172, 45, 0.97)",
"rgba(237, 129, 40, 0.89)",
"rgba(245, 54, 54, 0.9)");
private String neutral;
private String healthy;
private String warning;
private String error;
/**
* Constructor.
*
* @param neutral neutral color for texts that are neither good nor bad; e.g., white
* @param healthy color to mark healthy things, e.g., green
* @param warning color used for the middle part of the thresholds, e.g., yellow
* @param error color that marks an error, e.g., red
*/
public ColorTheme(String neutral, String healthy, String warning, String error) {
this.neutral = neutral;
this.healthy = healthy;
this.warning = warning;
this.error = error;
}
/**
* Gets neutral color.
* @return neutral color
*/
public String getNeutral() {
return neutral;
}
/**
* Gets healthy color.
* @return healthy color
*/
public String getHealthy() {
return healthy;
}
/**
* Gets warning color.
* @return warning color
*/
public String getWarning() {
return warning;
}
/**
* Gets error color.
* @return error color
*/
public String getError() {
return error;
}
/**
* Gets a color configuration used in singlestat for when low value is good,
* e.g., number of errors.
* @return color configuration for singlestat
*/ | public Colors colorsWhenLowIsHealthy() { |
szmg/grafana-dashboard-generator-java | grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/MyDashboardFactory.java | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/DashboardFactory.java
// public interface DashboardFactory {
//
// /**
// * Creates dashboards.
// * @return a list of dashboards created, should not be {@code null}
// */
// List<Dashboard> create();
//
// }
//
// Path: grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/Utils.java
// public static Dashboard createSimpleDashboard(String title, Class<?> clazz) {
// return newDashboard()
// .withTitle(title)
// .addRow(newRow()
// .addPanel(newText()
// .withSpan(12).withContent("This was created by " + clazz.getSimpleName())))
// .addRow(newRow()
// .withHeight("95px")
// .addPanel(newText()
// .withSpan(12).withContent("Selected env: $env")))
// .withAnnotations(newAnnotationList()
// .addList(newAlertAnnotation()
// .withName("alert")
// .withLimit(300)
// .withEnable(true))
// .addList(newGraphiteAnnotation()
// .withName("deployment")
// .withDatasource("graphite")
// .withTarget("app.deployment")
// .withIconColor("green")))
// .withTemplating(newTemplateList()
// .addList(newTemplate()
// .withName("env")
// .withLabel("Environment")
// .withType("custom")
// .withQuery("staging,canary,production,perf")
// // options have to be added... templating support should be revised...
// .addOption(newTemplateOption().withValue("staging").withText("staging"))
// .addOption(newTemplateOption().withValue("production").withText("production"))
// .withCurrent(new SelectedTemplate("staging", "staging"))));
// }
| import uk.co.szmg.grafana.DashboardFactory;
import uk.co.szmg.grafana.domain.Dashboard;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;
import static uk.co.szmg.grafana.example.dashboards.Utils.createSimpleDashboard; | package uk.co.szmg.grafana.example.dashboards;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
@Named
public class MyDashboardFactory implements DashboardFactory {
@Override
public List<Dashboard> create() {
List<Dashboard> dashboards = new ArrayList<>(); | // Path: grafana-dashboard-generator/src/main/java/uk/co/szmg/grafana/DashboardFactory.java
// public interface DashboardFactory {
//
// /**
// * Creates dashboards.
// * @return a list of dashboards created, should not be {@code null}
// */
// List<Dashboard> create();
//
// }
//
// Path: grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/Utils.java
// public static Dashboard createSimpleDashboard(String title, Class<?> clazz) {
// return newDashboard()
// .withTitle(title)
// .addRow(newRow()
// .addPanel(newText()
// .withSpan(12).withContent("This was created by " + clazz.getSimpleName())))
// .addRow(newRow()
// .withHeight("95px")
// .addPanel(newText()
// .withSpan(12).withContent("Selected env: $env")))
// .withAnnotations(newAnnotationList()
// .addList(newAlertAnnotation()
// .withName("alert")
// .withLimit(300)
// .withEnable(true))
// .addList(newGraphiteAnnotation()
// .withName("deployment")
// .withDatasource("graphite")
// .withTarget("app.deployment")
// .withIconColor("green")))
// .withTemplating(newTemplateList()
// .addList(newTemplate()
// .withName("env")
// .withLabel("Environment")
// .withType("custom")
// .withQuery("staging,canary,production,perf")
// // options have to be added... templating support should be revised...
// .addOption(newTemplateOption().withValue("staging").withText("staging"))
// .addOption(newTemplateOption().withValue("production").withText("production"))
// .withCurrent(new SelectedTemplate("staging", "staging"))));
// }
// Path: grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/MyDashboardFactory.java
import uk.co.szmg.grafana.DashboardFactory;
import uk.co.szmg.grafana.domain.Dashboard;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;
import static uk.co.szmg.grafana.example.dashboards.Utils.createSimpleDashboard;
package uk.co.szmg.grafana.example.dashboards;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* 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.
* #L%
*/
@Named
public class MyDashboardFactory implements DashboardFactory {
@Override
public List<Dashboard> create() {
List<Dashboard> dashboards = new ArrayList<>(); | dashboards.add(createSimpleDashboard("By factory 1", MyDashboardFactory.class)); |
fipro78/e4translationexample | org.fipro.e4.translation/src/org/fipro/e4/translation/parts/OsgiExample.java | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/OsgiMessageRegistry.java
// @Creatable
// public class OsgiMessageRegistry extends BaseMessageRegistry<OsgiMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation OsgiMessages messages) {
// super.updateMessages(messages);
// }
// }
| import java.util.Locale;
import java.util.ResourceBundle;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.core.services.nls.ILocaleChangeService;
import org.eclipse.e4.core.services.translation.ResourceBundleProvider;
import org.eclipse.e4.core.services.translation.TranslationService;
import org.eclipse.e4.ui.di.UIEventTopic;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.fipro.e4.translation.registry.OsgiMessageRegistry;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil; | package org.fipro.e4.translation.parts;
/**
* Example showing the usage of the new message extension by using
* OSGi ResourceBundles configured in the MANIFEST.MF
*/
public class OsgiExample {
@Inject | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/OsgiMessageRegistry.java
// @Creatable
// public class OsgiMessageRegistry extends BaseMessageRegistry<OsgiMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation OsgiMessages messages) {
// super.updateMessages(messages);
// }
// }
// Path: org.fipro.e4.translation/src/org/fipro/e4/translation/parts/OsgiExample.java
import java.util.Locale;
import java.util.ResourceBundle;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.core.services.nls.ILocaleChangeService;
import org.eclipse.e4.core.services.translation.ResourceBundleProvider;
import org.eclipse.e4.core.services.translation.TranslationService;
import org.eclipse.e4.ui.di.UIEventTopic;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.fipro.e4.translation.registry.OsgiMessageRegistry;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
package org.fipro.e4.translation.parts;
/**
* Example showing the usage of the new message extension by using
* OSGi ResourceBundles configured in the MANIFEST.MF
*/
public class OsgiExample {
@Inject | OsgiMessageRegistry registry; |
fipro78/e4translationexample | org.fipro.e4.translation/src/org/fipro/e4/translation/parts/LocationExample.java | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/LocationMessageRegistry.java
// @Creatable
// public class LocationMessageRegistry extends BaseMessageRegistry<LocationMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation LocationMessages messages) {
// super.updateMessages(messages);
// }
// }
| import javax.inject.Inject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.fipro.e4.translation.registry.LocationMessageRegistry; | package org.fipro.e4.translation.parts;
/**
* Example showing the usage of the new message extension by using
* ResourceBundles located in the same plugin at a different location.
*/
public class LocationExample {
@Inject | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/LocationMessageRegistry.java
// @Creatable
// public class LocationMessageRegistry extends BaseMessageRegistry<LocationMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation LocationMessages messages) {
// super.updateMessages(messages);
// }
// }
// Path: org.fipro.e4.translation/src/org/fipro/e4/translation/parts/LocationExample.java
import javax.inject.Inject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.fipro.e4.translation.registry.LocationMessageRegistry;
package org.fipro.e4.translation.parts;
/**
* Example showing the usage of the new message extension by using
* ResourceBundles located in the same plugin at a different location.
*/
public class LocationExample {
@Inject | public LocationExample(Composite parent, LocationMessageRegistry registry) { |
fipro78/e4translationexample | org.fipro.e4.translation/src/org/fipro/e4/translation/parts/FragmentExample.java | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/FragmentMessageRegistry.java
// @Creatable
// public class FragmentMessageRegistry extends BaseMessageRegistry<FragmentMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation FragmentMessages messages) {
// super.updateMessages(messages);
// }
// }
| import javax.annotation.PostConstruct;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.fipro.e4.translation.registry.FragmentMessageRegistry; |
package org.fipro.e4.translation.parts;
public class FragmentExample {
@PostConstruct | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/FragmentMessageRegistry.java
// @Creatable
// public class FragmentMessageRegistry extends BaseMessageRegistry<FragmentMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation FragmentMessages messages) {
// super.updateMessages(messages);
// }
// }
// Path: org.fipro.e4.translation/src/org/fipro/e4/translation/parts/FragmentExample.java
import javax.annotation.PostConstruct;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.fipro.e4.translation.registry.FragmentMessageRegistry;
package org.fipro.e4.translation.parts;
public class FragmentExample {
@PostConstruct | public void init(Composite parent, FragmentMessageRegistry registry) { |
fipro78/e4translationexample | org.fipro.e4.translation/src/org/fipro/e4/translation/parts/ImplementationExample.java | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/ImplementationMessageRegistry.java
// @Creatable
// public class ImplementationMessageRegistry extends BaseMessageRegistry<ImplementationMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation ImplementationMessages messages) {
// super.updateMessages(messages);
// }
// }
| import javax.inject.Inject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.fipro.e4.translation.registry.ImplementationMessageRegistry; |
package org.fipro.e4.translation.parts;
public class ImplementationExample {
@Inject | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/ImplementationMessageRegistry.java
// @Creatable
// public class ImplementationMessageRegistry extends BaseMessageRegistry<ImplementationMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation ImplementationMessages messages) {
// super.updateMessages(messages);
// }
// }
// Path: org.fipro.e4.translation/src/org/fipro/e4/translation/parts/ImplementationExample.java
import javax.inject.Inject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.fipro.e4.translation.registry.ImplementationMessageRegistry;
package org.fipro.e4.translation.parts;
public class ImplementationExample {
@Inject | public ImplementationExample(Composite parent, ImplementationMessageRegistry registry) { |
fipro78/e4translationexample | org.fipro.e4.translation/src/org/fipro/e4/translation/control/LocaleChangeItem.java | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/OsgiMessageRegistry.java
// @Creatable
// public class OsgiMessageRegistry extends BaseMessageRegistry<OsgiMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation OsgiMessages messages) {
// super.updateMessages(messages);
// }
// }
| import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.eclipse.e4.core.services.nls.ILocaleChangeService;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.fipro.e4.translation.registry.OsgiMessageRegistry; | package org.fipro.e4.translation.control;
/**
* Item that is added as a ToolControl to the TrimBar of the
* Window. Shows an input field which allows to enter a
* locale String and a Button to send the action to update
* the Locale.
*/
public class LocaleChangeItem {
@Inject
ILocaleChangeService lcs;
@PostConstruct | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/OsgiMessageRegistry.java
// @Creatable
// public class OsgiMessageRegistry extends BaseMessageRegistry<OsgiMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation OsgiMessages messages) {
// super.updateMessages(messages);
// }
// }
// Path: org.fipro.e4.translation/src/org/fipro/e4/translation/control/LocaleChangeItem.java
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.eclipse.e4.core.services.nls.ILocaleChangeService;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.fipro.e4.translation.registry.OsgiMessageRegistry;
package org.fipro.e4.translation.control;
/**
* Item that is added as a ToolControl to the TrimBar of the
* Window. Shows an input field which allows to enter a
* locale String and a Button to send the action to update
* the Locale.
*/
public class LocaleChangeItem {
@Inject
ILocaleChangeService lcs;
@PostConstruct | public void postConstruct(Composite parent, OsgiMessageRegistry registry) { |
fipro78/e4translationexample | org.fipro.e4.translation/src/org/fipro/e4/translation/parts/NamedExample.java | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/MessageRegistry.java
// @Creatable
// public class MessageRegistry extends BaseMessageRegistry<Messages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation Messages messages) {
// super.updateMessages(messages);
// }
// }
//
// Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/NamedMessageRegistry.java
// @Creatable
// public class NamedMessageRegistry extends BaseMessageRegistry<NamedMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation NamedMessages messages) {
// super.updateMessages(messages);
// }
// }
| import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.fipro.e4.translation.registry.MessageRegistry;
import org.fipro.e4.translation.registry.NamedMessageRegistry; | package org.fipro.e4.translation.parts;
/**
* Example showing the usage of the new message extension by using
* a ResourceBundle that is named and located like the messages class.
* <p>
* This example also shows how to implement the <i>Eclipse translation
* pattern</i> when creating the UI in the method annotated with
* <code>@PostConstruct</code>
*/
public class NamedExample {
@Inject | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/MessageRegistry.java
// @Creatable
// public class MessageRegistry extends BaseMessageRegistry<Messages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation Messages messages) {
// super.updateMessages(messages);
// }
// }
//
// Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/NamedMessageRegistry.java
// @Creatable
// public class NamedMessageRegistry extends BaseMessageRegistry<NamedMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation NamedMessages messages) {
// super.updateMessages(messages);
// }
// }
// Path: org.fipro.e4.translation/src/org/fipro/e4/translation/parts/NamedExample.java
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.fipro.e4.translation.registry.MessageRegistry;
import org.fipro.e4.translation.registry.NamedMessageRegistry;
package org.fipro.e4.translation.parts;
/**
* Example showing the usage of the new message extension by using
* a ResourceBundle that is named and located like the messages class.
* <p>
* This example also shows how to implement the <i>Eclipse translation
* pattern</i> when creating the UI in the method annotated with
* <code>@PostConstruct</code>
*/
public class NamedExample {
@Inject | NamedMessageRegistry registry; |
fipro78/e4translationexample | org.fipro.e4.translation/src/org/fipro/e4/translation/parts/NamedExample.java | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/MessageRegistry.java
// @Creatable
// public class MessageRegistry extends BaseMessageRegistry<Messages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation Messages messages) {
// super.updateMessages(messages);
// }
// }
//
// Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/NamedMessageRegistry.java
// @Creatable
// public class NamedMessageRegistry extends BaseMessageRegistry<NamedMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation NamedMessages messages) {
// super.updateMessages(messages);
// }
// }
| import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.fipro.e4.translation.registry.MessageRegistry;
import org.fipro.e4.translation.registry.NamedMessageRegistry; | package org.fipro.e4.translation.parts;
/**
* Example showing the usage of the new message extension by using
* a ResourceBundle that is named and located like the messages class.
* <p>
* This example also shows how to implement the <i>Eclipse translation
* pattern</i> when creating the UI in the method annotated with
* <code>@PostConstruct</code>
*/
public class NamedExample {
@Inject
NamedMessageRegistry registry;
@Inject | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/MessageRegistry.java
// @Creatable
// public class MessageRegistry extends BaseMessageRegistry<Messages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation Messages messages) {
// super.updateMessages(messages);
// }
// }
//
// Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/NamedMessageRegistry.java
// @Creatable
// public class NamedMessageRegistry extends BaseMessageRegistry<NamedMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation NamedMessages messages) {
// super.updateMessages(messages);
// }
// }
// Path: org.fipro.e4.translation/src/org/fipro/e4/translation/parts/NamedExample.java
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.fipro.e4.translation.registry.MessageRegistry;
import org.fipro.e4.translation.registry.NamedMessageRegistry;
package org.fipro.e4.translation.parts;
/**
* Example showing the usage of the new message extension by using
* a ResourceBundle that is named and located like the messages class.
* <p>
* This example also shows how to implement the <i>Eclipse translation
* pattern</i> when creating the UI in the method annotated with
* <code>@PostConstruct</code>
*/
public class NamedExample {
@Inject
NamedMessageRegistry registry;
@Inject | MessageRegistry mRegistry; |
fipro78/e4translationexample | org.fipro.e4.translation/src/org/fipro/e4/translation/parts/PluginExample.java | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/PluginMessageRegistry.java
// @Creatable
// public class PluginMessageRegistry extends BaseMessageRegistry<PluginMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation PluginMessages messages) {
// super.updateMessages(messages);
// }
// }
| import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.fipro.e4.translation.registry.PluginMessageRegistry; |
package org.fipro.e4.translation.parts;
public class PluginExample {
@Inject | // Path: org.fipro.e4.translation/src/org/fipro/e4/translation/registry/PluginMessageRegistry.java
// @Creatable
// public class PluginMessageRegistry extends BaseMessageRegistry<PluginMessages> {
//
// @Override
// @Inject
// public void updateMessages(@Translation PluginMessages messages) {
// super.updateMessages(messages);
// }
// }
// Path: org.fipro.e4.translation/src/org/fipro/e4/translation/parts/PluginExample.java
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.fipro.e4.translation.registry.PluginMessageRegistry;
package org.fipro.e4.translation.parts;
public class PluginExample {
@Inject | PluginMessageRegistry registry; |
tqvarnst/jboss-eap7-summit-lab | projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/rest/ProductResourceRESTService.java | // Path: projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/concurrency/DeleteTask.java
// public class DeleteTask implements Runnable {
//
// @Inject
// private Logger log;
//
// @Inject
// private EntityManager entityManager;
//
// @Inject
// private UserTransaction userTransaction;
//
// @Override
// public void run() {
// try {
// log.info("Begin transaction");
// userTransaction.begin();
// log.info("Deleting all products");
// int qtd = entityManager.createQuery("DELETE FROM Product").executeUpdate();
// log.info("Commit transaction. Products deleted: " + qtd);
// userTransaction.commit();
// } catch (Exception e) {
// log.info("Exception: " + e.getMessage());
// try {
// if (userTransaction != null) {
// log.info("Rollback transaction");
// userTransaction.rollback();
// }
// } catch (SystemException e1) {
// log.info("Failed to rollback transaction: " + e1.getMessage());
// }
// }
//
// }
//
// }
//
// Path: projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/concurrency/LongRunningTask.java
// public class LongRunningTask implements Callable<Integer> {
//
// @Inject
// private Logger log;
//
// @Inject
// private EntityManager entityManager;
//
// @Override
// @SuppressWarnings("unchecked")
// public Integer call() throws Exception {
// // here we simulate an access to Products listing
// List<Product> products = (List<Product>) entityManager.createQuery("SELECT p FROM Product p").getResultList();
// log.info("Starting a long running task");
// for (Product product : products) {
// log.info("Analysing " + product.getName());
// // We simulate now a long running task
// Thread.sleep(3000);
// }
// // after executing a long running task we return a result
// return (int) (Math.random() * 100);
// }
//
// }
//
// Path: projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/concurrency/PersitTask.java
// public class PersitTask implements Runnable {
//
// @Inject
// private Logger log;
//
// @Inject
// private EntityManager entityManager;
//
// @Inject
// private UserTransaction userTransaction;
//
// private Product product;
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// @Override
// public void run() {
// try {
// log.info("Begin transaction");
// userTransaction.begin();
// log.info("Persisting a new product");
// entityManager.persist(product);
// log.info("Commit transaction");
// userTransaction.commit();
// } catch (Exception e) {
// log.info("Exception: " + e.getMessage());
// try {
// if (userTransaction != null) {
// log.info("Rollback transaction");
// userTransaction.rollback();
// }
// } catch (SystemException e1) {
// log.info("Failed to rollback transaction: " + e1.getMessage());
// }
// }
//
// }
//
// }
| import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.as.quickstarts.managedexecutorservice.concurrency.DeleteTask;
import org.jboss.as.quickstarts.managedexecutorservice.concurrency.LongRunningTask;
import org.jboss.as.quickstarts.managedexecutorservice.concurrency.PersitTask;
import org.jboss.as.quickstarts.managedexecutorservice.model.Product; | /*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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.jboss.as.quickstarts.managedexecutorservice.rest;
@Path("/products")
public class ProductResourceRESTService {
@Inject
private Logger log;
@Resource
private ManagedExecutorService managedExecutorService;
// Here we use Instance so PersistTask can have CDI injections available
@Inject | // Path: projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/concurrency/DeleteTask.java
// public class DeleteTask implements Runnable {
//
// @Inject
// private Logger log;
//
// @Inject
// private EntityManager entityManager;
//
// @Inject
// private UserTransaction userTransaction;
//
// @Override
// public void run() {
// try {
// log.info("Begin transaction");
// userTransaction.begin();
// log.info("Deleting all products");
// int qtd = entityManager.createQuery("DELETE FROM Product").executeUpdate();
// log.info("Commit transaction. Products deleted: " + qtd);
// userTransaction.commit();
// } catch (Exception e) {
// log.info("Exception: " + e.getMessage());
// try {
// if (userTransaction != null) {
// log.info("Rollback transaction");
// userTransaction.rollback();
// }
// } catch (SystemException e1) {
// log.info("Failed to rollback transaction: " + e1.getMessage());
// }
// }
//
// }
//
// }
//
// Path: projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/concurrency/LongRunningTask.java
// public class LongRunningTask implements Callable<Integer> {
//
// @Inject
// private Logger log;
//
// @Inject
// private EntityManager entityManager;
//
// @Override
// @SuppressWarnings("unchecked")
// public Integer call() throws Exception {
// // here we simulate an access to Products listing
// List<Product> products = (List<Product>) entityManager.createQuery("SELECT p FROM Product p").getResultList();
// log.info("Starting a long running task");
// for (Product product : products) {
// log.info("Analysing " + product.getName());
// // We simulate now a long running task
// Thread.sleep(3000);
// }
// // after executing a long running task we return a result
// return (int) (Math.random() * 100);
// }
//
// }
//
// Path: projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/concurrency/PersitTask.java
// public class PersitTask implements Runnable {
//
// @Inject
// private Logger log;
//
// @Inject
// private EntityManager entityManager;
//
// @Inject
// private UserTransaction userTransaction;
//
// private Product product;
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// @Override
// public void run() {
// try {
// log.info("Begin transaction");
// userTransaction.begin();
// log.info("Persisting a new product");
// entityManager.persist(product);
// log.info("Commit transaction");
// userTransaction.commit();
// } catch (Exception e) {
// log.info("Exception: " + e.getMessage());
// try {
// if (userTransaction != null) {
// log.info("Rollback transaction");
// userTransaction.rollback();
// }
// } catch (SystemException e1) {
// log.info("Failed to rollback transaction: " + e1.getMessage());
// }
// }
//
// }
//
// }
// Path: projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/rest/ProductResourceRESTService.java
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.as.quickstarts.managedexecutorservice.concurrency.DeleteTask;
import org.jboss.as.quickstarts.managedexecutorservice.concurrency.LongRunningTask;
import org.jboss.as.quickstarts.managedexecutorservice.concurrency.PersitTask;
import org.jboss.as.quickstarts.managedexecutorservice.model.Product;
/*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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.jboss.as.quickstarts.managedexecutorservice.rest;
@Path("/products")
public class ProductResourceRESTService {
@Inject
private Logger log;
@Resource
private ManagedExecutorService managedExecutorService;
// Here we use Instance so PersistTask can have CDI injections available
@Inject | private Instance<PersitTask> persisTaskInstance; |
tqvarnst/jboss-eap7-summit-lab | projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/rest/ProductResourceRESTService.java | // Path: projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/concurrency/DeleteTask.java
// public class DeleteTask implements Runnable {
//
// @Inject
// private Logger log;
//
// @Inject
// private EntityManager entityManager;
//
// @Inject
// private UserTransaction userTransaction;
//
// @Override
// public void run() {
// try {
// log.info("Begin transaction");
// userTransaction.begin();
// log.info("Deleting all products");
// int qtd = entityManager.createQuery("DELETE FROM Product").executeUpdate();
// log.info("Commit transaction. Products deleted: " + qtd);
// userTransaction.commit();
// } catch (Exception e) {
// log.info("Exception: " + e.getMessage());
// try {
// if (userTransaction != null) {
// log.info("Rollback transaction");
// userTransaction.rollback();
// }
// } catch (SystemException e1) {
// log.info("Failed to rollback transaction: " + e1.getMessage());
// }
// }
//
// }
//
// }
//
// Path: projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/concurrency/LongRunningTask.java
// public class LongRunningTask implements Callable<Integer> {
//
// @Inject
// private Logger log;
//
// @Inject
// private EntityManager entityManager;
//
// @Override
// @SuppressWarnings("unchecked")
// public Integer call() throws Exception {
// // here we simulate an access to Products listing
// List<Product> products = (List<Product>) entityManager.createQuery("SELECT p FROM Product p").getResultList();
// log.info("Starting a long running task");
// for (Product product : products) {
// log.info("Analysing " + product.getName());
// // We simulate now a long running task
// Thread.sleep(3000);
// }
// // after executing a long running task we return a result
// return (int) (Math.random() * 100);
// }
//
// }
//
// Path: projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/concurrency/PersitTask.java
// public class PersitTask implements Runnable {
//
// @Inject
// private Logger log;
//
// @Inject
// private EntityManager entityManager;
//
// @Inject
// private UserTransaction userTransaction;
//
// private Product product;
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// @Override
// public void run() {
// try {
// log.info("Begin transaction");
// userTransaction.begin();
// log.info("Persisting a new product");
// entityManager.persist(product);
// log.info("Commit transaction");
// userTransaction.commit();
// } catch (Exception e) {
// log.info("Exception: " + e.getMessage());
// try {
// if (userTransaction != null) {
// log.info("Rollback transaction");
// userTransaction.rollback();
// }
// } catch (SystemException e1) {
// log.info("Failed to rollback transaction: " + e1.getMessage());
// }
// }
//
// }
//
// }
| import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.as.quickstarts.managedexecutorservice.concurrency.DeleteTask;
import org.jboss.as.quickstarts.managedexecutorservice.concurrency.LongRunningTask;
import org.jboss.as.quickstarts.managedexecutorservice.concurrency.PersitTask;
import org.jboss.as.quickstarts.managedexecutorservice.model.Product; | /*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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.jboss.as.quickstarts.managedexecutorservice.rest;
@Path("/products")
public class ProductResourceRESTService {
@Inject
private Logger log;
@Resource
private ManagedExecutorService managedExecutorService;
// Here we use Instance so PersistTask can have CDI injections available
@Inject
private Instance<PersitTask> persisTaskInstance;
// Here we use Instance so LongRunningTask can have CDI injections available
@Inject | // Path: projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/concurrency/DeleteTask.java
// public class DeleteTask implements Runnable {
//
// @Inject
// private Logger log;
//
// @Inject
// private EntityManager entityManager;
//
// @Inject
// private UserTransaction userTransaction;
//
// @Override
// public void run() {
// try {
// log.info("Begin transaction");
// userTransaction.begin();
// log.info("Deleting all products");
// int qtd = entityManager.createQuery("DELETE FROM Product").executeUpdate();
// log.info("Commit transaction. Products deleted: " + qtd);
// userTransaction.commit();
// } catch (Exception e) {
// log.info("Exception: " + e.getMessage());
// try {
// if (userTransaction != null) {
// log.info("Rollback transaction");
// userTransaction.rollback();
// }
// } catch (SystemException e1) {
// log.info("Failed to rollback transaction: " + e1.getMessage());
// }
// }
//
// }
//
// }
//
// Path: projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/concurrency/LongRunningTask.java
// public class LongRunningTask implements Callable<Integer> {
//
// @Inject
// private Logger log;
//
// @Inject
// private EntityManager entityManager;
//
// @Override
// @SuppressWarnings("unchecked")
// public Integer call() throws Exception {
// // here we simulate an access to Products listing
// List<Product> products = (List<Product>) entityManager.createQuery("SELECT p FROM Product p").getResultList();
// log.info("Starting a long running task");
// for (Product product : products) {
// log.info("Analysing " + product.getName());
// // We simulate now a long running task
// Thread.sleep(3000);
// }
// // after executing a long running task we return a result
// return (int) (Math.random() * 100);
// }
//
// }
//
// Path: projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/concurrency/PersitTask.java
// public class PersitTask implements Runnable {
//
// @Inject
// private Logger log;
//
// @Inject
// private EntityManager entityManager;
//
// @Inject
// private UserTransaction userTransaction;
//
// private Product product;
//
// public void setProduct(Product product) {
// this.product = product;
// }
//
// @Override
// public void run() {
// try {
// log.info("Begin transaction");
// userTransaction.begin();
// log.info("Persisting a new product");
// entityManager.persist(product);
// log.info("Commit transaction");
// userTransaction.commit();
// } catch (Exception e) {
// log.info("Exception: " + e.getMessage());
// try {
// if (userTransaction != null) {
// log.info("Rollback transaction");
// userTransaction.rollback();
// }
// } catch (SystemException e1) {
// log.info("Failed to rollback transaction: " + e1.getMessage());
// }
// }
//
// }
//
// }
// Path: projects/05_concurrency/managed-executor-service/src/main/java/org/jboss/as/quickstarts/managedexecutorservice/rest/ProductResourceRESTService.java
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.as.quickstarts.managedexecutorservice.concurrency.DeleteTask;
import org.jboss.as.quickstarts.managedexecutorservice.concurrency.LongRunningTask;
import org.jboss.as.quickstarts.managedexecutorservice.concurrency.PersitTask;
import org.jboss.as.quickstarts.managedexecutorservice.model.Product;
/*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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.jboss.as.quickstarts.managedexecutorservice.rest;
@Path("/products")
public class ProductResourceRESTService {
@Inject
private Logger log;
@Resource
private ManagedExecutorService managedExecutorService;
// Here we use Instance so PersistTask can have CDI injections available
@Inject
private Instance<PersitTask> persisTaskInstance;
// Here we use Instance so LongRunningTask can have CDI injections available
@Inject | private Instance<LongRunningTask> longRunningTaskIntance; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.