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
unsw-cse-soc/Data-curation-API
src/main/java/unsw/curation/api/extractsimilarity/ExtractNumberEuclideanSimilarity.java
// Path: src/main/java/unsw/curation/api/domain/ExtractNumberSimilarity.java // public class ExtractNumberSimilarity { // // private String vector1; // private String vector2; // private double score; // // public ExtractNumberSimilarity(){} // // public ExtractNumberSimilarity(String vector1,String vector2,double score) // { // this.vector1=vector1; // this.vector2=vector2; // this.score=score; // } // // public void setVector1(String vector1) // { // this.vector1=vector1; // } // public String getVector1() // { // return this.vector1; // } // // public void setVecor2(String vector2) // { // this.vector2=vector2; // } // public String getVector2() // { // return this.vector2; // } // public void setScore(double score) // { // this.score=score; // } // public double getScore() // { // return this.score; // } // } // // Path: src/main/java/unsw/curation/api/domain/abstraction/INumberEuclideanSimilarity.java // public interface INumberEuclideanSimilarity { // // double Euclidean_Vector_Vector(double [] number1,double [] number2); // List<ExtractNumberSimilarity> Euclidean_Vector_VectorS(String filePath) throws IOException; // List<ExtractNumberSimilarity> Euclidean_Vector_VectorS(double [] vector,String filePath) throws IOException; // }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import unsw.curation.api.domain.ExtractNumberSimilarity; import unsw.curation.api.domain.abstraction.INumberEuclideanSimilarity;
package unsw.curation.api.extractsimilarity; public class ExtractNumberEuclideanSimilarity implements INumberEuclideanSimilarity{ @Override public double Euclidean_Vector_Vector(double [] vector1,double [] vector2) { if(vector1.length==vector2.length) { double sum=0.0; for(int i=0;i<vector1.length;i++) { double tempValue= vector2[i]-vector1[i]; tempValue=Math.pow(tempValue, 2); sum+=tempValue; } double EclideanDistance=Math.sqrt(sum); return EclideanDistance; } else { System.err.println("Error in Vectors length..."); return 0.0; } } @Override
// Path: src/main/java/unsw/curation/api/domain/ExtractNumberSimilarity.java // public class ExtractNumberSimilarity { // // private String vector1; // private String vector2; // private double score; // // public ExtractNumberSimilarity(){} // // public ExtractNumberSimilarity(String vector1,String vector2,double score) // { // this.vector1=vector1; // this.vector2=vector2; // this.score=score; // } // // public void setVector1(String vector1) // { // this.vector1=vector1; // } // public String getVector1() // { // return this.vector1; // } // // public void setVecor2(String vector2) // { // this.vector2=vector2; // } // public String getVector2() // { // return this.vector2; // } // public void setScore(double score) // { // this.score=score; // } // public double getScore() // { // return this.score; // } // } // // Path: src/main/java/unsw/curation/api/domain/abstraction/INumberEuclideanSimilarity.java // public interface INumberEuclideanSimilarity { // // double Euclidean_Vector_Vector(double [] number1,double [] number2); // List<ExtractNumberSimilarity> Euclidean_Vector_VectorS(String filePath) throws IOException; // List<ExtractNumberSimilarity> Euclidean_Vector_VectorS(double [] vector,String filePath) throws IOException; // } // Path: src/main/java/unsw/curation/api/extractsimilarity/ExtractNumberEuclideanSimilarity.java import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import unsw.curation.api.domain.ExtractNumberSimilarity; import unsw.curation.api.domain.abstraction.INumberEuclideanSimilarity; package unsw.curation.api.extractsimilarity; public class ExtractNumberEuclideanSimilarity implements INumberEuclideanSimilarity{ @Override public double Euclidean_Vector_Vector(double [] vector1,double [] vector2) { if(vector1.length==vector2.length) { double sum=0.0; for(int i=0;i<vector1.length;i++) { double tempValue= vector2[i]-vector1[i]; tempValue=Math.pow(tempValue, 2); sum+=tempValue; } double EclideanDistance=Math.sqrt(sum); return EclideanDistance; } else { System.err.println("Error in Vectors length..."); return 0.0; } } @Override
public List<ExtractNumberSimilarity> Euclidean_Vector_VectorS(String filePath) throws IOException
unsw-cse-soc/Data-curation-API
src/main/java/unsw/curation/api/domain/abstraction/ITextLevenshtainSimilarity.java
// Path: src/main/java/unsw/curation/api/domain/ExtractTextSimilarity.java // public class ExtractTextSimilarity { // // private String word; // public void setWord(String word) // { // this.word=word; // } // public String getWord() // { // return this.word; // } // private String candidate; // public void setCandidate(String candidate) // { // this.candidate=candidate; // } // public String getCandidate() // { // return this.candidate; // } // private double similarity; // public void setSimilarity(double similarity) // { // this.similarity=similarity; // } // public double getSimilarity() // { // return this.similarity; // } // public ExtractTextSimilarity(){} // public ExtractTextSimilarity (String Word, String Candidate, double Similarity) // { // this.word=Word; // this.candidate=Candidate; // this.similarity=Similarity; // } // }
import java.io.IOException; import java.util.List; import unsw.curation.api.domain.ExtractTextSimilarity;
package unsw.curation.api.domain.abstraction; public interface ITextLevenshtainSimilarity {
// Path: src/main/java/unsw/curation/api/domain/ExtractTextSimilarity.java // public class ExtractTextSimilarity { // // private String word; // public void setWord(String word) // { // this.word=word; // } // public String getWord() // { // return this.word; // } // private String candidate; // public void setCandidate(String candidate) // { // this.candidate=candidate; // } // public String getCandidate() // { // return this.candidate; // } // private double similarity; // public void setSimilarity(double similarity) // { // this.similarity=similarity; // } // public double getSimilarity() // { // return this.similarity; // } // public ExtractTextSimilarity(){} // public ExtractTextSimilarity (String Word, String Candidate, double Similarity) // { // this.word=Word; // this.candidate=Candidate; // this.similarity=Similarity; // } // } // Path: src/main/java/unsw/curation/api/domain/abstraction/ITextLevenshtainSimilarity.java import java.io.IOException; import java.util.List; import unsw.curation.api.domain.ExtractTextSimilarity; package unsw.curation.api.domain.abstraction; public interface ITextLevenshtainSimilarity {
List<ExtractTextSimilarity> Leveneshtain_Word_Document(String word1, String filePath) throws IOException;
unsw-cse-soc/Data-curation-API
src/main/java/unsw/curation/api/twitter/Synonyms.java
// Path: src/main/java/unsw/curation/api/twitterdomain/SynonymDomain.java // public class SynonymDomain { // // public SynonymDomain(){} // public SynonymDomain(String word, String synset) // { // this.word=word; // this.synset=synset; // } // public String word; // public String synset; // // public void setWord(String word) // { // this.word=word; // } // public String getWord() // { // return this.word; // } // public void setSynset(String synset) // { // this.synset=synset; // } // public String getSynset() // { // return synset; // } // }
import edu.mit.jwi.Dictionary; import edu.mit.jwi.IDictionary; import edu.mit.jwi.item.IIndexWord; import edu.mit.jwi.item.ISynset; import edu.mit.jwi.item.IWord; import edu.mit.jwi.item.IWordID; import edu.mit.jwi.item.POS; import edu.mit.jwi.morph.WordnetStemmer; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import unsw.curation.api.twitterdomain.SynonymDomain;
package unsw.curation.api.twitter; /** * * @author Alireza */ public class Synonyms { KeywordExtraction EX; private String path="C:\\Program Files (x86)\\WordNet\\2.1\\dict\\"; public Synonyms() throws IOException { EX=new KeywordExtraction(); } public Synonyms(String dictionaryFilePath) throws IOException { path=dictionaryFilePath; EX=new KeywordExtraction(); }
// Path: src/main/java/unsw/curation/api/twitterdomain/SynonymDomain.java // public class SynonymDomain { // // public SynonymDomain(){} // public SynonymDomain(String word, String synset) // { // this.word=word; // this.synset=synset; // } // public String word; // public String synset; // // public void setWord(String word) // { // this.word=word; // } // public String getWord() // { // return this.word; // } // public void setSynset(String synset) // { // this.synset=synset; // } // public String getSynset() // { // return synset; // } // } // Path: src/main/java/unsw/curation/api/twitter/Synonyms.java import edu.mit.jwi.Dictionary; import edu.mit.jwi.IDictionary; import edu.mit.jwi.item.IIndexWord; import edu.mit.jwi.item.ISynset; import edu.mit.jwi.item.IWord; import edu.mit.jwi.item.IWordID; import edu.mit.jwi.item.POS; import edu.mit.jwi.morph.WordnetStemmer; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import unsw.curation.api.twitterdomain.SynonymDomain; package unsw.curation.api.twitter; /** * * @author Alireza */ public class Synonyms { KeywordExtraction EX; private String path="C:\\Program Files (x86)\\WordNet\\2.1\\dict\\"; public Synonyms() throws IOException { EX=new KeywordExtraction(); } public Synonyms(String dictionaryFilePath) throws IOException { path=dictionaryFilePath; EX=new KeywordExtraction(); }
public List<SynonymDomain> ExtractSynsetsSentence(String Sentence,File englishStopwordsFilePath) throws IOException, Exception
unsw-cse-soc/Data-curation-API
src/main/java/unsw/curation/api/extractnamedentity/ExtractEntitySentence.java
// Path: src/main/java/unsw/curation/api/domain/ExtractNamedEntity.java // public class ExtractNamedEntity { // // public ExtractNamedEntity() // { // // } // // public String word; // public String ner; // public int position; // /*public ExtractNamedEntity(String word,String ner) // { // this.word=word; // this.ner=ner; // }*/ // public ExtractNamedEntity(String word,String ner,int position) // { // this.word=word; // this.ner=ner; // this.position=position; // } // public int getPosition() { // return position; // } // public void setPosition(int position) { // this.position = position; // } // public void setWord(String word) // { // this.word=word; // } // public String getWord() // { // return this.word; // } // // public void setNer(String ner) // { // this.ner=ner; // } // public String getNer() // { // return this.ner; // } // } // // Path: src/main/java/unsw/curation/api/domain/abstraction/INamedEntity.java // public interface INamedEntity { // // List<ExtractNamedEntity>ExtractNamedEntityFile(File filePath) throws Exception; // //List<ExtractNamedEntity>ExtractNamedEntity(boolean useRegexNer,List<String> lstData) throws Exception; // List<ExtractNamedEntity> ExtractNamedEntitySentence(String inputSentence) throws Exception; // List<String> ExtractOrganization(String inputSentence) throws URISyntaxException, Exception; // List<String> ExtractPerson(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractLocation(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractDate(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractMoney(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractCity(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractState(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractCountry(String inputSentence)throws URISyntaxException, FileNotFoundException, IOException, Exception; // List<String> ExtractContinent(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractCrime(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractSport(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractHoliday(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractCompany(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractNaturalDisaster(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractDrug(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractProduct(String inputSentence)throws URISyntaxException, Exception; // //List<String> ExtractRadioProgram(String inputSentence)throws URISyntaxException, Exception; // //List<String> ExtractRadioStation(String inputSentence)throws URISyntaxException, Exception; // //List<String> ExtractTvShows(String inputSentence)throws URISyntaxException; // List<String> ExtractMedia(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractOperatingSystem(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractDegree(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractSportEvents(String inputSentence)throws URISyntaxException, Exception; // //List<String> ExtractRegion(String inputSentence)throws URISyntaxException; // //List<String> ExtractGeographicFeature(String inputSentence)throws URISyntaxException; // List<String> ReadRawData(File filePath) throws Exception; // // // // }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import unsw.curation.api.domain.ExtractNamedEntity; import unsw.curation.api.domain.abstraction.INamedEntity; import edu.stanford.nlp.ling.CoreAnnotations.NamedEntityTagAnnotation; import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation; import edu.stanford.nlp.ling.CoreAnnotations.TextAnnotation; import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.util.CoreMap;
package unsw.curation.api.extractnamedentity; public class ExtractEntitySentence implements INamedEntity { @Override
// Path: src/main/java/unsw/curation/api/domain/ExtractNamedEntity.java // public class ExtractNamedEntity { // // public ExtractNamedEntity() // { // // } // // public String word; // public String ner; // public int position; // /*public ExtractNamedEntity(String word,String ner) // { // this.word=word; // this.ner=ner; // }*/ // public ExtractNamedEntity(String word,String ner,int position) // { // this.word=word; // this.ner=ner; // this.position=position; // } // public int getPosition() { // return position; // } // public void setPosition(int position) { // this.position = position; // } // public void setWord(String word) // { // this.word=word; // } // public String getWord() // { // return this.word; // } // // public void setNer(String ner) // { // this.ner=ner; // } // public String getNer() // { // return this.ner; // } // } // // Path: src/main/java/unsw/curation/api/domain/abstraction/INamedEntity.java // public interface INamedEntity { // // List<ExtractNamedEntity>ExtractNamedEntityFile(File filePath) throws Exception; // //List<ExtractNamedEntity>ExtractNamedEntity(boolean useRegexNer,List<String> lstData) throws Exception; // List<ExtractNamedEntity> ExtractNamedEntitySentence(String inputSentence) throws Exception; // List<String> ExtractOrganization(String inputSentence) throws URISyntaxException, Exception; // List<String> ExtractPerson(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractLocation(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractDate(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractMoney(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractCity(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractState(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractCountry(String inputSentence)throws URISyntaxException, FileNotFoundException, IOException, Exception; // List<String> ExtractContinent(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractCrime(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractSport(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractHoliday(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractCompany(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractNaturalDisaster(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractDrug(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractProduct(String inputSentence)throws URISyntaxException, Exception; // //List<String> ExtractRadioProgram(String inputSentence)throws URISyntaxException, Exception; // //List<String> ExtractRadioStation(String inputSentence)throws URISyntaxException, Exception; // //List<String> ExtractTvShows(String inputSentence)throws URISyntaxException; // List<String> ExtractMedia(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractOperatingSystem(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractDegree(String inputSentence)throws URISyntaxException, Exception; // List<String> ExtractSportEvents(String inputSentence)throws URISyntaxException, Exception; // //List<String> ExtractRegion(String inputSentence)throws URISyntaxException; // //List<String> ExtractGeographicFeature(String inputSentence)throws URISyntaxException; // List<String> ReadRawData(File filePath) throws Exception; // // // // } // Path: src/main/java/unsw/curation/api/extractnamedentity/ExtractEntitySentence.java import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import unsw.curation.api.domain.ExtractNamedEntity; import unsw.curation.api.domain.abstraction.INamedEntity; import edu.stanford.nlp.ling.CoreAnnotations.NamedEntityTagAnnotation; import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation; import edu.stanford.nlp.ling.CoreAnnotations.TextAnnotation; import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.util.CoreMap; package unsw.curation.api.extractnamedentity; public class ExtractEntitySentence implements INamedEntity { @Override
public List<ExtractNamedEntity> ExtractNamedEntityFile(File filePath) throws Exception {
excelsior-oss/excelsior-jet-api
src/main/java/com/excelsiorjet/api/tasks/config/packagefile/PackageFile.java
// Path: src/main/java/com/excelsiorjet/api/tasks/JetTaskFailureException.java // public class JetTaskFailureException extends Exception { // // public JetTaskFailureException(String msg, Throwable throwable) { // super(msg, throwable); // } // // public JetTaskFailureException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // }
import java.io.File; import static com.excelsiorjet.api.util.Txt.s; import com.excelsiorjet.api.tasks.JetTaskFailureException;
public PackageFile(PackageFileType type, File path, String packagePath) { this.type = type.toString(); this.path = path; this.packagePath = packagePath; } public PackageFile(File path, String packagePath) { this.path = path; this.packagePath = packagePath; } public boolean isDefined() { return (path != null) || (packagePath != null); } /** * @return location of this file in the package including file name, or empty string if the file is not {@link #isDefined()}} */ public String getLocationInPackage() { if (!isDefined()) { return ""; } else if (path != null) { assert packagePath != null: "validate() must be called before"; return packagePath.endsWith("/") ? packagePath + path.getName() : packagePath + "/" + path.getName(); } else { return packagePath; } }
// Path: src/main/java/com/excelsiorjet/api/tasks/JetTaskFailureException.java // public class JetTaskFailureException extends Exception { // // public JetTaskFailureException(String msg, Throwable throwable) { // super(msg, throwable); // } // // public JetTaskFailureException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // } // Path: src/main/java/com/excelsiorjet/api/tasks/config/packagefile/PackageFile.java import java.io.File; import static com.excelsiorjet.api.util.Txt.s; import com.excelsiorjet.api.tasks.JetTaskFailureException; public PackageFile(PackageFileType type, File path, String packagePath) { this.type = type.toString(); this.path = path; this.packagePath = packagePath; } public PackageFile(File path, String packagePath) { this.path = path; this.packagePath = packagePath; } public boolean isDefined() { return (path != null) || (packagePath != null); } /** * @return location of this file in the package including file name, or empty string if the file is not {@link #isDefined()}} */ public String getLocationInPackage() { if (!isDefined()) { return ""; } else if (path != null) { assert packagePath != null: "validate() must be called before"; return packagePath.endsWith("/") ? packagePath + path.getName() : packagePath + "/" + path.getName(); } else { return packagePath; } }
public void validate(String notExistErrorKey, String errorParam) throws JetTaskFailureException {
excelsior-oss/excelsior-jet-api
src/main/java/com/excelsiorjet/api/tasks/config/packagefile/PackageFile.java
// Path: src/main/java/com/excelsiorjet/api/tasks/JetTaskFailureException.java // public class JetTaskFailureException extends Exception { // // public JetTaskFailureException(String msg, Throwable throwable) { // super(msg, throwable); // } // // public JetTaskFailureException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // }
import java.io.File; import static com.excelsiorjet.api.util.Txt.s; import com.excelsiorjet.api.tasks.JetTaskFailureException;
public PackageFile(File path, String packagePath) { this.path = path; this.packagePath = packagePath; } public boolean isDefined() { return (path != null) || (packagePath != null); } /** * @return location of this file in the package including file name, or empty string if the file is not {@link #isDefined()}} */ public String getLocationInPackage() { if (!isDefined()) { return ""; } else if (path != null) { assert packagePath != null: "validate() must be called before"; return packagePath.endsWith("/") ? packagePath + path.getName() : packagePath + "/" + path.getName(); } else { return packagePath; } } public void validate(String notExistErrorKey, String errorParam) throws JetTaskFailureException { if (!isDefined()) return; if (path != null) { if (!path.exists()) {
// Path: src/main/java/com/excelsiorjet/api/tasks/JetTaskFailureException.java // public class JetTaskFailureException extends Exception { // // public JetTaskFailureException(String msg, Throwable throwable) { // super(msg, throwable); // } // // public JetTaskFailureException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // } // Path: src/main/java/com/excelsiorjet/api/tasks/config/packagefile/PackageFile.java import java.io.File; import static com.excelsiorjet.api.util.Txt.s; import com.excelsiorjet.api.tasks.JetTaskFailureException; public PackageFile(File path, String packagePath) { this.path = path; this.packagePath = packagePath; } public boolean isDefined() { return (path != null) || (packagePath != null); } /** * @return location of this file in the package including file name, or empty string if the file is not {@link #isDefined()}} */ public String getLocationInPackage() { if (!isDefined()) { return ""; } else if (path != null) { assert packagePath != null: "validate() must be called before"; return packagePath.endsWith("/") ? packagePath + path.getName() : packagePath + "/" + path.getName(); } else { return packagePath; } } public void validate(String notExistErrorKey, String errorParam) throws JetTaskFailureException { if (!isDefined()) return; if (path != null) { if (!path.exists()) {
throw new JetTaskFailureException(s(notExistErrorKey, path.getAbsolutePath(), errorParam));
excelsior-oss/excelsior-jet-api
src/test/java/com/excelsiorjet/api/tasks/RunStopSupportTest.java
// Path: src/test/java/com/excelsiorjet/TestUtils.java // public class TestUtils { // // static final String FAKE_JET_HOME = "FakeJetHome"; // // public static File workDir() { // try { // return new File(TestUtils.class.getResource("/").toURI()); // } catch (URISyntaxException e) { // fail(); // return null; // } // } // // public static File classesDir() { // try { // String utilsClass = "/" + Utils.class.getName().replace('.', '/') + ".class"; // String utilsFile = new File(Utils.class.getResource(utilsClass).toURI()).getAbsolutePath(); // return new File (utilsFile.substring(0, utilsFile.length() - utilsClass.length())); // } catch (URISyntaxException e) { // fail(); // return null; // } // } // // static File getFakeJetHomeNoCreate(){ // return new File(workDir(), FAKE_JET_HOME); // } // // static File getOrCreateFakeJetHome(String version){ // File fakeJetHome = getFakeJetHomeNoCreate(); // File fakeJetHomeBin = new File(fakeJetHome, "bin"); // if (new File(fakeJetHomeBin, "jet.config").exists()) { // return fakeJetHome; // } // fakeJetHome.mkdir(); // fakeJetHomeBin.mkdir(); // try { // new File(fakeJetHomeBin, "jet.config").createNewFile(); // new File(fakeJetHomeBin, "jet" + version + ".home").createNewFile(); // File jc = new File(fakeJetHomeBin, Host.mangleExeName(JetCompiler.JET_COMPILER)); // if (!jc.exists()) { // jc.createNewFile(); // } // File xpack = new File(fakeJetHomeBin, Host.mangleExeName(JetPackager.JET_PACKAGER)); // if (!xpack.exists()) { // xpack.createNewFile(); // } // } catch (IOException ignore) { // } // return fakeJetHome; // } // // static File getOrCreateFakeJetHome(){ // return getOrCreateFakeJetHome("1100"); // } // // public static void cleanFakeJetDir() { // Utils.cleanDirectorySilently(new File(workDir(), FAKE_JET_HOME)); // } // } // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public class Txt { // // private static Messages messages = new Messages("Strings"); // private static Messages altMessages; // public static Log log; // // public static void setAdditionalMessages(ResourceBundle rb) { // altMessages = new Messages(rb); // } // // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // } // }
import com.excelsiorjet.TestUtils; import com.excelsiorjet.api.util.Txt; import org.junit.Test; import java.io.File; import static org.junit.Assert.*;
package com.excelsiorjet.api.tasks; public class RunStopSupportTest { //1 min timeout private static int RUN_TIMEOUT = 60000; private RunStopSupport runStopSupport(boolean toStop) {
// Path: src/test/java/com/excelsiorjet/TestUtils.java // public class TestUtils { // // static final String FAKE_JET_HOME = "FakeJetHome"; // // public static File workDir() { // try { // return new File(TestUtils.class.getResource("/").toURI()); // } catch (URISyntaxException e) { // fail(); // return null; // } // } // // public static File classesDir() { // try { // String utilsClass = "/" + Utils.class.getName().replace('.', '/') + ".class"; // String utilsFile = new File(Utils.class.getResource(utilsClass).toURI()).getAbsolutePath(); // return new File (utilsFile.substring(0, utilsFile.length() - utilsClass.length())); // } catch (URISyntaxException e) { // fail(); // return null; // } // } // // static File getFakeJetHomeNoCreate(){ // return new File(workDir(), FAKE_JET_HOME); // } // // static File getOrCreateFakeJetHome(String version){ // File fakeJetHome = getFakeJetHomeNoCreate(); // File fakeJetHomeBin = new File(fakeJetHome, "bin"); // if (new File(fakeJetHomeBin, "jet.config").exists()) { // return fakeJetHome; // } // fakeJetHome.mkdir(); // fakeJetHomeBin.mkdir(); // try { // new File(fakeJetHomeBin, "jet.config").createNewFile(); // new File(fakeJetHomeBin, "jet" + version + ".home").createNewFile(); // File jc = new File(fakeJetHomeBin, Host.mangleExeName(JetCompiler.JET_COMPILER)); // if (!jc.exists()) { // jc.createNewFile(); // } // File xpack = new File(fakeJetHomeBin, Host.mangleExeName(JetPackager.JET_PACKAGER)); // if (!xpack.exists()) { // xpack.createNewFile(); // } // } catch (IOException ignore) { // } // return fakeJetHome; // } // // static File getOrCreateFakeJetHome(){ // return getOrCreateFakeJetHome("1100"); // } // // public static void cleanFakeJetDir() { // Utils.cleanDirectorySilently(new File(workDir(), FAKE_JET_HOME)); // } // } // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public class Txt { // // private static Messages messages = new Messages("Strings"); // private static Messages altMessages; // public static Log log; // // public static void setAdditionalMessages(ResourceBundle rb) { // altMessages = new Messages(rb); // } // // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // } // } // Path: src/test/java/com/excelsiorjet/api/tasks/RunStopSupportTest.java import com.excelsiorjet.TestUtils; import com.excelsiorjet.api.util.Txt; import org.junit.Test; import java.io.File; import static org.junit.Assert.*; package com.excelsiorjet.api.tasks; public class RunStopSupportTest { //1 min timeout private static int RUN_TIMEOUT = 60000; private RunStopSupport runStopSupport(boolean toStop) {
return new RunStopSupport(TestUtils.workDir(), toStop);
excelsior-oss/excelsior-jet-api
src/test/java/com/excelsiorjet/api/tasks/RunStopSupportTest.java
// Path: src/test/java/com/excelsiorjet/TestUtils.java // public class TestUtils { // // static final String FAKE_JET_HOME = "FakeJetHome"; // // public static File workDir() { // try { // return new File(TestUtils.class.getResource("/").toURI()); // } catch (URISyntaxException e) { // fail(); // return null; // } // } // // public static File classesDir() { // try { // String utilsClass = "/" + Utils.class.getName().replace('.', '/') + ".class"; // String utilsFile = new File(Utils.class.getResource(utilsClass).toURI()).getAbsolutePath(); // return new File (utilsFile.substring(0, utilsFile.length() - utilsClass.length())); // } catch (URISyntaxException e) { // fail(); // return null; // } // } // // static File getFakeJetHomeNoCreate(){ // return new File(workDir(), FAKE_JET_HOME); // } // // static File getOrCreateFakeJetHome(String version){ // File fakeJetHome = getFakeJetHomeNoCreate(); // File fakeJetHomeBin = new File(fakeJetHome, "bin"); // if (new File(fakeJetHomeBin, "jet.config").exists()) { // return fakeJetHome; // } // fakeJetHome.mkdir(); // fakeJetHomeBin.mkdir(); // try { // new File(fakeJetHomeBin, "jet.config").createNewFile(); // new File(fakeJetHomeBin, "jet" + version + ".home").createNewFile(); // File jc = new File(fakeJetHomeBin, Host.mangleExeName(JetCompiler.JET_COMPILER)); // if (!jc.exists()) { // jc.createNewFile(); // } // File xpack = new File(fakeJetHomeBin, Host.mangleExeName(JetPackager.JET_PACKAGER)); // if (!xpack.exists()) { // xpack.createNewFile(); // } // } catch (IOException ignore) { // } // return fakeJetHome; // } // // static File getOrCreateFakeJetHome(){ // return getOrCreateFakeJetHome("1100"); // } // // public static void cleanFakeJetDir() { // Utils.cleanDirectorySilently(new File(workDir(), FAKE_JET_HOME)); // } // } // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public class Txt { // // private static Messages messages = new Messages("Strings"); // private static Messages altMessages; // public static Log log; // // public static void setAdditionalMessages(ResourceBundle rb) { // altMessages = new Messages(rb); // } // // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // } // }
import com.excelsiorjet.TestUtils; import com.excelsiorjet.api.util.Txt; import org.junit.Test; import java.io.File; import static org.junit.Assert.*;
//kill first task stopTask(runTask1); } @Test public void middleDies() { RunTask runTask1 = runTask(); RunTask runTask2 = runTask(100); RunTask runTask3 = runTask(); //wait until second task dies; runTask2.join(RUN_TIMEOUT); assertTrue(runTask2.isCompleted()); assertFalse(runTask3.isCompleted()); //kill 3d task stopTask(runTask3); assertFalse(runTask1.isCompleted()); //kill first task stopTask(runTask1); assertTrue(runTask1.isCompleted()); } @Test public void stopNoRun() { try { runStopSupport(true).stopRunTask(); fail("Stopped task without run"); } catch (JetTaskFailureException e) {
// Path: src/test/java/com/excelsiorjet/TestUtils.java // public class TestUtils { // // static final String FAKE_JET_HOME = "FakeJetHome"; // // public static File workDir() { // try { // return new File(TestUtils.class.getResource("/").toURI()); // } catch (URISyntaxException e) { // fail(); // return null; // } // } // // public static File classesDir() { // try { // String utilsClass = "/" + Utils.class.getName().replace('.', '/') + ".class"; // String utilsFile = new File(Utils.class.getResource(utilsClass).toURI()).getAbsolutePath(); // return new File (utilsFile.substring(0, utilsFile.length() - utilsClass.length())); // } catch (URISyntaxException e) { // fail(); // return null; // } // } // // static File getFakeJetHomeNoCreate(){ // return new File(workDir(), FAKE_JET_HOME); // } // // static File getOrCreateFakeJetHome(String version){ // File fakeJetHome = getFakeJetHomeNoCreate(); // File fakeJetHomeBin = new File(fakeJetHome, "bin"); // if (new File(fakeJetHomeBin, "jet.config").exists()) { // return fakeJetHome; // } // fakeJetHome.mkdir(); // fakeJetHomeBin.mkdir(); // try { // new File(fakeJetHomeBin, "jet.config").createNewFile(); // new File(fakeJetHomeBin, "jet" + version + ".home").createNewFile(); // File jc = new File(fakeJetHomeBin, Host.mangleExeName(JetCompiler.JET_COMPILER)); // if (!jc.exists()) { // jc.createNewFile(); // } // File xpack = new File(fakeJetHomeBin, Host.mangleExeName(JetPackager.JET_PACKAGER)); // if (!xpack.exists()) { // xpack.createNewFile(); // } // } catch (IOException ignore) { // } // return fakeJetHome; // } // // static File getOrCreateFakeJetHome(){ // return getOrCreateFakeJetHome("1100"); // } // // public static void cleanFakeJetDir() { // Utils.cleanDirectorySilently(new File(workDir(), FAKE_JET_HOME)); // } // } // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public class Txt { // // private static Messages messages = new Messages("Strings"); // private static Messages altMessages; // public static Log log; // // public static void setAdditionalMessages(ResourceBundle rb) { // altMessages = new Messages(rb); // } // // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // } // } // Path: src/test/java/com/excelsiorjet/api/tasks/RunStopSupportTest.java import com.excelsiorjet.TestUtils; import com.excelsiorjet.api.util.Txt; import org.junit.Test; import java.io.File; import static org.junit.Assert.*; //kill first task stopTask(runTask1); } @Test public void middleDies() { RunTask runTask1 = runTask(); RunTask runTask2 = runTask(100); RunTask runTask3 = runTask(); //wait until second task dies; runTask2.join(RUN_TIMEOUT); assertTrue(runTask2.isCompleted()); assertFalse(runTask3.isCompleted()); //kill 3d task stopTask(runTask3); assertFalse(runTask1.isCompleted()); //kill first task stopTask(runTask1); assertTrue(runTask1.isCompleted()); } @Test public void stopNoRun() { try { runStopSupport(true).stopRunTask(); fail("Stopped task without run"); } catch (JetTaskFailureException e) {
assertEquals(e.getMessage(), Txt.s("StopTask.NoRunApp.Error"));
excelsior-oss/excelsior-jet-api
src/main/java/com/excelsiorjet/api/util/Txt.java
// Path: src/main/java/com/excelsiorjet/api/log/Log.java // public abstract class Log { // // public static Log logger; // // /** // * Should print given msg and exception with debug level // */ // public abstract void debug(String msg, Throwable t); // // /** // * Should print given msg with info level // */ // public abstract void info(String msg); // // /** // * Should print given msg with warn level // */ // public abstract void warn(String msg); // // /** // * Should print given msg and exception with warn level // */ // public abstract void warn(String msg, Throwable t); // // /** // * Should print given msg with error level // */ // public abstract void error(String msg); // // }
import java.util.ResourceBundle; import com.excelsiorjet.api.log.Log;
/* * Copyright (c) 2015, Excelsior LLC. * * This file is part of Excelsior JET API. * * Excelsior JET API is free software: * you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Excelsior JET API is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Excelsior JET API. * If not, see <http://www.gnu.org/licenses/>. * */ package com.excelsiorjet.api.util; /** * @author Nikita Lipsky */ public class Txt { private static Messages messages = new Messages("Strings"); private static Messages altMessages;
// Path: src/main/java/com/excelsiorjet/api/log/Log.java // public abstract class Log { // // public static Log logger; // // /** // * Should print given msg and exception with debug level // */ // public abstract void debug(String msg, Throwable t); // // /** // * Should print given msg with info level // */ // public abstract void info(String msg); // // /** // * Should print given msg with warn level // */ // public abstract void warn(String msg); // // /** // * Should print given msg and exception with warn level // */ // public abstract void warn(String msg, Throwable t); // // /** // * Should print given msg with error level // */ // public abstract void error(String msg); // // } // Path: src/main/java/com/excelsiorjet/api/util/Txt.java import java.util.ResourceBundle; import com.excelsiorjet.api.log.Log; /* * Copyright (c) 2015, Excelsior LLC. * * This file is part of Excelsior JET API. * * Excelsior JET API is free software: * you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Excelsior JET API is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Excelsior JET API. * If not, see <http://www.gnu.org/licenses/>. * */ package com.excelsiorjet.api.util; /** * @author Nikita Lipsky */ public class Txt { private static Messages messages = new Messages("Strings"); private static Messages altMessages;
public static Log log;
excelsior-oss/excelsior-jet-api
src/main/java/com/excelsiorjet/api/util/Utils.java
// Path: src/main/java/com/excelsiorjet/api/platform/Host.java // public class Host { // // private static final OS hostOS; // // static { // //detect Host OS // String osName = System.getProperty("os.name"); // if (osName.contains("Windows")) { // hostOS = OS.WINDOWS; // } else if (osName.contains("Linux")) { // hostOS = OS.LINUX; // } else if (osName.contains("OS X")) { // hostOS = OS.OSX; // } else { // throw new AssertionError("Unknown OS: " + osName); // } // } // // public static boolean isWindows() { // return hostOS.isWindows(); // } // // public static boolean isLinux() { // return hostOS.isLinux(); // } // // public static boolean isOSX() { // return hostOS.isOSX(); // } // // public static boolean isUnix() { // return hostOS.isUnix(); // } // // public static String mangleExeName(String exe) { // return hostOS.mangleExeName(exe); // } // // public static OS getOS() { // return hostOS; // } // } // // Path: src/main/java/com/excelsiorjet/api/tasks/JetTaskFailureException.java // public class JetTaskFailureException extends Exception { // // public JetTaskFailureException(String msg, Throwable throwable) { // super(msg, throwable); // } // // public JetTaskFailureException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/excelsiorjet/api/log/Log.java // public static Log logger; // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // }
import com.excelsiorjet.api.platform.Host; import com.excelsiorjet.api.tasks.JetTaskFailureException; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.excelsiorjet.api.log.Log.logger; import static com.excelsiorjet.api.util.Txt.s;
/* * Copyright (c) 2015-2017, Excelsior LLC. * * This file is part of Excelsior JET API. * * Excelsior JET API is free software: * you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Excelsior JET API is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Excelsior JET API. * If not, see <http://www.gnu.org/licenses/>. * */ package com.excelsiorjet.api.util; public class Utils { public static void cleanDirectory(File f) throws IOException { Files.walkFileTree(f.toPath(), new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } private void deleteFile(File f) throws IOException { if (!f.delete()) { if (f.exists()) {
// Path: src/main/java/com/excelsiorjet/api/platform/Host.java // public class Host { // // private static final OS hostOS; // // static { // //detect Host OS // String osName = System.getProperty("os.name"); // if (osName.contains("Windows")) { // hostOS = OS.WINDOWS; // } else if (osName.contains("Linux")) { // hostOS = OS.LINUX; // } else if (osName.contains("OS X")) { // hostOS = OS.OSX; // } else { // throw new AssertionError("Unknown OS: " + osName); // } // } // // public static boolean isWindows() { // return hostOS.isWindows(); // } // // public static boolean isLinux() { // return hostOS.isLinux(); // } // // public static boolean isOSX() { // return hostOS.isOSX(); // } // // public static boolean isUnix() { // return hostOS.isUnix(); // } // // public static String mangleExeName(String exe) { // return hostOS.mangleExeName(exe); // } // // public static OS getOS() { // return hostOS; // } // } // // Path: src/main/java/com/excelsiorjet/api/tasks/JetTaskFailureException.java // public class JetTaskFailureException extends Exception { // // public JetTaskFailureException(String msg, Throwable throwable) { // super(msg, throwable); // } // // public JetTaskFailureException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/excelsiorjet/api/log/Log.java // public static Log logger; // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // } // Path: src/main/java/com/excelsiorjet/api/util/Utils.java import com.excelsiorjet.api.platform.Host; import com.excelsiorjet.api.tasks.JetTaskFailureException; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.excelsiorjet.api.log.Log.logger; import static com.excelsiorjet.api.util.Txt.s; /* * Copyright (c) 2015-2017, Excelsior LLC. * * This file is part of Excelsior JET API. * * Excelsior JET API is free software: * you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Excelsior JET API is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Excelsior JET API. * If not, see <http://www.gnu.org/licenses/>. * */ package com.excelsiorjet.api.util; public class Utils { public static void cleanDirectory(File f) throws IOException { Files.walkFileTree(f.toPath(), new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } private void deleteFile(File f) throws IOException { if (!f.delete()) { if (f.exists()) {
throw new IOException(Txt.s("JetApi.UnableToDelete.Error", f.getAbsolutePath()));
excelsior-oss/excelsior-jet-api
src/main/java/com/excelsiorjet/api/util/Utils.java
// Path: src/main/java/com/excelsiorjet/api/platform/Host.java // public class Host { // // private static final OS hostOS; // // static { // //detect Host OS // String osName = System.getProperty("os.name"); // if (osName.contains("Windows")) { // hostOS = OS.WINDOWS; // } else if (osName.contains("Linux")) { // hostOS = OS.LINUX; // } else if (osName.contains("OS X")) { // hostOS = OS.OSX; // } else { // throw new AssertionError("Unknown OS: " + osName); // } // } // // public static boolean isWindows() { // return hostOS.isWindows(); // } // // public static boolean isLinux() { // return hostOS.isLinux(); // } // // public static boolean isOSX() { // return hostOS.isOSX(); // } // // public static boolean isUnix() { // return hostOS.isUnix(); // } // // public static String mangleExeName(String exe) { // return hostOS.mangleExeName(exe); // } // // public static OS getOS() { // return hostOS; // } // } // // Path: src/main/java/com/excelsiorjet/api/tasks/JetTaskFailureException.java // public class JetTaskFailureException extends Exception { // // public JetTaskFailureException(String msg, Throwable throwable) { // super(msg, throwable); // } // // public JetTaskFailureException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/excelsiorjet/api/log/Log.java // public static Log logger; // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // }
import com.excelsiorjet.api.platform.Host; import com.excelsiorjet.api.tasks.JetTaskFailureException; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.excelsiorjet.api.log.Log.logger; import static com.excelsiorjet.api.util.Txt.s;
}); } public static boolean isEmpty(String s) { return (s == null) || s.isEmpty(); } public static boolean isEmpty(String[] strings) { return (strings == null) || (strings.length == 0); } public static String randomAlphanumeric(int count) { char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; StringBuilder res = new StringBuilder(); for (int i = 0; i < count; i++) { res.append(chars[(int) (chars.length * Math.random())]); } return res.toString(); } public static void copy(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024 * 1024]; int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } }
// Path: src/main/java/com/excelsiorjet/api/platform/Host.java // public class Host { // // private static final OS hostOS; // // static { // //detect Host OS // String osName = System.getProperty("os.name"); // if (osName.contains("Windows")) { // hostOS = OS.WINDOWS; // } else if (osName.contains("Linux")) { // hostOS = OS.LINUX; // } else if (osName.contains("OS X")) { // hostOS = OS.OSX; // } else { // throw new AssertionError("Unknown OS: " + osName); // } // } // // public static boolean isWindows() { // return hostOS.isWindows(); // } // // public static boolean isLinux() { // return hostOS.isLinux(); // } // // public static boolean isOSX() { // return hostOS.isOSX(); // } // // public static boolean isUnix() { // return hostOS.isUnix(); // } // // public static String mangleExeName(String exe) { // return hostOS.mangleExeName(exe); // } // // public static OS getOS() { // return hostOS; // } // } // // Path: src/main/java/com/excelsiorjet/api/tasks/JetTaskFailureException.java // public class JetTaskFailureException extends Exception { // // public JetTaskFailureException(String msg, Throwable throwable) { // super(msg, throwable); // } // // public JetTaskFailureException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/excelsiorjet/api/log/Log.java // public static Log logger; // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // } // Path: src/main/java/com/excelsiorjet/api/util/Utils.java import com.excelsiorjet.api.platform.Host; import com.excelsiorjet.api.tasks.JetTaskFailureException; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.excelsiorjet.api.log.Log.logger; import static com.excelsiorjet.api.util.Txt.s; }); } public static boolean isEmpty(String s) { return (s == null) || s.isEmpty(); } public static boolean isEmpty(String[] strings) { return (strings == null) || (strings.length == 0); } public static String randomAlphanumeric(int count) { char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; StringBuilder res = new StringBuilder(); for (int i = 0; i < count; i++) { res.append(chars[(int) (chars.length * Math.random())]); } return res.toString(); } public static void copy(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024 * 1024]; int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } }
public static void mkdir(File dir) throws JetTaskFailureException {
excelsior-oss/excelsior-jet-api
src/main/java/com/excelsiorjet/api/util/Utils.java
// Path: src/main/java/com/excelsiorjet/api/platform/Host.java // public class Host { // // private static final OS hostOS; // // static { // //detect Host OS // String osName = System.getProperty("os.name"); // if (osName.contains("Windows")) { // hostOS = OS.WINDOWS; // } else if (osName.contains("Linux")) { // hostOS = OS.LINUX; // } else if (osName.contains("OS X")) { // hostOS = OS.OSX; // } else { // throw new AssertionError("Unknown OS: " + osName); // } // } // // public static boolean isWindows() { // return hostOS.isWindows(); // } // // public static boolean isLinux() { // return hostOS.isLinux(); // } // // public static boolean isOSX() { // return hostOS.isOSX(); // } // // public static boolean isUnix() { // return hostOS.isUnix(); // } // // public static String mangleExeName(String exe) { // return hostOS.mangleExeName(exe); // } // // public static OS getOS() { // return hostOS; // } // } // // Path: src/main/java/com/excelsiorjet/api/tasks/JetTaskFailureException.java // public class JetTaskFailureException extends Exception { // // public JetTaskFailureException(String msg, Throwable throwable) { // super(msg, throwable); // } // // public JetTaskFailureException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/excelsiorjet/api/log/Log.java // public static Log logger; // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // }
import com.excelsiorjet.api.platform.Host; import com.excelsiorjet.api.tasks.JetTaskFailureException; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.excelsiorjet.api.log.Log.logger; import static com.excelsiorjet.api.util.Txt.s;
} public static boolean isEmpty(String[] strings) { return (strings == null) || (strings.length == 0); } public static String randomAlphanumeric(int count) { char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; StringBuilder res = new StringBuilder(); for (int i = 0; i < count; i++) { res.append(chars[(int) (chars.length * Math.random())]); } return res.toString(); } public static void copy(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024 * 1024]; int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } public static void mkdir(File dir) throws JetTaskFailureException { if (!dir.exists() && !dir.mkdirs()) { if (!dir.exists()) { throw new JetTaskFailureException(s("JetApi.DirCreate.Error", dir.getAbsolutePath())); }
// Path: src/main/java/com/excelsiorjet/api/platform/Host.java // public class Host { // // private static final OS hostOS; // // static { // //detect Host OS // String osName = System.getProperty("os.name"); // if (osName.contains("Windows")) { // hostOS = OS.WINDOWS; // } else if (osName.contains("Linux")) { // hostOS = OS.LINUX; // } else if (osName.contains("OS X")) { // hostOS = OS.OSX; // } else { // throw new AssertionError("Unknown OS: " + osName); // } // } // // public static boolean isWindows() { // return hostOS.isWindows(); // } // // public static boolean isLinux() { // return hostOS.isLinux(); // } // // public static boolean isOSX() { // return hostOS.isOSX(); // } // // public static boolean isUnix() { // return hostOS.isUnix(); // } // // public static String mangleExeName(String exe) { // return hostOS.mangleExeName(exe); // } // // public static OS getOS() { // return hostOS; // } // } // // Path: src/main/java/com/excelsiorjet/api/tasks/JetTaskFailureException.java // public class JetTaskFailureException extends Exception { // // public JetTaskFailureException(String msg, Throwable throwable) { // super(msg, throwable); // } // // public JetTaskFailureException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/excelsiorjet/api/log/Log.java // public static Log logger; // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // } // Path: src/main/java/com/excelsiorjet/api/util/Utils.java import com.excelsiorjet.api.platform.Host; import com.excelsiorjet.api.tasks.JetTaskFailureException; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.excelsiorjet.api.log.Log.logger; import static com.excelsiorjet.api.util.Txt.s; } public static boolean isEmpty(String[] strings) { return (strings == null) || (strings.length == 0); } public static String randomAlphanumeric(int count) { char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; StringBuilder res = new StringBuilder(); for (int i = 0; i < count; i++) { res.append(chars[(int) (chars.length * Math.random())]); } return res.toString(); } public static void copy(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024 * 1024]; int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } public static void mkdir(File dir) throws JetTaskFailureException { if (!dir.exists() && !dir.mkdirs()) { if (!dir.exists()) { throw new JetTaskFailureException(s("JetApi.DirCreate.Error", dir.getAbsolutePath())); }
logger.warn(s("JetApi.DirCreate.Warning", dir.getAbsolutePath()));
excelsior-oss/excelsior-jet-api
src/main/java/com/excelsiorjet/api/util/Utils.java
// Path: src/main/java/com/excelsiorjet/api/platform/Host.java // public class Host { // // private static final OS hostOS; // // static { // //detect Host OS // String osName = System.getProperty("os.name"); // if (osName.contains("Windows")) { // hostOS = OS.WINDOWS; // } else if (osName.contains("Linux")) { // hostOS = OS.LINUX; // } else if (osName.contains("OS X")) { // hostOS = OS.OSX; // } else { // throw new AssertionError("Unknown OS: " + osName); // } // } // // public static boolean isWindows() { // return hostOS.isWindows(); // } // // public static boolean isLinux() { // return hostOS.isLinux(); // } // // public static boolean isOSX() { // return hostOS.isOSX(); // } // // public static boolean isUnix() { // return hostOS.isUnix(); // } // // public static String mangleExeName(String exe) { // return hostOS.mangleExeName(exe); // } // // public static OS getOS() { // return hostOS; // } // } // // Path: src/main/java/com/excelsiorjet/api/tasks/JetTaskFailureException.java // public class JetTaskFailureException extends Exception { // // public JetTaskFailureException(String msg, Throwable throwable) { // super(msg, throwable); // } // // public JetTaskFailureException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/excelsiorjet/api/log/Log.java // public static Log logger; // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // }
import com.excelsiorjet.api.platform.Host; import com.excelsiorjet.api.tasks.JetTaskFailureException; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.excelsiorjet.api.log.Log.logger; import static com.excelsiorjet.api.util.Txt.s;
for (int i = 0; i < count; i++) { res.append(chars[(int) (chars.length * Math.random())]); } return res.toString(); } public static void copy(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024 * 1024]; int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } public static void mkdir(File dir) throws JetTaskFailureException { if (!dir.exists() && !dir.mkdirs()) { if (!dir.exists()) { throw new JetTaskFailureException(s("JetApi.DirCreate.Error", dir.getAbsolutePath())); } logger.warn(s("JetApi.DirCreate.Warning", dir.getAbsolutePath())); } } @FunctionalInterface private interface CreateArchiveEntry { ArchiveEntry createEntry(String name, long size, int mode); } private static ArchiveEntry createZipEntry(String name, long size, int mode) { ZipArchiveEntry entry = new ZipArchiveEntry(name);
// Path: src/main/java/com/excelsiorjet/api/platform/Host.java // public class Host { // // private static final OS hostOS; // // static { // //detect Host OS // String osName = System.getProperty("os.name"); // if (osName.contains("Windows")) { // hostOS = OS.WINDOWS; // } else if (osName.contains("Linux")) { // hostOS = OS.LINUX; // } else if (osName.contains("OS X")) { // hostOS = OS.OSX; // } else { // throw new AssertionError("Unknown OS: " + osName); // } // } // // public static boolean isWindows() { // return hostOS.isWindows(); // } // // public static boolean isLinux() { // return hostOS.isLinux(); // } // // public static boolean isOSX() { // return hostOS.isOSX(); // } // // public static boolean isUnix() { // return hostOS.isUnix(); // } // // public static String mangleExeName(String exe) { // return hostOS.mangleExeName(exe); // } // // public static OS getOS() { // return hostOS; // } // } // // Path: src/main/java/com/excelsiorjet/api/tasks/JetTaskFailureException.java // public class JetTaskFailureException extends Exception { // // public JetTaskFailureException(String msg, Throwable throwable) { // super(msg, throwable); // } // // public JetTaskFailureException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/excelsiorjet/api/log/Log.java // public static Log logger; // // Path: src/main/java/com/excelsiorjet/api/util/Txt.java // public static String s(String id, Object... params) { // String str = null; // if (altMessages != null) { // str = altMessages.format(id, params); // } // if (str == null) { // str = messages.format(id, params); // } // if (str != null) { // return str; // } else { // if (log != null) { // log.error("JET message file broken: key = " + id); // } else { // throw new IllegalStateException("No log to issue error. JET message file broken: key = " + id); // } // return id; // } // } // Path: src/main/java/com/excelsiorjet/api/util/Utils.java import com.excelsiorjet.api.platform.Host; import com.excelsiorjet.api.tasks.JetTaskFailureException; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.excelsiorjet.api.log.Log.logger; import static com.excelsiorjet.api.util.Txt.s; for (int i = 0; i < count; i++) { res.append(chars[(int) (chars.length * Math.random())]); } return res.toString(); } public static void copy(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024 * 1024]; int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } public static void mkdir(File dir) throws JetTaskFailureException { if (!dir.exists() && !dir.mkdirs()) { if (!dir.exists()) { throw new JetTaskFailureException(s("JetApi.DirCreate.Error", dir.getAbsolutePath())); } logger.warn(s("JetApi.DirCreate.Warning", dir.getAbsolutePath())); } } @FunctionalInterface private interface CreateArchiveEntry { ArchiveEntry createEntry(String name, long size, int mode); } private static ArchiveEntry createZipEntry(String name, long size, int mode) { ZipArchiveEntry entry = new ZipArchiveEntry(name);
if (Host.isUnix()) {
excelsior-oss/excelsior-jet-api
src/test/java/com/excelsiorjet/EncodingDetectorTest.java
// Path: src/main/java/com/excelsiorjet/api/util/EncodingDetector.java // public class EncodingDetector { // // private static final byte[] UTF_32BE_BOM = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0xFE, (byte) 0xFF}; // private static final byte[] UTF_32LE_BOM = new byte[]{(byte) 0xFF, (byte) 0xFE, (byte) 0x00, (byte) 0x00}; // // private static final byte[] UTF_8_BOM = new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}; // // private static final byte[] UTF_16BE_BOM = new byte[]{(byte) 0xFE, (byte) 0xFF}; // private static final byte[] UTF_16LE_BOM = new byte[]{(byte) 0xFF, (byte) 0xFE}; // // // public static String detectEncoding(File eula) throws IOException { // // try (InputStream is = new FileInputStream(eula)) { // byte[] bom = readBytes(is, 4); // return detectEncodingByBom(bom).name(); // } // } // // /** // * Tries to recognize bom bytes. If UTF-8 bom bytes or no bom bytes recognized returns US-ASCII charset, otherwise // * returns corresponding UTF-16/32 charset // */ // private static Charset detectEncodingByBom(byte[] fileBomBytes) { // // should be ordered descending by corresponding bom bytes length // if (startsWith(fileBomBytes, UTF_32BE_BOM)) return Charset.forName("UTF-32BE"); // else if (startsWith(fileBomBytes, UTF_32LE_BOM)) return Charset.forName("UTF-32LE"); // else if (startsWith(fileBomBytes, UTF_8_BOM)) return StandardCharsets.UTF_8; // else if (startsWith(fileBomBytes, UTF_16BE_BOM)) return StandardCharsets.UTF_16BE; // else if (startsWith(fileBomBytes, UTF_16LE_BOM)) return StandardCharsets.UTF_16LE; // else return StandardCharsets.US_ASCII; // } // // private static boolean startsWith(byte[] array, byte[] prefix) { // int len = Math.min(array.length, prefix.length); // for (int i = 0; i < len; i++) { // if (array[i] != prefix[i]) { // return false; // } // } // return true; // } // // private static byte[] readBytes(InputStream is, int count) throws IOException { // byte[] res = new byte[count]; // is.read(res); // return res; // } // }
import com.excelsiorjet.api.util.EncodingDetector; import org.junit.Test; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import static org.junit.Assert.assertEquals;
testFile(StandardCharsets.UTF_8.name(), "/com/excelsiorjet/eula-utf8.txt"); } @Test public void testUTF16BE() throws Exception { testFile(StandardCharsets.UTF_16BE.name(), "/com/excelsiorjet/eula-utf16be.txt"); } @Test public void testUTF16LE() throws Exception { testFile(StandardCharsets.UTF_16LE.name(), "/com/excelsiorjet/eula-utf16le.txt"); } @Test public void testUTF32BE() throws Exception { testFile(Charset.forName("UTF-32BE").name(), "/com/excelsiorjet/eula-utf32be.txt"); } @Test public void testUTF32LE() throws Exception { testFile(Charset.forName("UTF-32LE").name(), "/com/excelsiorjet/eula-utf32le.txt"); } @Test public void testOneByte() throws Exception { testFile(StandardCharsets.US_ASCII.name(), "/com/excelsiorjet/eula-one-byte.txt"); } private void testFile(String expectedEncoding, String filePath) throws URISyntaxException, IOException { File eula = Paths.get(getClass().getResource(filePath).toURI()).toFile();
// Path: src/main/java/com/excelsiorjet/api/util/EncodingDetector.java // public class EncodingDetector { // // private static final byte[] UTF_32BE_BOM = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0xFE, (byte) 0xFF}; // private static final byte[] UTF_32LE_BOM = new byte[]{(byte) 0xFF, (byte) 0xFE, (byte) 0x00, (byte) 0x00}; // // private static final byte[] UTF_8_BOM = new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}; // // private static final byte[] UTF_16BE_BOM = new byte[]{(byte) 0xFE, (byte) 0xFF}; // private static final byte[] UTF_16LE_BOM = new byte[]{(byte) 0xFF, (byte) 0xFE}; // // // public static String detectEncoding(File eula) throws IOException { // // try (InputStream is = new FileInputStream(eula)) { // byte[] bom = readBytes(is, 4); // return detectEncodingByBom(bom).name(); // } // } // // /** // * Tries to recognize bom bytes. If UTF-8 bom bytes or no bom bytes recognized returns US-ASCII charset, otherwise // * returns corresponding UTF-16/32 charset // */ // private static Charset detectEncodingByBom(byte[] fileBomBytes) { // // should be ordered descending by corresponding bom bytes length // if (startsWith(fileBomBytes, UTF_32BE_BOM)) return Charset.forName("UTF-32BE"); // else if (startsWith(fileBomBytes, UTF_32LE_BOM)) return Charset.forName("UTF-32LE"); // else if (startsWith(fileBomBytes, UTF_8_BOM)) return StandardCharsets.UTF_8; // else if (startsWith(fileBomBytes, UTF_16BE_BOM)) return StandardCharsets.UTF_16BE; // else if (startsWith(fileBomBytes, UTF_16LE_BOM)) return StandardCharsets.UTF_16LE; // else return StandardCharsets.US_ASCII; // } // // private static boolean startsWith(byte[] array, byte[] prefix) { // int len = Math.min(array.length, prefix.length); // for (int i = 0; i < len; i++) { // if (array[i] != prefix[i]) { // return false; // } // } // return true; // } // // private static byte[] readBytes(InputStream is, int count) throws IOException { // byte[] res = new byte[count]; // is.read(res); // return res; // } // } // Path: src/test/java/com/excelsiorjet/EncodingDetectorTest.java import com.excelsiorjet.api.util.EncodingDetector; import org.junit.Test; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; testFile(StandardCharsets.UTF_8.name(), "/com/excelsiorjet/eula-utf8.txt"); } @Test public void testUTF16BE() throws Exception { testFile(StandardCharsets.UTF_16BE.name(), "/com/excelsiorjet/eula-utf16be.txt"); } @Test public void testUTF16LE() throws Exception { testFile(StandardCharsets.UTF_16LE.name(), "/com/excelsiorjet/eula-utf16le.txt"); } @Test public void testUTF32BE() throws Exception { testFile(Charset.forName("UTF-32BE").name(), "/com/excelsiorjet/eula-utf32be.txt"); } @Test public void testUTF32LE() throws Exception { testFile(Charset.forName("UTF-32LE").name(), "/com/excelsiorjet/eula-utf32le.txt"); } @Test public void testOneByte() throws Exception { testFile(StandardCharsets.US_ASCII.name(), "/com/excelsiorjet/eula-one-byte.txt"); } private void testFile(String expectedEncoding, String filePath) throws URISyntaxException, IOException { File eula = Paths.get(getClass().getResource(filePath).toURI()).toFile();
String encoding = EncodingDetector.detectEncoding(eula);
307509256/ijkplayer-android
android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/fragments/FileListFragment.java
// Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/content/PathCursorLoader.java // public class PathCursorLoader extends AsyncTaskLoader<Cursor> { // private File mPath; // // public PathCursorLoader(Context context) { // this(context, Environment.getExternalStorageDirectory()); // } // // public PathCursorLoader(Context context, String path) { // super(context); // mPath = new File(path).getAbsoluteFile(); // } // // public PathCursorLoader(Context context, File path) { // super(context); // mPath = path; // } // // @Override // public Cursor loadInBackground() { // File[] file_list = mPath.listFiles(); // return new PathCursor(mPath, file_list); // } // // @Override // protected void onStartLoading() { // forceLoad(); // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/eventbus/FileExplorerEvents.java // public class FileExplorerEvents { // private static final Bus BUS = new Bus(); // // public static Bus getBus() { // return BUS; // } // // private FileExplorerEvents() { // // No instances. // } // // public static class OnClickFile { // public File mFile; // // public OnClickFile(String path) { // this(new File(path)); // } // // public OnClickFile(File file) { // mFile = file; // } // } // }
import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v4.widget.SimpleCursorAdapter; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.io.File; import tv.danmaku.ijk.media.example.R; import tv.danmaku.ijk.media.example.content.PathCursor; import tv.danmaku.ijk.media.example.content.PathCursorLoader; import tv.danmaku.ijk.media.example.eventbus.FileExplorerEvents;
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_file_list, container, false); mPathView = (TextView) viewGroup.findViewById(R.id.path_view); mFileListView = (ListView) viewGroup.findViewById(R.id.file_list_view); mPathView.setVisibility(View.VISIBLE); return viewGroup; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Activity activity = getActivity(); Bundle bundle = getArguments(); if (bundle != null) { mPath = bundle.getString(ARG_PATH); mPath = new File(mPath).getAbsolutePath(); mPathView.setText(mPath); } mAdapter = new VideoAdapter(activity); mFileListView.setAdapter(mAdapter); mFileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, final long id) { String path = mAdapter.getFilePath(position); if (TextUtils.isEmpty(path)) return;
// Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/content/PathCursorLoader.java // public class PathCursorLoader extends AsyncTaskLoader<Cursor> { // private File mPath; // // public PathCursorLoader(Context context) { // this(context, Environment.getExternalStorageDirectory()); // } // // public PathCursorLoader(Context context, String path) { // super(context); // mPath = new File(path).getAbsoluteFile(); // } // // public PathCursorLoader(Context context, File path) { // super(context); // mPath = path; // } // // @Override // public Cursor loadInBackground() { // File[] file_list = mPath.listFiles(); // return new PathCursor(mPath, file_list); // } // // @Override // protected void onStartLoading() { // forceLoad(); // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/eventbus/FileExplorerEvents.java // public class FileExplorerEvents { // private static final Bus BUS = new Bus(); // // public static Bus getBus() { // return BUS; // } // // private FileExplorerEvents() { // // No instances. // } // // public static class OnClickFile { // public File mFile; // // public OnClickFile(String path) { // this(new File(path)); // } // // public OnClickFile(File file) { // mFile = file; // } // } // } // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/fragments/FileListFragment.java import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v4.widget.SimpleCursorAdapter; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.io.File; import tv.danmaku.ijk.media.example.R; import tv.danmaku.ijk.media.example.content.PathCursor; import tv.danmaku.ijk.media.example.content.PathCursorLoader; import tv.danmaku.ijk.media.example.eventbus.FileExplorerEvents; ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_file_list, container, false); mPathView = (TextView) viewGroup.findViewById(R.id.path_view); mFileListView = (ListView) viewGroup.findViewById(R.id.file_list_view); mPathView.setVisibility(View.VISIBLE); return viewGroup; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Activity activity = getActivity(); Bundle bundle = getArguments(); if (bundle != null) { mPath = bundle.getString(ARG_PATH); mPath = new File(mPath).getAbsolutePath(); mPathView.setText(mPath); } mAdapter = new VideoAdapter(activity); mFileListView.setAdapter(mAdapter); mFileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, final long id) { String path = mAdapter.getFilePath(position); if (TextUtils.isEmpty(path)) return;
FileExplorerEvents.getBus().post(new FileExplorerEvents.OnClickFile(path));
307509256/ijkplayer-android
android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/fragments/FileListFragment.java
// Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/content/PathCursorLoader.java // public class PathCursorLoader extends AsyncTaskLoader<Cursor> { // private File mPath; // // public PathCursorLoader(Context context) { // this(context, Environment.getExternalStorageDirectory()); // } // // public PathCursorLoader(Context context, String path) { // super(context); // mPath = new File(path).getAbsoluteFile(); // } // // public PathCursorLoader(Context context, File path) { // super(context); // mPath = path; // } // // @Override // public Cursor loadInBackground() { // File[] file_list = mPath.listFiles(); // return new PathCursor(mPath, file_list); // } // // @Override // protected void onStartLoading() { // forceLoad(); // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/eventbus/FileExplorerEvents.java // public class FileExplorerEvents { // private static final Bus BUS = new Bus(); // // public static Bus getBus() { // return BUS; // } // // private FileExplorerEvents() { // // No instances. // } // // public static class OnClickFile { // public File mFile; // // public OnClickFile(String path) { // this(new File(path)); // } // // public OnClickFile(File file) { // mFile = file; // } // } // }
import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v4.widget.SimpleCursorAdapter; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.io.File; import tv.danmaku.ijk.media.example.R; import tv.danmaku.ijk.media.example.content.PathCursor; import tv.danmaku.ijk.media.example.content.PathCursorLoader; import tv.danmaku.ijk.media.example.eventbus.FileExplorerEvents;
super.onActivityCreated(savedInstanceState); Activity activity = getActivity(); Bundle bundle = getArguments(); if (bundle != null) { mPath = bundle.getString(ARG_PATH); mPath = new File(mPath).getAbsolutePath(); mPathView.setText(mPath); } mAdapter = new VideoAdapter(activity); mFileListView.setAdapter(mAdapter); mFileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, final long id) { String path = mAdapter.getFilePath(position); if (TextUtils.isEmpty(path)) return; FileExplorerEvents.getBus().post(new FileExplorerEvents.OnClickFile(path)); } }); getLoaderManager().initLoader(1, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (TextUtils.isEmpty(mPath)) return null;
// Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/content/PathCursorLoader.java // public class PathCursorLoader extends AsyncTaskLoader<Cursor> { // private File mPath; // // public PathCursorLoader(Context context) { // this(context, Environment.getExternalStorageDirectory()); // } // // public PathCursorLoader(Context context, String path) { // super(context); // mPath = new File(path).getAbsoluteFile(); // } // // public PathCursorLoader(Context context, File path) { // super(context); // mPath = path; // } // // @Override // public Cursor loadInBackground() { // File[] file_list = mPath.listFiles(); // return new PathCursor(mPath, file_list); // } // // @Override // protected void onStartLoading() { // forceLoad(); // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/eventbus/FileExplorerEvents.java // public class FileExplorerEvents { // private static final Bus BUS = new Bus(); // // public static Bus getBus() { // return BUS; // } // // private FileExplorerEvents() { // // No instances. // } // // public static class OnClickFile { // public File mFile; // // public OnClickFile(String path) { // this(new File(path)); // } // // public OnClickFile(File file) { // mFile = file; // } // } // } // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/fragments/FileListFragment.java import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v4.widget.SimpleCursorAdapter; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.io.File; import tv.danmaku.ijk.media.example.R; import tv.danmaku.ijk.media.example.content.PathCursor; import tv.danmaku.ijk.media.example.content.PathCursorLoader; import tv.danmaku.ijk.media.example.eventbus.FileExplorerEvents; super.onActivityCreated(savedInstanceState); Activity activity = getActivity(); Bundle bundle = getArguments(); if (bundle != null) { mPath = bundle.getString(ARG_PATH); mPath = new File(mPath).getAbsolutePath(); mPathView.setText(mPath); } mAdapter = new VideoAdapter(activity); mFileListView.setAdapter(mAdapter); mFileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, final long id) { String path = mAdapter.getFilePath(position); if (TextUtils.isEmpty(path)) return; FileExplorerEvents.getBus().post(new FileExplorerEvents.OnClickFile(path)); } }); getLoaderManager().initLoader(1, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (TextUtils.isEmpty(mPath)) return null;
return new PathCursorLoader(getActivity(), mPath);
307509256/ijkplayer-android
android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/application/AppActivity.java
// Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/RecentMediaActivity.java // public class RecentMediaActivity extends AppActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, RecentMediaActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Fragment newFragment = RecentMediaListFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // boolean show = super.onPrepareOptionsMenu(menu); // if (!show) // return show; // // MenuItem item = menu.findItem(R.id.action_recent); // if (item != null) // item.setVisible(false); // // return true; // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/SampleMediaActivity.java // public class SampleMediaActivity extends AppActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, SampleMediaActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Fragment newFragment = SampleMediaListFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // boolean show = super.onPrepareOptionsMenu(menu); // if (!show) // return show; // // MenuItem item = menu.findItem(R.id.action_recent); // if (item != null) // item.setVisible(false); // // return true; // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/SettingsActivity.java // public class SettingsActivity extends AppCompatActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, SettingsActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_app); // // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // // Fragment newFragment = SettingsFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // }
import tv.danmaku.ijk.media.example.activities.SettingsActivity; import android.Manifest; import android.annotation.SuppressLint; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import tv.danmaku.ijk.media.example.R; import tv.danmaku.ijk.media.example.activities.RecentMediaActivity; import tv.danmaku.ijk.media.example.activities.SampleMediaActivity;
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); } } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the task you need to do. } else { // permission denied, boo! Disable the functionality that depends on this permission. } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_app, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) {
// Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/RecentMediaActivity.java // public class RecentMediaActivity extends AppActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, RecentMediaActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Fragment newFragment = RecentMediaListFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // boolean show = super.onPrepareOptionsMenu(menu); // if (!show) // return show; // // MenuItem item = menu.findItem(R.id.action_recent); // if (item != null) // item.setVisible(false); // // return true; // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/SampleMediaActivity.java // public class SampleMediaActivity extends AppActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, SampleMediaActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Fragment newFragment = SampleMediaListFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // boolean show = super.onPrepareOptionsMenu(menu); // if (!show) // return show; // // MenuItem item = menu.findItem(R.id.action_recent); // if (item != null) // item.setVisible(false); // // return true; // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/SettingsActivity.java // public class SettingsActivity extends AppCompatActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, SettingsActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_app); // // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // // Fragment newFragment = SettingsFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // } // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/application/AppActivity.java import tv.danmaku.ijk.media.example.activities.SettingsActivity; import android.Manifest; import android.annotation.SuppressLint; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import tv.danmaku.ijk.media.example.R; import tv.danmaku.ijk.media.example.activities.RecentMediaActivity; import tv.danmaku.ijk.media.example.activities.SampleMediaActivity; ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); } } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the task you need to do. } else { // permission denied, boo! Disable the functionality that depends on this permission. } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_app, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) {
SettingsActivity.intentTo(this);
307509256/ijkplayer-android
android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/application/AppActivity.java
// Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/RecentMediaActivity.java // public class RecentMediaActivity extends AppActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, RecentMediaActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Fragment newFragment = RecentMediaListFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // boolean show = super.onPrepareOptionsMenu(menu); // if (!show) // return show; // // MenuItem item = menu.findItem(R.id.action_recent); // if (item != null) // item.setVisible(false); // // return true; // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/SampleMediaActivity.java // public class SampleMediaActivity extends AppActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, SampleMediaActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Fragment newFragment = SampleMediaListFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // boolean show = super.onPrepareOptionsMenu(menu); // if (!show) // return show; // // MenuItem item = menu.findItem(R.id.action_recent); // if (item != null) // item.setVisible(false); // // return true; // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/SettingsActivity.java // public class SettingsActivity extends AppCompatActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, SettingsActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_app); // // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // // Fragment newFragment = SettingsFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // }
import tv.danmaku.ijk.media.example.activities.SettingsActivity; import android.Manifest; import android.annotation.SuppressLint; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import tv.danmaku.ijk.media.example.R; import tv.danmaku.ijk.media.example.activities.RecentMediaActivity; import tv.danmaku.ijk.media.example.activities.SampleMediaActivity;
} } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the task you need to do. } else { // permission denied, boo! Disable the functionality that depends on this permission. } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_app, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { SettingsActivity.intentTo(this); return true; } else if (id == R.id.action_recent) {
// Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/RecentMediaActivity.java // public class RecentMediaActivity extends AppActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, RecentMediaActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Fragment newFragment = RecentMediaListFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // boolean show = super.onPrepareOptionsMenu(menu); // if (!show) // return show; // // MenuItem item = menu.findItem(R.id.action_recent); // if (item != null) // item.setVisible(false); // // return true; // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/SampleMediaActivity.java // public class SampleMediaActivity extends AppActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, SampleMediaActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Fragment newFragment = SampleMediaListFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // boolean show = super.onPrepareOptionsMenu(menu); // if (!show) // return show; // // MenuItem item = menu.findItem(R.id.action_recent); // if (item != null) // item.setVisible(false); // // return true; // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/SettingsActivity.java // public class SettingsActivity extends AppCompatActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, SettingsActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_app); // // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // // Fragment newFragment = SettingsFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // } // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/application/AppActivity.java import tv.danmaku.ijk.media.example.activities.SettingsActivity; import android.Manifest; import android.annotation.SuppressLint; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import tv.danmaku.ijk.media.example.R; import tv.danmaku.ijk.media.example.activities.RecentMediaActivity; import tv.danmaku.ijk.media.example.activities.SampleMediaActivity; } } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the task you need to do. } else { // permission denied, boo! Disable the functionality that depends on this permission. } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_app, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { SettingsActivity.intentTo(this); return true; } else if (id == R.id.action_recent) {
RecentMediaActivity.intentTo(this);
307509256/ijkplayer-android
android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/application/AppActivity.java
// Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/RecentMediaActivity.java // public class RecentMediaActivity extends AppActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, RecentMediaActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Fragment newFragment = RecentMediaListFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // boolean show = super.onPrepareOptionsMenu(menu); // if (!show) // return show; // // MenuItem item = menu.findItem(R.id.action_recent); // if (item != null) // item.setVisible(false); // // return true; // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/SampleMediaActivity.java // public class SampleMediaActivity extends AppActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, SampleMediaActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Fragment newFragment = SampleMediaListFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // boolean show = super.onPrepareOptionsMenu(menu); // if (!show) // return show; // // MenuItem item = menu.findItem(R.id.action_recent); // if (item != null) // item.setVisible(false); // // return true; // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/SettingsActivity.java // public class SettingsActivity extends AppCompatActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, SettingsActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_app); // // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // // Fragment newFragment = SettingsFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // }
import tv.danmaku.ijk.media.example.activities.SettingsActivity; import android.Manifest; import android.annotation.SuppressLint; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import tv.danmaku.ijk.media.example.R; import tv.danmaku.ijk.media.example.activities.RecentMediaActivity; import tv.danmaku.ijk.media.example.activities.SampleMediaActivity;
} @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the task you need to do. } else { // permission denied, boo! Disable the functionality that depends on this permission. } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_app, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { SettingsActivity.intentTo(this); return true; } else if (id == R.id.action_recent) { RecentMediaActivity.intentTo(this); } else if (id == R.id.action_sample) {
// Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/RecentMediaActivity.java // public class RecentMediaActivity extends AppActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, RecentMediaActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Fragment newFragment = RecentMediaListFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // boolean show = super.onPrepareOptionsMenu(menu); // if (!show) // return show; // // MenuItem item = menu.findItem(R.id.action_recent); // if (item != null) // item.setVisible(false); // // return true; // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/SampleMediaActivity.java // public class SampleMediaActivity extends AppActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, SampleMediaActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Fragment newFragment = SampleMediaListFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // boolean show = super.onPrepareOptionsMenu(menu); // if (!show) // return show; // // MenuItem item = menu.findItem(R.id.action_recent); // if (item != null) // item.setVisible(false); // // return true; // } // } // // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/SettingsActivity.java // public class SettingsActivity extends AppCompatActivity { // public static Intent newIntent(Context context) { // Intent intent = new Intent(context, SettingsActivity.class); // return intent; // } // // public static void intentTo(Context context) { // context.startActivity(newIntent(context)); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_app); // // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // // Fragment newFragment = SettingsFragment.newInstance(); // FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // transaction.replace(R.id.body, newFragment); // transaction.commit(); // } // } // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/application/AppActivity.java import tv.danmaku.ijk.media.example.activities.SettingsActivity; import android.Manifest; import android.annotation.SuppressLint; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import tv.danmaku.ijk.media.example.R; import tv.danmaku.ijk.media.example.activities.RecentMediaActivity; import tv.danmaku.ijk.media.example.activities.SampleMediaActivity; } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the task you need to do. } else { // permission denied, boo! Disable the functionality that depends on this permission. } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_app, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { SettingsActivity.intentTo(this); return true; } else if (id == R.id.action_recent) { RecentMediaActivity.intentTo(this); } else if (id == R.id.action_sample) {
SampleMediaActivity.intentTo(this);
307509256/ijkplayer-android
android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/fragments/RecentMediaListFragment.java
// Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/content/RecentMediaStorage.java // public class RecentMediaStorage { // private Context mAppContext; // // public RecentMediaStorage(Context context) { // mAppContext = context.getApplicationContext(); // } // // public void saveUrlAsync(String url) { // new AsyncTask<String, Void, Void>() { // @Override // protected Void doInBackground(String... params) { // saveUrl(params[0]); // return null; // } // }.execute(url); // } // // public void saveUrl(String url) { // ContentValues cv = new ContentValues(); // cv.putNull(Entry.COLUMN_NAME_ID); // cv.put(Entry.COLUMN_NAME_URL, url); // cv.put(Entry.COLUMN_NAME_LAST_ACCESS, System.currentTimeMillis()); // cv.put(Entry.COLUMN_NAME_NAME, getNameOfUrl(url)); // save(cv); // } // // public void save(ContentValues contentValue) { // OpenHelper openHelper = new OpenHelper(mAppContext); // SQLiteDatabase db = openHelper.getWritableDatabase(); // db.replace(Entry.TABLE_NAME, null, contentValue); // } // // public static String getNameOfUrl(String url) { // return getNameOfUrl(url, ""); // } // // public static String getNameOfUrl(String url, String defaultName) { // String name = null; // int pos = url.lastIndexOf('/'); // if (pos >= 0) // name = url.substring(pos + 1); // // if (TextUtils.isEmpty(name)) // name = defaultName; // // return name; // } // // public static class Entry { // public static final String TABLE_NAME = "RecentMedia"; // public static final String COLUMN_NAME_ID = "id"; // public static final String COLUMN_NAME_URL = "url"; // public static final String COLUMN_NAME_NAME = "name"; // public static final String COLUMN_NAME_LAST_ACCESS = "last_access"; // } // // public static final String ALL_COLUMNS[] = new String[]{ // Entry.COLUMN_NAME_ID + " as _id", // Entry.COLUMN_NAME_ID, // Entry.COLUMN_NAME_URL, // Entry.COLUMN_NAME_NAME, // Entry.COLUMN_NAME_LAST_ACCESS}; // // public static class OpenHelper extends SQLiteOpenHelper { // private static final int DATABASE_VERSION = 1; // private static final String DATABASE_NAME = "RecentMedia.db"; // private static final String SQL_CREATE_ENTRIES = // " CREATE TABLE IF NOT EXISTS " + Entry.TABLE_NAME + " (" + // Entry.COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + // Entry.COLUMN_NAME_URL + " VARCHAR UNIQUE, " + // Entry.COLUMN_NAME_NAME + " VARCHAR, " + // Entry.COLUMN_NAME_LAST_ACCESS + " INTEGER) "; // // public OpenHelper(Context context) { // super(context, DATABASE_NAME, null, DATABASE_VERSION); // } // // @Override // public void onCreate(SQLiteDatabase db) { // db.execSQL(SQL_CREATE_ENTRIES); // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // } // } // // public static class CursorLoader extends AsyncTaskLoader<Cursor> { // public CursorLoader(Context context) { // super(context); // } // // @Override // public Cursor loadInBackground() { // Context context = getContext(); // OpenHelper openHelper = new OpenHelper(context); // SQLiteDatabase db = openHelper.getReadableDatabase(); // // return db.query(Entry.TABLE_NAME, ALL_COLUMNS, null, null, null, null, // Entry.COLUMN_NAME_LAST_ACCESS + " DESC", // "100"); // } // // @Override // protected void onStartLoading() { // forceLoad(); // } // } // }
import tv.danmaku.ijk.media.example.R; import tv.danmaku.ijk.media.example.activities.VideoActivity; import tv.danmaku.ijk.media.example.content.RecentMediaStorage; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v4.widget.SimpleCursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView;
@Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_file_list, container, false); mFileListView = (ListView) viewGroup.findViewById(R.id.file_list_view); return viewGroup; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final Activity activity = getActivity(); mAdapter = new RecentMediaAdapter(activity); mFileListView.setAdapter(mAdapter); mFileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, final long id) { String url = mAdapter.getUrl(position); String name = mAdapter.getName(position); VideoActivity.intentTo(activity, url, name); } }); getLoaderManager().initLoader(2, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/content/RecentMediaStorage.java // public class RecentMediaStorage { // private Context mAppContext; // // public RecentMediaStorage(Context context) { // mAppContext = context.getApplicationContext(); // } // // public void saveUrlAsync(String url) { // new AsyncTask<String, Void, Void>() { // @Override // protected Void doInBackground(String... params) { // saveUrl(params[0]); // return null; // } // }.execute(url); // } // // public void saveUrl(String url) { // ContentValues cv = new ContentValues(); // cv.putNull(Entry.COLUMN_NAME_ID); // cv.put(Entry.COLUMN_NAME_URL, url); // cv.put(Entry.COLUMN_NAME_LAST_ACCESS, System.currentTimeMillis()); // cv.put(Entry.COLUMN_NAME_NAME, getNameOfUrl(url)); // save(cv); // } // // public void save(ContentValues contentValue) { // OpenHelper openHelper = new OpenHelper(mAppContext); // SQLiteDatabase db = openHelper.getWritableDatabase(); // db.replace(Entry.TABLE_NAME, null, contentValue); // } // // public static String getNameOfUrl(String url) { // return getNameOfUrl(url, ""); // } // // public static String getNameOfUrl(String url, String defaultName) { // String name = null; // int pos = url.lastIndexOf('/'); // if (pos >= 0) // name = url.substring(pos + 1); // // if (TextUtils.isEmpty(name)) // name = defaultName; // // return name; // } // // public static class Entry { // public static final String TABLE_NAME = "RecentMedia"; // public static final String COLUMN_NAME_ID = "id"; // public static final String COLUMN_NAME_URL = "url"; // public static final String COLUMN_NAME_NAME = "name"; // public static final String COLUMN_NAME_LAST_ACCESS = "last_access"; // } // // public static final String ALL_COLUMNS[] = new String[]{ // Entry.COLUMN_NAME_ID + " as _id", // Entry.COLUMN_NAME_ID, // Entry.COLUMN_NAME_URL, // Entry.COLUMN_NAME_NAME, // Entry.COLUMN_NAME_LAST_ACCESS}; // // public static class OpenHelper extends SQLiteOpenHelper { // private static final int DATABASE_VERSION = 1; // private static final String DATABASE_NAME = "RecentMedia.db"; // private static final String SQL_CREATE_ENTRIES = // " CREATE TABLE IF NOT EXISTS " + Entry.TABLE_NAME + " (" + // Entry.COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + // Entry.COLUMN_NAME_URL + " VARCHAR UNIQUE, " + // Entry.COLUMN_NAME_NAME + " VARCHAR, " + // Entry.COLUMN_NAME_LAST_ACCESS + " INTEGER) "; // // public OpenHelper(Context context) { // super(context, DATABASE_NAME, null, DATABASE_VERSION); // } // // @Override // public void onCreate(SQLiteDatabase db) { // db.execSQL(SQL_CREATE_ENTRIES); // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // } // } // // public static class CursorLoader extends AsyncTaskLoader<Cursor> { // public CursorLoader(Context context) { // super(context); // } // // @Override // public Cursor loadInBackground() { // Context context = getContext(); // OpenHelper openHelper = new OpenHelper(context); // SQLiteDatabase db = openHelper.getReadableDatabase(); // // return db.query(Entry.TABLE_NAME, ALL_COLUMNS, null, null, null, null, // Entry.COLUMN_NAME_LAST_ACCESS + " DESC", // "100"); // } // // @Override // protected void onStartLoading() { // forceLoad(); // } // } // } // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/fragments/RecentMediaListFragment.java import tv.danmaku.ijk.media.example.R; import tv.danmaku.ijk.media.example.activities.VideoActivity; import tv.danmaku.ijk.media.example.content.RecentMediaStorage; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v4.widget.SimpleCursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_file_list, container, false); mFileListView = (ListView) viewGroup.findViewById(R.id.file_list_view); return viewGroup; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final Activity activity = getActivity(); mAdapter = new RecentMediaAdapter(activity); mFileListView.setAdapter(mAdapter); mFileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, final long id) { String url = mAdapter.getUrl(position); String name = mAdapter.getName(position); VideoActivity.intentTo(activity, url, name); } }); getLoaderManager().initLoader(2, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new RecentMediaStorage.CursorLoader(getActivity());
307509256/ijkplayer-android
android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/SettingsActivity.java
// Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/fragments/SettingsFragment.java // public class SettingsFragment extends PreferenceFragmentCompat { // public static SettingsFragment newInstance() { // SettingsFragment f = new SettingsFragment(); // return f; // } // // @Override // public void onCreatePreferences(Bundle bundle, String s) { // addPreferencesFromResource(R.xml.settings); // } // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import tv.danmaku.ijk.media.example.R; import tv.danmaku.ijk.media.example.fragments.SettingsFragment;
/* * Copyright (C) 2015 Zhang Rui <bbcallen@gmail.com> * * 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 tv.danmaku.ijk.media.example.activities; public class SettingsActivity extends AppCompatActivity { public static Intent newIntent(Context context) { Intent intent = new Intent(context, SettingsActivity.class); return intent; } public static void intentTo(Context context) { context.startActivity(newIntent(context)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);
// Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/fragments/SettingsFragment.java // public class SettingsFragment extends PreferenceFragmentCompat { // public static SettingsFragment newInstance() { // SettingsFragment f = new SettingsFragment(); // return f; // } // // @Override // public void onCreatePreferences(Bundle bundle, String s) { // addPreferencesFromResource(R.xml.settings); // } // } // Path: android/ijkplayer/ijkplayer-example/src/main/java/tv/danmaku/ijk/media/example/activities/SettingsActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import tv.danmaku.ijk.media.example.R; import tv.danmaku.ijk.media.example.fragments.SettingsFragment; /* * Copyright (C) 2015 Zhang Rui <bbcallen@gmail.com> * * 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 tv.danmaku.ijk.media.example.activities; public class SettingsActivity extends AppCompatActivity { public static Intent newIntent(Context context) { Intent intent = new Intent(context, SettingsActivity.class); return intent; } public static void intentTo(Context context) { context.startActivity(newIntent(context)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);
Fragment newFragment = SettingsFragment.newInstance();
thinkhoon/tkhoon
src/main/java/com/tkhoon/framework/util/CodecUtil.java
// Path: src/main/java/com/tkhoon/framework/Constant.java // public interface Constant { // // String DEFAULT_CHARSET = "UTF-8"; // // String APP_HOME_PAGE = "app.home_page"; // String APP_JSP_PATH = "app.jsp_path"; // String APP_WWW_PATH = "app.www_path"; // // String SERVLET_DEFAULT = "default"; // String SERVLET_JSP = "jsp"; // String SERVLET_UPLOAD = "upload"; // // String REQUEST_FAVICON = "/favicon.ico"; // String REQUEST_UPLOAD = "/upload.do"; // // String UPLOAD_BASE_PATH = "upload/"; // String UPLOAD_PATH_NAME = "path"; // String UPLOAD_INPUT_NAME = "file"; // String UPLOAD_FILE_NAME = "file_name"; // String UPLOAD_FILE_TYPE = "file_type"; // String UPLOAD_FILE_SIZE = "file_size"; // // String PLUGIN_PACKAGE = "com.tkhoon.plugin"; // }
import com.tkhoon.framework.Constant; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.UUID; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.RandomStringUtils; import org.apache.log4j.Logger;
package com.tkhoon.framework.util; public class CodecUtil { private static final Logger logger = Logger.getLogger(CodecUtil.class); // 将字符串 UTF-8 编码 public static String encodeUTF8(String str) { String target; try {
// Path: src/main/java/com/tkhoon/framework/Constant.java // public interface Constant { // // String DEFAULT_CHARSET = "UTF-8"; // // String APP_HOME_PAGE = "app.home_page"; // String APP_JSP_PATH = "app.jsp_path"; // String APP_WWW_PATH = "app.www_path"; // // String SERVLET_DEFAULT = "default"; // String SERVLET_JSP = "jsp"; // String SERVLET_UPLOAD = "upload"; // // String REQUEST_FAVICON = "/favicon.ico"; // String REQUEST_UPLOAD = "/upload.do"; // // String UPLOAD_BASE_PATH = "upload/"; // String UPLOAD_PATH_NAME = "path"; // String UPLOAD_INPUT_NAME = "file"; // String UPLOAD_FILE_NAME = "file_name"; // String UPLOAD_FILE_TYPE = "file_type"; // String UPLOAD_FILE_SIZE = "file_size"; // // String PLUGIN_PACKAGE = "com.tkhoon.plugin"; // } // Path: src/main/java/com/tkhoon/framework/util/CodecUtil.java import com.tkhoon.framework.Constant; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.UUID; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.RandomStringUtils; import org.apache.log4j.Logger; package com.tkhoon.framework.util; public class CodecUtil { private static final Logger logger = Logger.getLogger(CodecUtil.class); // 将字符串 UTF-8 编码 public static String encodeUTF8(String str) { String target; try {
target = URLEncoder.encode(str, Constant.DEFAULT_CHARSET);
thinkhoon/tkhoon
src/main/java/com/tkhoon/framework/base/BaseBean.java
// Path: src/main/java/com/tkhoon/framework/util/JSONUtil.java // public class JSONUtil { // // private static final Logger logger = Logger.getLogger(JSONUtil.class); // // private static final ObjectMapper objectMapper = new ObjectMapper(); // // // 将 Java 对象转为 JSON 字符串 // public static <T> String toJSON(T obj) { // String jsonStr; // try { // jsonStr = objectMapper.writeValueAsString(obj); // } catch (Exception e) { // logger.error("Java 转 JSON 出错!", e); // throw new RuntimeException(e); // } // return jsonStr; // } // // // 将 JSON 字符串转为 Java 对象 // public static <T> T fromJSON(String json, Class<T> type) { // T obj; // try { // obj = objectMapper.readValue(json, type); // } catch (Exception e) { // logger.error("JSON 转 Java 出错!", e); // throw new RuntimeException(e); // } // return obj; // } // }
import com.tkhoon.framework.util.JSONUtil; import java.io.Serializable; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle;
package com.tkhoon.framework.base; public abstract class BaseBean implements Serializable { @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } public String toJson() {
// Path: src/main/java/com/tkhoon/framework/util/JSONUtil.java // public class JSONUtil { // // private static final Logger logger = Logger.getLogger(JSONUtil.class); // // private static final ObjectMapper objectMapper = new ObjectMapper(); // // // 将 Java 对象转为 JSON 字符串 // public static <T> String toJSON(T obj) { // String jsonStr; // try { // jsonStr = objectMapper.writeValueAsString(obj); // } catch (Exception e) { // logger.error("Java 转 JSON 出错!", e); // throw new RuntimeException(e); // } // return jsonStr; // } // // // 将 JSON 字符串转为 Java 对象 // public static <T> T fromJSON(String json, Class<T> type) { // T obj; // try { // obj = objectMapper.readValue(json, type); // } catch (Exception e) { // logger.error("JSON 转 Java 出错!", e); // throw new RuntimeException(e); // } // return obj; // } // } // Path: src/main/java/com/tkhoon/framework/base/BaseBean.java import com.tkhoon.framework.util.JSONUtil; import java.io.Serializable; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; package com.tkhoon.framework.base; public abstract class BaseBean implements Serializable { @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } public String toJson() {
return JSONUtil.toJSON(this);
thinkhoon/tkhoon
src/main/java/com/tkhoon/framework/util/WebUtil.java
// Path: src/main/java/com/tkhoon/framework/Constant.java // public interface Constant { // // String DEFAULT_CHARSET = "UTF-8"; // // String APP_HOME_PAGE = "app.home_page"; // String APP_JSP_PATH = "app.jsp_path"; // String APP_WWW_PATH = "app.www_path"; // // String SERVLET_DEFAULT = "default"; // String SERVLET_JSP = "jsp"; // String SERVLET_UPLOAD = "upload"; // // String REQUEST_FAVICON = "/favicon.ico"; // String REQUEST_UPLOAD = "/upload.do"; // // String UPLOAD_BASE_PATH = "upload/"; // String UPLOAD_PATH_NAME = "path"; // String UPLOAD_INPUT_NAME = "file"; // String UPLOAD_FILE_NAME = "file_name"; // String UPLOAD_FILE_TYPE = "file_type"; // String UPLOAD_FILE_SIZE = "file_size"; // // String PLUGIN_PACKAGE = "com.tkhoon.plugin"; // }
import com.tkhoon.framework.Constant; import java.io.PrintWriter; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import org.apache.log4j.Logger;
package com.tkhoon.framework.util; public class WebUtil { private static final Logger logger = Logger.getLogger(WebUtil.class); // 将数据以纯文本格式写入响应中 public static void writeText(HttpServletResponse response, Object data) { try { // 设置响应头 response.setContentType("text/plain"); // 指定内容类型为纯文本格式
// Path: src/main/java/com/tkhoon/framework/Constant.java // public interface Constant { // // String DEFAULT_CHARSET = "UTF-8"; // // String APP_HOME_PAGE = "app.home_page"; // String APP_JSP_PATH = "app.jsp_path"; // String APP_WWW_PATH = "app.www_path"; // // String SERVLET_DEFAULT = "default"; // String SERVLET_JSP = "jsp"; // String SERVLET_UPLOAD = "upload"; // // String REQUEST_FAVICON = "/favicon.ico"; // String REQUEST_UPLOAD = "/upload.do"; // // String UPLOAD_BASE_PATH = "upload/"; // String UPLOAD_PATH_NAME = "path"; // String UPLOAD_INPUT_NAME = "file"; // String UPLOAD_FILE_NAME = "file_name"; // String UPLOAD_FILE_TYPE = "file_type"; // String UPLOAD_FILE_SIZE = "file_size"; // // String PLUGIN_PACKAGE = "com.tkhoon.plugin"; // } // Path: src/main/java/com/tkhoon/framework/util/WebUtil.java import com.tkhoon.framework.Constant; import java.io.PrintWriter; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import org.apache.log4j.Logger; package com.tkhoon.framework.util; public class WebUtil { private static final Logger logger = Logger.getLogger(WebUtil.class); // 将数据以纯文本格式写入响应中 public static void writeText(HttpServletResponse response, Object data) { try { // 设置响应头 response.setContentType("text/plain"); // 指定内容类型为纯文本格式
response.setCharacterEncoding(Constant.DEFAULT_CHARSET); // 防止中文乱码
thinkhoon/tkhoon
src/main/java/com/tkhoon/framework/helper/IOCHelper.java
// Path: src/main/java/com/tkhoon/framework/util/ArrayUtil.java // public class ArrayUtil { // // // 判断 Array 是否非空 // public static boolean isNotEmpty(Object[] array) { // return ArrayUtils.isNotEmpty(array); // } // // // 判断 Array 是否为空 // public static boolean isEmpty(Object[] array) { // return ArrayUtils.isEmpty(array); // } // } // // Path: src/main/java/com/tkhoon/framework/util/CollectionUtil.java // public class CollectionUtil { // // // 判断集合是否非空 // public static boolean isNotEmpty(Collection<?> collection) { // return CollectionUtils.isNotEmpty(collection); // } // // // 判断集合是否为空 // public static boolean isEmpty(Collection<?> collection) { // return CollectionUtils.isEmpty(collection); // } // }
import com.tkhoon.framework.annotation.Impl; import com.tkhoon.framework.annotation.Inject; import com.tkhoon.framework.util.ArrayUtil; import com.tkhoon.framework.util.CollectionUtil; import java.lang.reflect.Field; import java.util.List; import java.util.Map; import org.apache.log4j.Logger;
package com.tkhoon.framework.helper; public class IOCHelper { private static final Logger logger = Logger.getLogger(IOCHelper.class); static { try { // 获取并遍历所有的 Bean 类 Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap(); for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) { // 获取 Bean 类与 Bean 实例 Class<?> beanClass = beanEntry.getKey(); Object beanInstance = beanEntry.getValue(); // 获取 Bean 类中所有的字段(不包括父类中的方法) Field[] beanFields = beanClass.getDeclaredFields();
// Path: src/main/java/com/tkhoon/framework/util/ArrayUtil.java // public class ArrayUtil { // // // 判断 Array 是否非空 // public static boolean isNotEmpty(Object[] array) { // return ArrayUtils.isNotEmpty(array); // } // // // 判断 Array 是否为空 // public static boolean isEmpty(Object[] array) { // return ArrayUtils.isEmpty(array); // } // } // // Path: src/main/java/com/tkhoon/framework/util/CollectionUtil.java // public class CollectionUtil { // // // 判断集合是否非空 // public static boolean isNotEmpty(Collection<?> collection) { // return CollectionUtils.isNotEmpty(collection); // } // // // 判断集合是否为空 // public static boolean isEmpty(Collection<?> collection) { // return CollectionUtils.isEmpty(collection); // } // } // Path: src/main/java/com/tkhoon/framework/helper/IOCHelper.java import com.tkhoon.framework.annotation.Impl; import com.tkhoon.framework.annotation.Inject; import com.tkhoon.framework.util.ArrayUtil; import com.tkhoon.framework.util.CollectionUtil; import java.lang.reflect.Field; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; package com.tkhoon.framework.helper; public class IOCHelper { private static final Logger logger = Logger.getLogger(IOCHelper.class); static { try { // 获取并遍历所有的 Bean 类 Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap(); for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) { // 获取 Bean 类与 Bean 实例 Class<?> beanClass = beanEntry.getKey(); Object beanInstance = beanEntry.getValue(); // 获取 Bean 类中所有的字段(不包括父类中的方法) Field[] beanFields = beanClass.getDeclaredFields();
if (ArrayUtil.isNotEmpty(beanFields)) {
thinkhoon/tkhoon
src/main/java/com/tkhoon/framework/helper/IOCHelper.java
// Path: src/main/java/com/tkhoon/framework/util/ArrayUtil.java // public class ArrayUtil { // // // 判断 Array 是否非空 // public static boolean isNotEmpty(Object[] array) { // return ArrayUtils.isNotEmpty(array); // } // // // 判断 Array 是否为空 // public static boolean isEmpty(Object[] array) { // return ArrayUtils.isEmpty(array); // } // } // // Path: src/main/java/com/tkhoon/framework/util/CollectionUtil.java // public class CollectionUtil { // // // 判断集合是否非空 // public static boolean isNotEmpty(Collection<?> collection) { // return CollectionUtils.isNotEmpty(collection); // } // // // 判断集合是否为空 // public static boolean isEmpty(Collection<?> collection) { // return CollectionUtils.isEmpty(collection); // } // }
import com.tkhoon.framework.annotation.Impl; import com.tkhoon.framework.annotation.Inject; import com.tkhoon.framework.util.ArrayUtil; import com.tkhoon.framework.util.CollectionUtil; import java.lang.reflect.Field; import java.util.List; import java.util.Map; import org.apache.log4j.Logger;
beanField.set(beanInstance, implementInstance); // beanInstance 是普通实例,或 CGLib 动态代理实例(不能使 JDK 动态代理实例) } } } } } } } catch (Exception e) { logger.error("初始化 IOCHelper 出错!", e); } } private static Class<?> getImplementClass(Field beanField) { // 定义实现类对象 Class<?> implementClass = null; // 获取 Bean 字段对应的接口 Class<?> interfaceClass = beanField.getType(); // 通过接口查找唯一的实现类 return findImplementClass(interfaceClass); } public static Class<?> findImplementClass(Class<?> interfaceClass) { Class<?> implementClass = interfaceClass; // 判断接口上是否标注了 @Impl 注解 if (interfaceClass.isAnnotationPresent(Impl.class)) { // 获取强制指定的实现类 implementClass = interfaceClass.getAnnotation(Impl.class).value(); } else { // 获取该接口所有的实现类 List<Class<?>> implementClassList = ClassHelper.getClassListBySuper(interfaceClass);
// Path: src/main/java/com/tkhoon/framework/util/ArrayUtil.java // public class ArrayUtil { // // // 判断 Array 是否非空 // public static boolean isNotEmpty(Object[] array) { // return ArrayUtils.isNotEmpty(array); // } // // // 判断 Array 是否为空 // public static boolean isEmpty(Object[] array) { // return ArrayUtils.isEmpty(array); // } // } // // Path: src/main/java/com/tkhoon/framework/util/CollectionUtil.java // public class CollectionUtil { // // // 判断集合是否非空 // public static boolean isNotEmpty(Collection<?> collection) { // return CollectionUtils.isNotEmpty(collection); // } // // // 判断集合是否为空 // public static boolean isEmpty(Collection<?> collection) { // return CollectionUtils.isEmpty(collection); // } // } // Path: src/main/java/com/tkhoon/framework/helper/IOCHelper.java import com.tkhoon.framework.annotation.Impl; import com.tkhoon.framework.annotation.Inject; import com.tkhoon.framework.util.ArrayUtil; import com.tkhoon.framework.util.CollectionUtil; import java.lang.reflect.Field; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; beanField.set(beanInstance, implementInstance); // beanInstance 是普通实例,或 CGLib 动态代理实例(不能使 JDK 动态代理实例) } } } } } } } catch (Exception e) { logger.error("初始化 IOCHelper 出错!", e); } } private static Class<?> getImplementClass(Field beanField) { // 定义实现类对象 Class<?> implementClass = null; // 获取 Bean 字段对应的接口 Class<?> interfaceClass = beanField.getType(); // 通过接口查找唯一的实现类 return findImplementClass(interfaceClass); } public static Class<?> findImplementClass(Class<?> interfaceClass) { Class<?> implementClass = interfaceClass; // 判断接口上是否标注了 @Impl 注解 if (interfaceClass.isAnnotationPresent(Impl.class)) { // 获取强制指定的实现类 implementClass = interfaceClass.getAnnotation(Impl.class).value(); } else { // 获取该接口所有的实现类 List<Class<?>> implementClassList = ClassHelper.getClassListBySuper(interfaceClass);
if (CollectionUtil.isNotEmpty(implementClassList)) {
thinkhoon/tkhoon
src/main/java/com/tkhoon/framework/base/BaseAspect.java
// Path: src/main/java/com/tkhoon/framework/proxy/Proxy.java // public interface Proxy { // // Object doProxy(ProxyChain proxyChain) throws Exception; // } // // Path: src/main/java/com/tkhoon/framework/proxy/ProxyChain.java // public class ProxyChain { // // private Class<?> targetClass; // private Object targetObject; // private Method targetMethod; // private Object[] methodParams; // private MethodProxy methodProxy; // // private List<Proxy> proxyList; // private int currentProxyIndex = 0; // // public ProxyChain(Class<?> targetClass, Object targetObject, Method targetMethod, Object[] methodParams, MethodProxy methodProxy, List<Proxy> proxyList) { // this.targetClass = targetClass; // this.targetObject = targetObject; // this.targetMethod = targetMethod; // this.methodParams = methodParams; // this.methodProxy = methodProxy; // this.proxyList = proxyList; // } // // public Class<?> getTargetClass() { // return targetClass; // } // // public Method getTargetMethod() { // return targetMethod; // } // // public Object[] getMethodParams() { // return methodParams; // } // // public Object doProxyChain() throws Exception { // Object methodResult; // if (currentProxyIndex < proxyList.size()) { // methodResult = proxyList.get(currentProxyIndex++).doProxy(this); // } else { // try { // methodResult = methodProxy.invokeSuper(targetObject, methodParams); // } catch (Throwable throwable) { // throw new RuntimeException(throwable); // } // } // return methodResult; // } // }
import com.tkhoon.framework.proxy.Proxy; import com.tkhoon.framework.proxy.ProxyChain; import java.lang.reflect.Method;
package com.tkhoon.framework.base; public abstract class BaseAspect implements Proxy { @Override
// Path: src/main/java/com/tkhoon/framework/proxy/Proxy.java // public interface Proxy { // // Object doProxy(ProxyChain proxyChain) throws Exception; // } // // Path: src/main/java/com/tkhoon/framework/proxy/ProxyChain.java // public class ProxyChain { // // private Class<?> targetClass; // private Object targetObject; // private Method targetMethod; // private Object[] methodParams; // private MethodProxy methodProxy; // // private List<Proxy> proxyList; // private int currentProxyIndex = 0; // // public ProxyChain(Class<?> targetClass, Object targetObject, Method targetMethod, Object[] methodParams, MethodProxy methodProxy, List<Proxy> proxyList) { // this.targetClass = targetClass; // this.targetObject = targetObject; // this.targetMethod = targetMethod; // this.methodParams = methodParams; // this.methodProxy = methodProxy; // this.proxyList = proxyList; // } // // public Class<?> getTargetClass() { // return targetClass; // } // // public Method getTargetMethod() { // return targetMethod; // } // // public Object[] getMethodParams() { // return methodParams; // } // // public Object doProxyChain() throws Exception { // Object methodResult; // if (currentProxyIndex < proxyList.size()) { // methodResult = proxyList.get(currentProxyIndex++).doProxy(this); // } else { // try { // methodResult = methodProxy.invokeSuper(targetObject, methodParams); // } catch (Throwable throwable) { // throw new RuntimeException(throwable); // } // } // return methodResult; // } // } // Path: src/main/java/com/tkhoon/framework/base/BaseAspect.java import com.tkhoon.framework.proxy.Proxy; import com.tkhoon.framework.proxy.ProxyChain; import java.lang.reflect.Method; package com.tkhoon.framework.base; public abstract class BaseAspect implements Proxy { @Override
public final Object doProxy(ProxyChain proxyChain) throws Exception {
thinkhoon/tkhoon
src/main/java/com/tkhoon/framework/util/FileUtil.java
// Path: src/main/java/com/tkhoon/framework/Constant.java // public interface Constant { // // String DEFAULT_CHARSET = "UTF-8"; // // String APP_HOME_PAGE = "app.home_page"; // String APP_JSP_PATH = "app.jsp_path"; // String APP_WWW_PATH = "app.www_path"; // // String SERVLET_DEFAULT = "default"; // String SERVLET_JSP = "jsp"; // String SERVLET_UPLOAD = "upload"; // // String REQUEST_FAVICON = "/favicon.ico"; // String REQUEST_UPLOAD = "/upload.do"; // // String UPLOAD_BASE_PATH = "upload/"; // String UPLOAD_PATH_NAME = "path"; // String UPLOAD_INPUT_NAME = "file"; // String UPLOAD_FILE_NAME = "file_name"; // String UPLOAD_FILE_TYPE = "file_type"; // String UPLOAD_FILE_SIZE = "file_size"; // // String PLUGIN_PACKAGE = "com.tkhoon.plugin"; // }
import com.tkhoon.framework.Constant; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger;
logger.error("删除文件出错!", e); throw new RuntimeException(e); } } private static void checkDir(File src) { if (!src.exists()) { throw new RuntimeException("该路径不存在!" + src); } if (!src.isDirectory()) { throw new RuntimeException("该路径不是目录!"); } } private static void checkFile(File src) { if (!src.exists()) { throw new RuntimeException("该路径不存在!" + src); } if (!src.isFile()) { throw new RuntimeException("该路径不是文件!"); } } // 将字符串写入文件 public static void writeFile(String filePath, String fileContent) { OutputStream os = null; Writer w = null; try { FileUtil.createFile(filePath); os = new BufferedOutputStream(new FileOutputStream(filePath));
// Path: src/main/java/com/tkhoon/framework/Constant.java // public interface Constant { // // String DEFAULT_CHARSET = "UTF-8"; // // String APP_HOME_PAGE = "app.home_page"; // String APP_JSP_PATH = "app.jsp_path"; // String APP_WWW_PATH = "app.www_path"; // // String SERVLET_DEFAULT = "default"; // String SERVLET_JSP = "jsp"; // String SERVLET_UPLOAD = "upload"; // // String REQUEST_FAVICON = "/favicon.ico"; // String REQUEST_UPLOAD = "/upload.do"; // // String UPLOAD_BASE_PATH = "upload/"; // String UPLOAD_PATH_NAME = "path"; // String UPLOAD_INPUT_NAME = "file"; // String UPLOAD_FILE_NAME = "file_name"; // String UPLOAD_FILE_TYPE = "file_type"; // String UPLOAD_FILE_SIZE = "file_size"; // // String PLUGIN_PACKAGE = "com.tkhoon.plugin"; // } // Path: src/main/java/com/tkhoon/framework/util/FileUtil.java import com.tkhoon.framework.Constant; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; logger.error("删除文件出错!", e); throw new RuntimeException(e); } } private static void checkDir(File src) { if (!src.exists()) { throw new RuntimeException("该路径不存在!" + src); } if (!src.isDirectory()) { throw new RuntimeException("该路径不是目录!"); } } private static void checkFile(File src) { if (!src.exists()) { throw new RuntimeException("该路径不存在!" + src); } if (!src.isFile()) { throw new RuntimeException("该路径不是文件!"); } } // 将字符串写入文件 public static void writeFile(String filePath, String fileContent) { OutputStream os = null; Writer w = null; try { FileUtil.createFile(filePath); os = new BufferedOutputStream(new FileOutputStream(filePath));
w = new OutputStreamWriter(os, Constant.DEFAULT_CHARSET);
chenjishi/usite
u148/app/src/main/java/com/chenjishi/u148/widget/GifMovieView.java
// Path: u148/app/src/main/java/com/chenjishi/u148/utils/ErrorListener.java // public interface ErrorListener { // // void onErrorResponse(); // } // // Path: u148/app/src/main/java/com/chenjishi/u148/utils/Listener.java // public interface Listener<T> { // // void onResponse(T response); // // } // // Path: u148/app/src/main/java/com/chenjishi/u148/utils/NetworkRequest.java // public class NetworkRequest { // private static final NetworkRequest INSTANCE = new NetworkRequest(); // // private OkHttpClient mHttpClient; // // private Gson mGson; // // private Handler mHandler; // // private NetworkRequest() { // mHttpClient = new OkHttpClient(); // mGson = new GsonBuilder().create(); // mHandler = new Handler(Looper.getMainLooper()); // } // // public static NetworkRequest getInstance() { // return INSTANCE; // } // // public <T> void get(String url, // final Class<T> clazz, // final Listener<T> listener, // final ErrorListener errorListener) { // // Request.Builder request = new Request.Builder().url(url); // request.cacheControl(CacheControl.FORCE_NETWORK); // // mHttpClient.newCall(request.build()).enqueue(new Callback() { // @Override // public void onFailure(Call call, IOException e) { // onError(errorListener); // } // // @Override // public void onResponse(Call call, Response response) throws IOException { // parseJson(response.body().string(), clazz, listener, errorListener); // } // }); // } // // public void post(String url, // Map<String, String> params, // final Listener<String> listener, // final ErrorListener errorListener) { // FormBody.Builder builder = new FormBody.Builder(); // for (String key : params.keySet()) { // builder.add(key, params.get(key)); // } // // Request.Builder request = new Request.Builder() // .url(url) // .post(builder.build()); // // mHttpClient.newCall(request.build()).enqueue(new Callback() { // @Override // public void onFailure(Call call, IOException e) { // onError(errorListener); // } // // @Override // public void onResponse(Call call, Response response) throws IOException { // onSuccess(listener, response.body().string()); // } // }); // } // // public void getBytes(String url, // final Listener<byte[]> listener, // final ErrorListener errorListener) { // Request.Builder request = new Request.Builder() // .url(url); // // mHttpClient.newCall(request.build()).enqueue(new Callback() { // @Override // public void onFailure(Call call, IOException e) { // onError(errorListener); // } // // @Override // public void onResponse(Call call, final Response response) throws IOException { // listener.onResponse(response.body().bytes()); // } // }); // } // // public void get(String url, // final Listener<String> listener, // final ErrorListener errorListener) { // Request.Builder request = new Request.Builder() // .url(url); // // mHttpClient.newCall(request.build()).enqueue(new Callback() { // @Override // public void onFailure(Call call, IOException e) { // onError(errorListener); // } // // @Override // public void onResponse(Call call, Response response) throws IOException { // onSuccess(listener, response.body().string()); // } // }); // } // // private void onError(final ErrorListener listener) { // mHandler.post(new Runnable() { // @Override // public void run() { // listener.onErrorResponse(); // } // }); // } // // private <T> void parseJson(final String json, // final Class<T> clazz, // final Listener<T> listener, // final ErrorListener errorListener) { // if (TextUtils.isEmpty(json)) { // onError(errorListener); // return; // } // // mHandler.post(new Runnable() { // @Override // public void run() { // try { // T obj = mGson.fromJson(json, clazz); // listener.onResponse(obj); // } catch (JsonSyntaxException e) { // onError(errorListener); // } // } // }); // } // // private void onSuccess(final Listener<String> listener, final String json) { // mHandler.post(new Runnable() { // @Override // public void run() { // listener.onResponse(json); // } // }); // } // }
import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Movie; import android.os.Build; import android.util.AttributeSet; import android.view.View; import com.chenjishi.u148.utils.ErrorListener; import com.chenjishi.u148.utils.Listener; import com.chenjishi.u148.utils.NetworkRequest;
invalidateView(); } @Override public void onErrorResponse() { } @Override public void onResponse(byte[] response) { if (null != response && response.length > 0) { mMovie = Movie.decodeByteArray(response, 0, response.length); post(new Runnable() { @Override public void run() { requestLayout(); } }); } } public void setImageResId(int resId, int width) { mRequestWidth = width; mMovie = Movie.decodeStream(getResources().openRawResource(resId)); requestLayout(); } public void setImageUrl(String url, int width) {
// Path: u148/app/src/main/java/com/chenjishi/u148/utils/ErrorListener.java // public interface ErrorListener { // // void onErrorResponse(); // } // // Path: u148/app/src/main/java/com/chenjishi/u148/utils/Listener.java // public interface Listener<T> { // // void onResponse(T response); // // } // // Path: u148/app/src/main/java/com/chenjishi/u148/utils/NetworkRequest.java // public class NetworkRequest { // private static final NetworkRequest INSTANCE = new NetworkRequest(); // // private OkHttpClient mHttpClient; // // private Gson mGson; // // private Handler mHandler; // // private NetworkRequest() { // mHttpClient = new OkHttpClient(); // mGson = new GsonBuilder().create(); // mHandler = new Handler(Looper.getMainLooper()); // } // // public static NetworkRequest getInstance() { // return INSTANCE; // } // // public <T> void get(String url, // final Class<T> clazz, // final Listener<T> listener, // final ErrorListener errorListener) { // // Request.Builder request = new Request.Builder().url(url); // request.cacheControl(CacheControl.FORCE_NETWORK); // // mHttpClient.newCall(request.build()).enqueue(new Callback() { // @Override // public void onFailure(Call call, IOException e) { // onError(errorListener); // } // // @Override // public void onResponse(Call call, Response response) throws IOException { // parseJson(response.body().string(), clazz, listener, errorListener); // } // }); // } // // public void post(String url, // Map<String, String> params, // final Listener<String> listener, // final ErrorListener errorListener) { // FormBody.Builder builder = new FormBody.Builder(); // for (String key : params.keySet()) { // builder.add(key, params.get(key)); // } // // Request.Builder request = new Request.Builder() // .url(url) // .post(builder.build()); // // mHttpClient.newCall(request.build()).enqueue(new Callback() { // @Override // public void onFailure(Call call, IOException e) { // onError(errorListener); // } // // @Override // public void onResponse(Call call, Response response) throws IOException { // onSuccess(listener, response.body().string()); // } // }); // } // // public void getBytes(String url, // final Listener<byte[]> listener, // final ErrorListener errorListener) { // Request.Builder request = new Request.Builder() // .url(url); // // mHttpClient.newCall(request.build()).enqueue(new Callback() { // @Override // public void onFailure(Call call, IOException e) { // onError(errorListener); // } // // @Override // public void onResponse(Call call, final Response response) throws IOException { // listener.onResponse(response.body().bytes()); // } // }); // } // // public void get(String url, // final Listener<String> listener, // final ErrorListener errorListener) { // Request.Builder request = new Request.Builder() // .url(url); // // mHttpClient.newCall(request.build()).enqueue(new Callback() { // @Override // public void onFailure(Call call, IOException e) { // onError(errorListener); // } // // @Override // public void onResponse(Call call, Response response) throws IOException { // onSuccess(listener, response.body().string()); // } // }); // } // // private void onError(final ErrorListener listener) { // mHandler.post(new Runnable() { // @Override // public void run() { // listener.onErrorResponse(); // } // }); // } // // private <T> void parseJson(final String json, // final Class<T> clazz, // final Listener<T> listener, // final ErrorListener errorListener) { // if (TextUtils.isEmpty(json)) { // onError(errorListener); // return; // } // // mHandler.post(new Runnable() { // @Override // public void run() { // try { // T obj = mGson.fromJson(json, clazz); // listener.onResponse(obj); // } catch (JsonSyntaxException e) { // onError(errorListener); // } // } // }); // } // // private void onSuccess(final Listener<String> listener, final String json) { // mHandler.post(new Runnable() { // @Override // public void run() { // listener.onResponse(json); // } // }); // } // } // Path: u148/app/src/main/java/com/chenjishi/u148/widget/GifMovieView.java import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Movie; import android.os.Build; import android.util.AttributeSet; import android.view.View; import com.chenjishi.u148.utils.ErrorListener; import com.chenjishi.u148.utils.Listener; import com.chenjishi.u148.utils.NetworkRequest; invalidateView(); } @Override public void onErrorResponse() { } @Override public void onResponse(byte[] response) { if (null != response && response.length > 0) { mMovie = Movie.decodeByteArray(response, 0, response.length); post(new Runnable() { @Override public void run() { requestLayout(); } }); } } public void setImageResId(int resId, int width) { mRequestWidth = width; mMovie = Movie.decodeStream(getResources().openRawResource(resId)); requestLayout(); } public void setImageUrl(String url, int width) {
NetworkRequest.getInstance().getBytes(url, this, this);
chenjishi/usite
u148/app/src/main/java/com/chenjishi/u148/comment/Comment.java
// Path: u148/app/src/main/java/com/chenjishi/u148/home/UserInfo.java // public class UserInfo implements Parcelable { // public String icon; // public String alias; // public String nickname; // public String sexStr; // public String statusStr; // public String id; // public String token; // // public static final Creator<UserInfo> CREATOR = new Creator<UserInfo>() { // @Override // public UserInfo createFromParcel(Parcel source) { // return new UserInfo(source); // } // // @Override // public UserInfo[] newArray(int size) { // return new UserInfo[size]; // } // }; // // public UserInfo() { // } // // public UserInfo(Parcel in) { // icon = in.readString(); // alias = in.readString(); // nickname = in.readString(); // sexStr = in.readString(); // statusStr = in.readString(); // id = in.readString(); // token = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(alias); // dest.writeString(nickname); // dest.writeString(sexStr); // dest.writeString(statusStr); // dest.writeString(id); // dest.writeString(token); // } // }
import com.chenjishi.u148.home.UserInfo;
package com.chenjishi.u148.comment; /** * Created by jishichen on 2017/4/25. */ public class Comment { public String id; public String contents; public int status; public String uid; public String aid; public int count_support; public int is_commend; public long create_time; public String area; public String ip; public int count_tread; public int floor_no;
// Path: u148/app/src/main/java/com/chenjishi/u148/home/UserInfo.java // public class UserInfo implements Parcelable { // public String icon; // public String alias; // public String nickname; // public String sexStr; // public String statusStr; // public String id; // public String token; // // public static final Creator<UserInfo> CREATOR = new Creator<UserInfo>() { // @Override // public UserInfo createFromParcel(Parcel source) { // return new UserInfo(source); // } // // @Override // public UserInfo[] newArray(int size) { // return new UserInfo[size]; // } // }; // // public UserInfo() { // } // // public UserInfo(Parcel in) { // icon = in.readString(); // alias = in.readString(); // nickname = in.readString(); // sexStr = in.readString(); // statusStr = in.readString(); // id = in.readString(); // token = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(alias); // dest.writeString(nickname); // dest.writeString(sexStr); // dest.writeString(statusStr); // dest.writeString(id); // dest.writeString(token); // } // } // Path: u148/app/src/main/java/com/chenjishi/u148/comment/Comment.java import com.chenjishi.u148.home.UserInfo; package com.chenjishi.u148.comment; /** * Created by jishichen on 2017/4/25. */ public class Comment { public String id; public String contents; public int status; public String uid; public String aid; public int count_support; public int is_commend; public long create_time; public String area; public String ip; public int count_tread; public int floor_no;
public UserInfo usr;
chenjishi/usite
u148/app/src/main/java/com/chenjishi/u148/Config.java
// Path: u148/app/src/main/java/com/chenjishi/u148/home/UserInfo.java // public class UserInfo implements Parcelable { // public String icon; // public String alias; // public String nickname; // public String sexStr; // public String statusStr; // public String id; // public String token; // // public static final Creator<UserInfo> CREATOR = new Creator<UserInfo>() { // @Override // public UserInfo createFromParcel(Parcel source) { // return new UserInfo(source); // } // // @Override // public UserInfo[] newArray(int size) { // return new UserInfo[size]; // } // }; // // public UserInfo() { // } // // public UserInfo(Parcel in) { // icon = in.readString(); // alias = in.readString(); // nickname = in.readString(); // sexStr = in.readString(); // statusStr = in.readString(); // id = in.readString(); // token = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(alias); // dest.writeString(nickname); // dest.writeString(sexStr); // dest.writeString(statusStr); // dest.writeString(id); // dest.writeString(token); // } // } // // Path: u148/app/src/main/java/com/chenjishi/u148/utils/Constants.java // public interface Constants { // // String KEY_FEED = "feed"; // String KEY_FEED_LIST = "feed_list"; // String KEY_FEED_INDEX = "index"; // // int MODE_DAY = 0; // int MODE_NIGHT = 1; // // String EVENT_ARTICLE_SHARE = "ArticleShare"; // String EVENT_IMAGE_SHARE = "ArticleShare"; // // String PARAM_TITLE = "title"; // String PARAM_URL = "url"; // // String BASE_URL = "http://api.u148.net/json/"; // // String API_FEED_LIST = BASE_URL + "%1$d/%2$d"; // String API_ARTICLE = BASE_URL + "article/%1$s"; // String API_ADD_FAVORITE = BASE_URL + "favourite?id=%1$s&token=%2$s"; // String API_DELETE_FAVORITE = BASE_URL + "del_favourite?id=%1$s&token=%2$s"; // String API_LOGIN = BASE_URL + "login"; // String API_REGISTER = BASE_URL + "register"; // String API_COMMENTS_GET = BASE_URL + "get_comment/%1$s/%2$d"; // String API_COMMENT_POST = BASE_URL + "comment"; // String API_FAVORITE_GET = BASE_URL + "get_favourite/0/%1$d?token=%2$s"; // String API_UPGRADE = BASE_URL + "version"; // String API_SEARCH = BASE_URL + "search/%1$d?keyword=%2$s"; // String XIAO_MI = "http://app.mi.com/details?id=com.chenjishi.u148&ref=search"; // }
import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import com.chenjishi.u148.home.UserInfo; import com.chenjishi.u148.utils.Constants;
package com.chenjishi.u148; /** * Created by jishichen on 2017/4/14. */ public class Config { private static final long TWO_DAYS = 2 * 24 * 60 * 60 * 1000; private static final String CONFIG_FILE_NAME = "u148_config"; private static final long VERSION_CHECK_INTERVAL = 24 * 60 * 60 * 1000; private static final String KEY_NEXT_TOKEN = "next_from"; public static final String KEY_UPDATE_TIME = "last_update_time"; public static final String KEY_CHECK_UPDATE_TIME = "last_check_time"; public static final String KEY_CHECK_VERSION = "check_version"; public static final String KEY_VIDEO_UPDATE_TIME = "last_update_time"; private static final String KEY_CACHE_CLEAR_TIME = "cache_clear_time"; private static final String KEY_CACHE_UPDATE_TIME = "cache_update_time"; private static final String KEY_REGISTER_TIME = "register_time"; private static final String KEY_USER_NAME = "user_name"; private static final String KEY_USER_SEX = "user_sex"; private static final String KEY_USER_ICON = "user_icon"; private static final String KEY_USER_TOKEN = "user_token"; private static final String KEY_THEME_MODE = "theme_mode"; private static final String SURPRISE_TITLE = "surprise_title"; private static final String SURPRISE_DESC = "surprise_desc"; private Config() { } public static boolean isLogin(Context ctx) { return null != getUser(ctx); } public static int getThemeMode(Context ctx) {
// Path: u148/app/src/main/java/com/chenjishi/u148/home/UserInfo.java // public class UserInfo implements Parcelable { // public String icon; // public String alias; // public String nickname; // public String sexStr; // public String statusStr; // public String id; // public String token; // // public static final Creator<UserInfo> CREATOR = new Creator<UserInfo>() { // @Override // public UserInfo createFromParcel(Parcel source) { // return new UserInfo(source); // } // // @Override // public UserInfo[] newArray(int size) { // return new UserInfo[size]; // } // }; // // public UserInfo() { // } // // public UserInfo(Parcel in) { // icon = in.readString(); // alias = in.readString(); // nickname = in.readString(); // sexStr = in.readString(); // statusStr = in.readString(); // id = in.readString(); // token = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(alias); // dest.writeString(nickname); // dest.writeString(sexStr); // dest.writeString(statusStr); // dest.writeString(id); // dest.writeString(token); // } // } // // Path: u148/app/src/main/java/com/chenjishi/u148/utils/Constants.java // public interface Constants { // // String KEY_FEED = "feed"; // String KEY_FEED_LIST = "feed_list"; // String KEY_FEED_INDEX = "index"; // // int MODE_DAY = 0; // int MODE_NIGHT = 1; // // String EVENT_ARTICLE_SHARE = "ArticleShare"; // String EVENT_IMAGE_SHARE = "ArticleShare"; // // String PARAM_TITLE = "title"; // String PARAM_URL = "url"; // // String BASE_URL = "http://api.u148.net/json/"; // // String API_FEED_LIST = BASE_URL + "%1$d/%2$d"; // String API_ARTICLE = BASE_URL + "article/%1$s"; // String API_ADD_FAVORITE = BASE_URL + "favourite?id=%1$s&token=%2$s"; // String API_DELETE_FAVORITE = BASE_URL + "del_favourite?id=%1$s&token=%2$s"; // String API_LOGIN = BASE_URL + "login"; // String API_REGISTER = BASE_URL + "register"; // String API_COMMENTS_GET = BASE_URL + "get_comment/%1$s/%2$d"; // String API_COMMENT_POST = BASE_URL + "comment"; // String API_FAVORITE_GET = BASE_URL + "get_favourite/0/%1$d?token=%2$s"; // String API_UPGRADE = BASE_URL + "version"; // String API_SEARCH = BASE_URL + "search/%1$d?keyword=%2$s"; // String XIAO_MI = "http://app.mi.com/details?id=com.chenjishi.u148&ref=search"; // } // Path: u148/app/src/main/java/com/chenjishi/u148/Config.java import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import com.chenjishi.u148.home.UserInfo; import com.chenjishi.u148.utils.Constants; package com.chenjishi.u148; /** * Created by jishichen on 2017/4/14. */ public class Config { private static final long TWO_DAYS = 2 * 24 * 60 * 60 * 1000; private static final String CONFIG_FILE_NAME = "u148_config"; private static final long VERSION_CHECK_INTERVAL = 24 * 60 * 60 * 1000; private static final String KEY_NEXT_TOKEN = "next_from"; public static final String KEY_UPDATE_TIME = "last_update_time"; public static final String KEY_CHECK_UPDATE_TIME = "last_check_time"; public static final String KEY_CHECK_VERSION = "check_version"; public static final String KEY_VIDEO_UPDATE_TIME = "last_update_time"; private static final String KEY_CACHE_CLEAR_TIME = "cache_clear_time"; private static final String KEY_CACHE_UPDATE_TIME = "cache_update_time"; private static final String KEY_REGISTER_TIME = "register_time"; private static final String KEY_USER_NAME = "user_name"; private static final String KEY_USER_SEX = "user_sex"; private static final String KEY_USER_ICON = "user_icon"; private static final String KEY_USER_TOKEN = "user_token"; private static final String KEY_THEME_MODE = "theme_mode"; private static final String SURPRISE_TITLE = "surprise_title"; private static final String SURPRISE_DESC = "surprise_desc"; private Config() { } public static boolean isLogin(Context ctx) { return null != getUser(ctx); } public static int getThemeMode(Context ctx) {
return getInt(ctx, KEY_THEME_MODE, Constants.MODE_DAY);
chenjishi/usite
u148/app/src/main/java/com/chenjishi/u148/Config.java
// Path: u148/app/src/main/java/com/chenjishi/u148/home/UserInfo.java // public class UserInfo implements Parcelable { // public String icon; // public String alias; // public String nickname; // public String sexStr; // public String statusStr; // public String id; // public String token; // // public static final Creator<UserInfo> CREATOR = new Creator<UserInfo>() { // @Override // public UserInfo createFromParcel(Parcel source) { // return new UserInfo(source); // } // // @Override // public UserInfo[] newArray(int size) { // return new UserInfo[size]; // } // }; // // public UserInfo() { // } // // public UserInfo(Parcel in) { // icon = in.readString(); // alias = in.readString(); // nickname = in.readString(); // sexStr = in.readString(); // statusStr = in.readString(); // id = in.readString(); // token = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(alias); // dest.writeString(nickname); // dest.writeString(sexStr); // dest.writeString(statusStr); // dest.writeString(id); // dest.writeString(token); // } // } // // Path: u148/app/src/main/java/com/chenjishi/u148/utils/Constants.java // public interface Constants { // // String KEY_FEED = "feed"; // String KEY_FEED_LIST = "feed_list"; // String KEY_FEED_INDEX = "index"; // // int MODE_DAY = 0; // int MODE_NIGHT = 1; // // String EVENT_ARTICLE_SHARE = "ArticleShare"; // String EVENT_IMAGE_SHARE = "ArticleShare"; // // String PARAM_TITLE = "title"; // String PARAM_URL = "url"; // // String BASE_URL = "http://api.u148.net/json/"; // // String API_FEED_LIST = BASE_URL + "%1$d/%2$d"; // String API_ARTICLE = BASE_URL + "article/%1$s"; // String API_ADD_FAVORITE = BASE_URL + "favourite?id=%1$s&token=%2$s"; // String API_DELETE_FAVORITE = BASE_URL + "del_favourite?id=%1$s&token=%2$s"; // String API_LOGIN = BASE_URL + "login"; // String API_REGISTER = BASE_URL + "register"; // String API_COMMENTS_GET = BASE_URL + "get_comment/%1$s/%2$d"; // String API_COMMENT_POST = BASE_URL + "comment"; // String API_FAVORITE_GET = BASE_URL + "get_favourite/0/%1$d?token=%2$s"; // String API_UPGRADE = BASE_URL + "version"; // String API_SEARCH = BASE_URL + "search/%1$d?keyword=%2$s"; // String XIAO_MI = "http://app.mi.com/details?id=com.chenjishi.u148&ref=search"; // }
import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import com.chenjishi.u148.home.UserInfo; import com.chenjishi.u148.utils.Constants;
private static final String KEY_USER_ICON = "user_icon"; private static final String KEY_USER_TOKEN = "user_token"; private static final String KEY_THEME_MODE = "theme_mode"; private static final String SURPRISE_TITLE = "surprise_title"; private static final String SURPRISE_DESC = "surprise_desc"; private Config() { } public static boolean isLogin(Context ctx) { return null != getUser(ctx); } public static int getThemeMode(Context ctx) { return getInt(ctx, KEY_THEME_MODE, Constants.MODE_DAY); } public static void setThemeMode(Context ctx, int mode) { putInt(ctx, KEY_THEME_MODE, mode); } public static void setRegisterTime(Context ctx, long time) { putLong(ctx, KEY_REGISTER_TIME, time); } public static long getRegisterTime(Context ctx) { return getLong(ctx, KEY_REGISTER_TIME, -1L); }
// Path: u148/app/src/main/java/com/chenjishi/u148/home/UserInfo.java // public class UserInfo implements Parcelable { // public String icon; // public String alias; // public String nickname; // public String sexStr; // public String statusStr; // public String id; // public String token; // // public static final Creator<UserInfo> CREATOR = new Creator<UserInfo>() { // @Override // public UserInfo createFromParcel(Parcel source) { // return new UserInfo(source); // } // // @Override // public UserInfo[] newArray(int size) { // return new UserInfo[size]; // } // }; // // public UserInfo() { // } // // public UserInfo(Parcel in) { // icon = in.readString(); // alias = in.readString(); // nickname = in.readString(); // sexStr = in.readString(); // statusStr = in.readString(); // id = in.readString(); // token = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(alias); // dest.writeString(nickname); // dest.writeString(sexStr); // dest.writeString(statusStr); // dest.writeString(id); // dest.writeString(token); // } // } // // Path: u148/app/src/main/java/com/chenjishi/u148/utils/Constants.java // public interface Constants { // // String KEY_FEED = "feed"; // String KEY_FEED_LIST = "feed_list"; // String KEY_FEED_INDEX = "index"; // // int MODE_DAY = 0; // int MODE_NIGHT = 1; // // String EVENT_ARTICLE_SHARE = "ArticleShare"; // String EVENT_IMAGE_SHARE = "ArticleShare"; // // String PARAM_TITLE = "title"; // String PARAM_URL = "url"; // // String BASE_URL = "http://api.u148.net/json/"; // // String API_FEED_LIST = BASE_URL + "%1$d/%2$d"; // String API_ARTICLE = BASE_URL + "article/%1$s"; // String API_ADD_FAVORITE = BASE_URL + "favourite?id=%1$s&token=%2$s"; // String API_DELETE_FAVORITE = BASE_URL + "del_favourite?id=%1$s&token=%2$s"; // String API_LOGIN = BASE_URL + "login"; // String API_REGISTER = BASE_URL + "register"; // String API_COMMENTS_GET = BASE_URL + "get_comment/%1$s/%2$d"; // String API_COMMENT_POST = BASE_URL + "comment"; // String API_FAVORITE_GET = BASE_URL + "get_favourite/0/%1$d?token=%2$s"; // String API_UPGRADE = BASE_URL + "version"; // String API_SEARCH = BASE_URL + "search/%1$d?keyword=%2$s"; // String XIAO_MI = "http://app.mi.com/details?id=com.chenjishi.u148&ref=search"; // } // Path: u148/app/src/main/java/com/chenjishi/u148/Config.java import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import com.chenjishi.u148.home.UserInfo; import com.chenjishi.u148.utils.Constants; private static final String KEY_USER_ICON = "user_icon"; private static final String KEY_USER_TOKEN = "user_token"; private static final String KEY_THEME_MODE = "theme_mode"; private static final String SURPRISE_TITLE = "surprise_title"; private static final String SURPRISE_DESC = "surprise_desc"; private Config() { } public static boolean isLogin(Context ctx) { return null != getUser(ctx); } public static int getThemeMode(Context ctx) { return getInt(ctx, KEY_THEME_MODE, Constants.MODE_DAY); } public static void setThemeMode(Context ctx, int mode) { putInt(ctx, KEY_THEME_MODE, mode); } public static void setRegisterTime(Context ctx, long time) { putLong(ctx, KEY_REGISTER_TIME, time); } public static long getRegisterTime(Context ctx) { return getLong(ctx, KEY_REGISTER_TIME, -1L); }
public static void setUser(Context ctx, UserInfo user) {
chenjishi/usite
u148/app/src/main/java/com/chenjishi/u148/utils/DBHelper.java
// Path: u148/app/src/main/java/com/chenjishi/u148/home/Feed.java // public class Feed implements Parcelable { // public String id; // public String status; // public String uid; // public int category; // public String title; // public String summary; // public String pic_min; // public String pic_mid; // public int star; // public long create_time; // public int count_browse; // public int count_review; // // public UserInfo usr; // // public static final Creator<Feed> CREATOR = new Creator<Feed>() { // @Override // public Feed createFromParcel(Parcel source) { // return new Feed(source); // } // // @Override // public Feed[] newArray(int size) { // return new Feed[size]; // } // }; // // public Feed() { // // } // // public Feed(Parcel in) { // id = in.readString(); // status = in.readString(); // uid = in.readString(); // category = in.readInt(); // title = in.readString(); // summary = in.readString(); // pic_min = in.readString(); // pic_mid = in.readString(); // star = in.readInt(); // create_time = in.readLong(); // count_browse = in.readInt(); // count_review = in.readInt(); // // usr = in.readParcelable(UserInfo.class.getClassLoader()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(id); // dest.writeString(status); // dest.writeString(uid); // dest.writeInt(category); // dest.writeString(title); // dest.writeString(summary); // dest.writeString(pic_min); // dest.writeString(pic_mid); // dest.writeInt(star); // dest.writeLong(create_time); // dest.writeInt(count_browse); // dest.writeInt(count_review); // // dest.writeParcelable(usr, flags); // } // } // // Path: u148/app/src/main/java/com/chenjishi/u148/home/UserInfo.java // public class UserInfo implements Parcelable { // public String icon; // public String alias; // public String nickname; // public String sexStr; // public String statusStr; // public String id; // public String token; // // public static final Creator<UserInfo> CREATOR = new Creator<UserInfo>() { // @Override // public UserInfo createFromParcel(Parcel source) { // return new UserInfo(source); // } // // @Override // public UserInfo[] newArray(int size) { // return new UserInfo[size]; // } // }; // // public UserInfo() { // } // // public UserInfo(Parcel in) { // icon = in.readString(); // alias = in.readString(); // nickname = in.readString(); // sexStr = in.readString(); // statusStr = in.readString(); // id = in.readString(); // token = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(alias); // dest.writeString(nickname); // dest.writeString(sexStr); // dest.writeString(statusStr); // dest.writeString(id); // dest.writeString(token); // } // }
import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.text.TextUtils; import android.util.Log; import com.chenjishi.u148.home.Feed; import com.chenjishi.u148.home.UserInfo; import java.util.ArrayList;
final String sql = "INSERT OR REPLACE INTO " + TB_NAME_ARTICLE + " VALUES (?, ?, ?)"; mDb.execSQL(sql, new String[] { id, String.valueOf(offset), String.valueOf(0) }); } public int getOffsetById(String id) { int result = 0; final String sql = "SELECT " + COL_ID + ", " + COL_OFFSET + ", " + COL_READ_STATE + " FROM " + TB_NAME_ARTICLE + " WHERE " + COL_ID + " = ?"; Cursor c = null; try { c = mDb.rawQuery(sql, new String[]{id}); if (c.moveToNext()) { result = c.getInt(1); } } finally { if (null != c) c.close(); } return result; }
// Path: u148/app/src/main/java/com/chenjishi/u148/home/Feed.java // public class Feed implements Parcelable { // public String id; // public String status; // public String uid; // public int category; // public String title; // public String summary; // public String pic_min; // public String pic_mid; // public int star; // public long create_time; // public int count_browse; // public int count_review; // // public UserInfo usr; // // public static final Creator<Feed> CREATOR = new Creator<Feed>() { // @Override // public Feed createFromParcel(Parcel source) { // return new Feed(source); // } // // @Override // public Feed[] newArray(int size) { // return new Feed[size]; // } // }; // // public Feed() { // // } // // public Feed(Parcel in) { // id = in.readString(); // status = in.readString(); // uid = in.readString(); // category = in.readInt(); // title = in.readString(); // summary = in.readString(); // pic_min = in.readString(); // pic_mid = in.readString(); // star = in.readInt(); // create_time = in.readLong(); // count_browse = in.readInt(); // count_review = in.readInt(); // // usr = in.readParcelable(UserInfo.class.getClassLoader()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(id); // dest.writeString(status); // dest.writeString(uid); // dest.writeInt(category); // dest.writeString(title); // dest.writeString(summary); // dest.writeString(pic_min); // dest.writeString(pic_mid); // dest.writeInt(star); // dest.writeLong(create_time); // dest.writeInt(count_browse); // dest.writeInt(count_review); // // dest.writeParcelable(usr, flags); // } // } // // Path: u148/app/src/main/java/com/chenjishi/u148/home/UserInfo.java // public class UserInfo implements Parcelable { // public String icon; // public String alias; // public String nickname; // public String sexStr; // public String statusStr; // public String id; // public String token; // // public static final Creator<UserInfo> CREATOR = new Creator<UserInfo>() { // @Override // public UserInfo createFromParcel(Parcel source) { // return new UserInfo(source); // } // // @Override // public UserInfo[] newArray(int size) { // return new UserInfo[size]; // } // }; // // public UserInfo() { // } // // public UserInfo(Parcel in) { // icon = in.readString(); // alias = in.readString(); // nickname = in.readString(); // sexStr = in.readString(); // statusStr = in.readString(); // id = in.readString(); // token = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(alias); // dest.writeString(nickname); // dest.writeString(sexStr); // dest.writeString(statusStr); // dest.writeString(id); // dest.writeString(token); // } // } // Path: u148/app/src/main/java/com/chenjishi/u148/utils/DBHelper.java import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.text.TextUtils; import android.util.Log; import com.chenjishi.u148.home.Feed; import com.chenjishi.u148.home.UserInfo; import java.util.ArrayList; final String sql = "INSERT OR REPLACE INTO " + TB_NAME_ARTICLE + " VALUES (?, ?, ?)"; mDb.execSQL(sql, new String[] { id, String.valueOf(offset), String.valueOf(0) }); } public int getOffsetById(String id) { int result = 0; final String sql = "SELECT " + COL_ID + ", " + COL_OFFSET + ", " + COL_READ_STATE + " FROM " + TB_NAME_ARTICLE + " WHERE " + COL_ID + " = ?"; Cursor c = null; try { c = mDb.rawQuery(sql, new String[]{id}); if (c.moveToNext()) { result = c.getInt(1); } } finally { if (null != c) c.close(); } return result; }
public Feed getFavoriteById(String id) {
chenjishi/usite
u148/app/src/main/java/com/chenjishi/u148/utils/DBHelper.java
// Path: u148/app/src/main/java/com/chenjishi/u148/home/Feed.java // public class Feed implements Parcelable { // public String id; // public String status; // public String uid; // public int category; // public String title; // public String summary; // public String pic_min; // public String pic_mid; // public int star; // public long create_time; // public int count_browse; // public int count_review; // // public UserInfo usr; // // public static final Creator<Feed> CREATOR = new Creator<Feed>() { // @Override // public Feed createFromParcel(Parcel source) { // return new Feed(source); // } // // @Override // public Feed[] newArray(int size) { // return new Feed[size]; // } // }; // // public Feed() { // // } // // public Feed(Parcel in) { // id = in.readString(); // status = in.readString(); // uid = in.readString(); // category = in.readInt(); // title = in.readString(); // summary = in.readString(); // pic_min = in.readString(); // pic_mid = in.readString(); // star = in.readInt(); // create_time = in.readLong(); // count_browse = in.readInt(); // count_review = in.readInt(); // // usr = in.readParcelable(UserInfo.class.getClassLoader()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(id); // dest.writeString(status); // dest.writeString(uid); // dest.writeInt(category); // dest.writeString(title); // dest.writeString(summary); // dest.writeString(pic_min); // dest.writeString(pic_mid); // dest.writeInt(star); // dest.writeLong(create_time); // dest.writeInt(count_browse); // dest.writeInt(count_review); // // dest.writeParcelable(usr, flags); // } // } // // Path: u148/app/src/main/java/com/chenjishi/u148/home/UserInfo.java // public class UserInfo implements Parcelable { // public String icon; // public String alias; // public String nickname; // public String sexStr; // public String statusStr; // public String id; // public String token; // // public static final Creator<UserInfo> CREATOR = new Creator<UserInfo>() { // @Override // public UserInfo createFromParcel(Parcel source) { // return new UserInfo(source); // } // // @Override // public UserInfo[] newArray(int size) { // return new UserInfo[size]; // } // }; // // public UserInfo() { // } // // public UserInfo(Parcel in) { // icon = in.readString(); // alias = in.readString(); // nickname = in.readString(); // sexStr = in.readString(); // statusStr = in.readString(); // id = in.readString(); // token = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(alias); // dest.writeString(nickname); // dest.writeString(sexStr); // dest.writeString(statusStr); // dest.writeString(id); // dest.writeString(token); // } // }
import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.text.TextUtils; import android.util.Log; import com.chenjishi.u148.home.Feed; import com.chenjishi.u148.home.UserInfo; import java.util.ArrayList;
try { c = mDb.rawQuery(sql, new String[]{id}); if (c.moveToNext()) { result = c.getInt(1); } } finally { if (null != c) c.close(); } return result; } public Feed getFavoriteById(String id) { if (TextUtils.isEmpty(id)) return null; Feed feed = null; final String sql = "SELECT * FROM " + TB_NAME_FAVORITE + " WHERE " + COL_ID + " = " + id; Cursor cursor = null; try { cursor = mDb.rawQuery(sql, null); if (cursor.moveToNext()) { feed = new Feed(); feed.id = cursor.getString(0); feed.uid = cursor.getString(1); feed.category = cursor.getInt(2); feed.title = cursor.getString(3); feed.summary = cursor.getString(4); feed.pic_mid = cursor.getString(5); feed.create_time = cursor.getLong(6);
// Path: u148/app/src/main/java/com/chenjishi/u148/home/Feed.java // public class Feed implements Parcelable { // public String id; // public String status; // public String uid; // public int category; // public String title; // public String summary; // public String pic_min; // public String pic_mid; // public int star; // public long create_time; // public int count_browse; // public int count_review; // // public UserInfo usr; // // public static final Creator<Feed> CREATOR = new Creator<Feed>() { // @Override // public Feed createFromParcel(Parcel source) { // return new Feed(source); // } // // @Override // public Feed[] newArray(int size) { // return new Feed[size]; // } // }; // // public Feed() { // // } // // public Feed(Parcel in) { // id = in.readString(); // status = in.readString(); // uid = in.readString(); // category = in.readInt(); // title = in.readString(); // summary = in.readString(); // pic_min = in.readString(); // pic_mid = in.readString(); // star = in.readInt(); // create_time = in.readLong(); // count_browse = in.readInt(); // count_review = in.readInt(); // // usr = in.readParcelable(UserInfo.class.getClassLoader()); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(id); // dest.writeString(status); // dest.writeString(uid); // dest.writeInt(category); // dest.writeString(title); // dest.writeString(summary); // dest.writeString(pic_min); // dest.writeString(pic_mid); // dest.writeInt(star); // dest.writeLong(create_time); // dest.writeInt(count_browse); // dest.writeInt(count_review); // // dest.writeParcelable(usr, flags); // } // } // // Path: u148/app/src/main/java/com/chenjishi/u148/home/UserInfo.java // public class UserInfo implements Parcelable { // public String icon; // public String alias; // public String nickname; // public String sexStr; // public String statusStr; // public String id; // public String token; // // public static final Creator<UserInfo> CREATOR = new Creator<UserInfo>() { // @Override // public UserInfo createFromParcel(Parcel source) { // return new UserInfo(source); // } // // @Override // public UserInfo[] newArray(int size) { // return new UserInfo[size]; // } // }; // // public UserInfo() { // } // // public UserInfo(Parcel in) { // icon = in.readString(); // alias = in.readString(); // nickname = in.readString(); // sexStr = in.readString(); // statusStr = in.readString(); // id = in.readString(); // token = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(alias); // dest.writeString(nickname); // dest.writeString(sexStr); // dest.writeString(statusStr); // dest.writeString(id); // dest.writeString(token); // } // } // Path: u148/app/src/main/java/com/chenjishi/u148/utils/DBHelper.java import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.text.TextUtils; import android.util.Log; import com.chenjishi.u148.home.Feed; import com.chenjishi.u148.home.UserInfo; import java.util.ArrayList; try { c = mDb.rawQuery(sql, new String[]{id}); if (c.moveToNext()) { result = c.getInt(1); } } finally { if (null != c) c.close(); } return result; } public Feed getFavoriteById(String id) { if (TextUtils.isEmpty(id)) return null; Feed feed = null; final String sql = "SELECT * FROM " + TB_NAME_FAVORITE + " WHERE " + COL_ID + " = " + id; Cursor cursor = null; try { cursor = mDb.rawQuery(sql, null); if (cursor.moveToNext()) { feed = new Feed(); feed.id = cursor.getString(0); feed.uid = cursor.getString(1); feed.category = cursor.getInt(2); feed.title = cursor.getString(3); feed.summary = cursor.getString(4); feed.pic_mid = cursor.getString(5); feed.create_time = cursor.getLong(6);
UserInfo usr = new UserInfo();
chenjishi/usite
u148/app/src/main/java/com/chenjishi/u148/home/FeedListFragment.java
// Path: u148/app/src/main/java/com/chenjishi/u148/widget/LoadingView.java // public class LoadingView extends FrameLayout { // // public TextView textView; // // public LoadingView(Context context) { // this(context, null); // } // // public LoadingView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public LoadingView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // init(); // } // // private void init() { // Context context = getContext(); // // LayoutInflater.from(context).inflate(R.layout.empty_view, this); // } // // public void setError(String text) { // findViewById(R.id.progress_bar).setVisibility(GONE); // textView = (TextView) findViewById(R.id.tv_empty_tip); // textView.setText(text); // textView.setVisibility(VISIBLE); // } // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import com.chenjishi.u148.R; import com.chenjishi.u148.utils.*; import com.chenjishi.u148.widget.LoadingView; import java.util.ArrayList; import java.util.List; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static com.chenjishi.u148.utils.Constants.API_FEED_LIST;
package com.chenjishi.u148.home; /** * Created with IntelliJ IDEA. * User: chenjishi * Date: 13-11-28 * Time: 下午3:20 * To change this template use File | Settings | File Templates. */ public class FeedListFragment extends Fragment implements Listener<FeedDoc>, ErrorListener, SwipeRefreshLayout.OnRefreshListener, OnPageEndListener { private SwipeRefreshLayout swipeRefreshLayout; private FrameLayout mContentView; protected int mPage = 1; private int category; private boolean dataLoaded;
// Path: u148/app/src/main/java/com/chenjishi/u148/widget/LoadingView.java // public class LoadingView extends FrameLayout { // // public TextView textView; // // public LoadingView(Context context) { // this(context, null); // } // // public LoadingView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public LoadingView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // init(); // } // // private void init() { // Context context = getContext(); // // LayoutInflater.from(context).inflate(R.layout.empty_view, this); // } // // public void setError(String text) { // findViewById(R.id.progress_bar).setVisibility(GONE); // textView = (TextView) findViewById(R.id.tv_empty_tip); // textView.setText(text); // textView.setVisibility(VISIBLE); // } // } // Path: u148/app/src/main/java/com/chenjishi/u148/home/FeedListFragment.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import com.chenjishi.u148.R; import com.chenjishi.u148.utils.*; import com.chenjishi.u148.widget.LoadingView; import java.util.ArrayList; import java.util.List; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static com.chenjishi.u148.utils.Constants.API_FEED_LIST; package com.chenjishi.u148.home; /** * Created with IntelliJ IDEA. * User: chenjishi * Date: 13-11-28 * Time: 下午3:20 * To change this template use File | Settings | File Templates. */ public class FeedListFragment extends Fragment implements Listener<FeedDoc>, ErrorListener, SwipeRefreshLayout.OnRefreshListener, OnPageEndListener { private SwipeRefreshLayout swipeRefreshLayout; private FrameLayout mContentView; protected int mPage = 1; private int category; private boolean dataLoaded;
private LoadingView mLoadingView;
chenjishi/usite
u148/app/src/main/java/com/chenjishi/u148/utils/DividerItemDecoration.java
// Path: u148/app/src/main/java/com/chenjishi/u148/Config.java // public class Config { // // private static final long TWO_DAYS = 2 * 24 * 60 * 60 * 1000; // // private static final String CONFIG_FILE_NAME = "u148_config"; // // private static final long VERSION_CHECK_INTERVAL = 24 * 60 * 60 * 1000; // // private static final String KEY_NEXT_TOKEN = "next_from"; // // public static final String KEY_UPDATE_TIME = "last_update_time"; // // public static final String KEY_CHECK_UPDATE_TIME = "last_check_time"; // // public static final String KEY_CHECK_VERSION = "check_version"; // // public static final String KEY_VIDEO_UPDATE_TIME = "last_update_time"; // // private static final String KEY_CACHE_CLEAR_TIME = "cache_clear_time"; // private static final String KEY_CACHE_UPDATE_TIME = "cache_update_time"; // // private static final String KEY_REGISTER_TIME = "register_time"; // // private static final String KEY_USER_NAME = "user_name"; // private static final String KEY_USER_SEX = "user_sex"; // private static final String KEY_USER_ICON = "user_icon"; // private static final String KEY_USER_TOKEN = "user_token"; // // private static final String KEY_THEME_MODE = "theme_mode"; // private static final String SURPRISE_TITLE = "surprise_title"; // private static final String SURPRISE_DESC = "surprise_desc"; // // private Config() { // } // // public static boolean isLogin(Context ctx) { // return null != getUser(ctx); // } // // public static int getThemeMode(Context ctx) { // return getInt(ctx, KEY_THEME_MODE, Constants.MODE_DAY); // } // // public static void setThemeMode(Context ctx, int mode) { // putInt(ctx, KEY_THEME_MODE, mode); // } // // public static void setRegisterTime(Context ctx, long time) { // putLong(ctx, KEY_REGISTER_TIME, time); // } // // public static long getRegisterTime(Context ctx) { // return getLong(ctx, KEY_REGISTER_TIME, -1L); // } // // public static void setUser(Context ctx, UserInfo user) { // if (null != user && !TextUtils.isEmpty(user.token)) { // putString(ctx, KEY_USER_NAME, user.nickname); // putString(ctx, KEY_USER_SEX, user.sexStr); // putString(ctx, KEY_USER_ICON, user.icon); // putString(ctx, KEY_USER_TOKEN, user.token); // } else { // putString(ctx, KEY_USER_NAME, ""); // putString(ctx, KEY_USER_SEX, ""); // putString(ctx, KEY_USER_ICON, ""); // putString(ctx, KEY_USER_TOKEN, ""); // } // } // // public static UserInfo getUser(Context ctx) { // String token = getString(ctx, KEY_USER_TOKEN, ""); // // if (!TextUtils.isEmpty(token)) { // UserInfo user = new UserInfo(); // // user.nickname = getString(ctx, KEY_USER_NAME, ""); // user.sexStr = getString(ctx, KEY_USER_SEX, ""); // user.icon = getString(ctx, KEY_USER_ICON, ""); // user.token = getString(ctx, KEY_USER_TOKEN, ""); // // return user; // } else { // return null; // } // } // // public static void saveSurpriseTitle(Context ctx, String title) { // putString(ctx, SURPRISE_TITLE, title); // } // // public static void saveSurpriseDesc(Context ctx, String desc) { // putString(ctx, SURPRISE_DESC, desc); // } // // public static String getSurpriseTitle(Context ctx) { // return getString(ctx, SURPRISE_TITLE, ""); // } // // public static String getSurpriseDesc(Context ctx) { // return getString(ctx, SURPRISE_DESC, ""); // } // // public static void setClearCacheTime(Context ctx, long t) { // putLong(ctx, KEY_CACHE_CLEAR_TIME, t + TWO_DAYS); // } // // public static long getClearCacheTime(Context ctx) { // return getLong(ctx, KEY_CACHE_CLEAR_TIME, -1L); // } // // public static int getInt(Context context, String key, int defaultValue) { // return getPreferences(context).getInt(key, defaultValue); // } // // public static void putInt(Context context, String key, int value) { // SharedPreferences.Editor editor = getPreferences(context).edit(); // editor.putInt(key, value); // editor.apply(); // } // // public static long getLong(Context context, String key, long defaultValue) { // return getPreferences(context).getLong(key, defaultValue); // } // // public static void putLong(Context context, String key, long value) { // SharedPreferences.Editor editor = getPreferences(context).edit(); // editor.putLong(key, value); // editor.apply(); // } // // public static String getString(Context context, String key, String defaultValue) { // return getPreferences(context).getString(key, defaultValue); // } // // public static void putString(Context context, String key, String value) { // SharedPreferences.Editor editor = getPreferences(context).edit(); // editor.putString(key, value); // editor.apply(); // } // // private static SharedPreferences getPreferences(Context context) { // return context.getSharedPreferences(CONFIG_FILE_NAME, Context.MODE_PRIVATE); // } // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.support.v7.widget.RecyclerView; import android.view.View; import com.chenjishi.u148.Config;
package com.chenjishi.u148.utils; /** * Created by chenjishi on 16/1/19. */ public class DividerItemDecoration extends RecyclerView.ItemDecoration { private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); public DividerItemDecoration(Context context) { mPaint.setStyle(Paint.Style.FILL);
// Path: u148/app/src/main/java/com/chenjishi/u148/Config.java // public class Config { // // private static final long TWO_DAYS = 2 * 24 * 60 * 60 * 1000; // // private static final String CONFIG_FILE_NAME = "u148_config"; // // private static final long VERSION_CHECK_INTERVAL = 24 * 60 * 60 * 1000; // // private static final String KEY_NEXT_TOKEN = "next_from"; // // public static final String KEY_UPDATE_TIME = "last_update_time"; // // public static final String KEY_CHECK_UPDATE_TIME = "last_check_time"; // // public static final String KEY_CHECK_VERSION = "check_version"; // // public static final String KEY_VIDEO_UPDATE_TIME = "last_update_time"; // // private static final String KEY_CACHE_CLEAR_TIME = "cache_clear_time"; // private static final String KEY_CACHE_UPDATE_TIME = "cache_update_time"; // // private static final String KEY_REGISTER_TIME = "register_time"; // // private static final String KEY_USER_NAME = "user_name"; // private static final String KEY_USER_SEX = "user_sex"; // private static final String KEY_USER_ICON = "user_icon"; // private static final String KEY_USER_TOKEN = "user_token"; // // private static final String KEY_THEME_MODE = "theme_mode"; // private static final String SURPRISE_TITLE = "surprise_title"; // private static final String SURPRISE_DESC = "surprise_desc"; // // private Config() { // } // // public static boolean isLogin(Context ctx) { // return null != getUser(ctx); // } // // public static int getThemeMode(Context ctx) { // return getInt(ctx, KEY_THEME_MODE, Constants.MODE_DAY); // } // // public static void setThemeMode(Context ctx, int mode) { // putInt(ctx, KEY_THEME_MODE, mode); // } // // public static void setRegisterTime(Context ctx, long time) { // putLong(ctx, KEY_REGISTER_TIME, time); // } // // public static long getRegisterTime(Context ctx) { // return getLong(ctx, KEY_REGISTER_TIME, -1L); // } // // public static void setUser(Context ctx, UserInfo user) { // if (null != user && !TextUtils.isEmpty(user.token)) { // putString(ctx, KEY_USER_NAME, user.nickname); // putString(ctx, KEY_USER_SEX, user.sexStr); // putString(ctx, KEY_USER_ICON, user.icon); // putString(ctx, KEY_USER_TOKEN, user.token); // } else { // putString(ctx, KEY_USER_NAME, ""); // putString(ctx, KEY_USER_SEX, ""); // putString(ctx, KEY_USER_ICON, ""); // putString(ctx, KEY_USER_TOKEN, ""); // } // } // // public static UserInfo getUser(Context ctx) { // String token = getString(ctx, KEY_USER_TOKEN, ""); // // if (!TextUtils.isEmpty(token)) { // UserInfo user = new UserInfo(); // // user.nickname = getString(ctx, KEY_USER_NAME, ""); // user.sexStr = getString(ctx, KEY_USER_SEX, ""); // user.icon = getString(ctx, KEY_USER_ICON, ""); // user.token = getString(ctx, KEY_USER_TOKEN, ""); // // return user; // } else { // return null; // } // } // // public static void saveSurpriseTitle(Context ctx, String title) { // putString(ctx, SURPRISE_TITLE, title); // } // // public static void saveSurpriseDesc(Context ctx, String desc) { // putString(ctx, SURPRISE_DESC, desc); // } // // public static String getSurpriseTitle(Context ctx) { // return getString(ctx, SURPRISE_TITLE, ""); // } // // public static String getSurpriseDesc(Context ctx) { // return getString(ctx, SURPRISE_DESC, ""); // } // // public static void setClearCacheTime(Context ctx, long t) { // putLong(ctx, KEY_CACHE_CLEAR_TIME, t + TWO_DAYS); // } // // public static long getClearCacheTime(Context ctx) { // return getLong(ctx, KEY_CACHE_CLEAR_TIME, -1L); // } // // public static int getInt(Context context, String key, int defaultValue) { // return getPreferences(context).getInt(key, defaultValue); // } // // public static void putInt(Context context, String key, int value) { // SharedPreferences.Editor editor = getPreferences(context).edit(); // editor.putInt(key, value); // editor.apply(); // } // // public static long getLong(Context context, String key, long defaultValue) { // return getPreferences(context).getLong(key, defaultValue); // } // // public static void putLong(Context context, String key, long value) { // SharedPreferences.Editor editor = getPreferences(context).edit(); // editor.putLong(key, value); // editor.apply(); // } // // public static String getString(Context context, String key, String defaultValue) { // return getPreferences(context).getString(key, defaultValue); // } // // public static void putString(Context context, String key, String value) { // SharedPreferences.Editor editor = getPreferences(context).edit(); // editor.putString(key, value); // editor.apply(); // } // // private static SharedPreferences getPreferences(Context context) { // return context.getSharedPreferences(CONFIG_FILE_NAME, Context.MODE_PRIVATE); // } // } // Path: u148/app/src/main/java/com/chenjishi/u148/utils/DividerItemDecoration.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.support.v7.widget.RecyclerView; import android.view.View; import com.chenjishi.u148.Config; package com.chenjishi.u148.utils; /** * Created by chenjishi on 16/1/19. */ public class DividerItemDecoration extends RecyclerView.ItemDecoration { private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); public DividerItemDecoration(Context context) { mPaint.setStyle(Paint.Style.FILL);
int theme = Config.getThemeMode(context);
chenjishi/usite
u148/app/src/main/java/com/chenjishi/u148/U148.java
// Path: u148/app/src/main/java/com/chenjishi/u148/utils/FileUtils.java // public class FileUtils { // // private FileUtils() { // } // // public static void init(Context context) { // mkDirs(getImageCacheDir(context)); // mkDirs(getDataCacheDir(context)); // } // // public static void mkDirs(String dirPath) { // File file = new File(dirPath); // if (!file.exists()) file.mkdirs(); // } // // public static String getImageCacheDir(Context context) { // return getRootDir(context) + "/image/"; // } // // public static String getDataCacheDir(Context context) { // return getRootDir(context) + "/data/"; // } // // public static String getTempCacheDir() { // return getSDCardDir() + "/u148/"; // } // // public static String getSDCardDir() { // if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { // return Environment.getExternalStorageDirectory().getPath(); // } // return null; // } // // public static String getRootDir(Context context) { // if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { // String cacheDir = "/Android/data/" + context.getPackageName(); // return Environment.getExternalStorageDirectory() + cacheDir; // } else { // String path = null; // File cacheDir = context.getCacheDir(); // if (cacheDir.exists()) path = cacheDir.getAbsolutePath(); // return path; // } // } // }
import android.app.Application; import com.chenjishi.u148.utils.FileUtils; import com.flurry.android.FlurryAgent;
package com.chenjishi.u148; /** * Created by jishichen on 2017/4/14. */ public class U148 extends Application { @Override public void onCreate() { super.onCreate();
// Path: u148/app/src/main/java/com/chenjishi/u148/utils/FileUtils.java // public class FileUtils { // // private FileUtils() { // } // // public static void init(Context context) { // mkDirs(getImageCacheDir(context)); // mkDirs(getDataCacheDir(context)); // } // // public static void mkDirs(String dirPath) { // File file = new File(dirPath); // if (!file.exists()) file.mkdirs(); // } // // public static String getImageCacheDir(Context context) { // return getRootDir(context) + "/image/"; // } // // public static String getDataCacheDir(Context context) { // return getRootDir(context) + "/data/"; // } // // public static String getTempCacheDir() { // return getSDCardDir() + "/u148/"; // } // // public static String getSDCardDir() { // if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { // return Environment.getExternalStorageDirectory().getPath(); // } // return null; // } // // public static String getRootDir(Context context) { // if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { // String cacheDir = "/Android/data/" + context.getPackageName(); // return Environment.getExternalStorageDirectory() + cacheDir; // } else { // String path = null; // File cacheDir = context.getCacheDir(); // if (cacheDir.exists()) path = cacheDir.getAbsolutePath(); // return path; // } // } // } // Path: u148/app/src/main/java/com/chenjishi/u148/U148.java import android.app.Application; import com.chenjishi.u148.utils.FileUtils; import com.flurry.android.FlurryAgent; package com.chenjishi.u148; /** * Created by jishichen on 2017/4/14. */ public class U148 extends Application { @Override public void onCreate() { super.onCreate();
FileUtils.init(this);
chenjishi/usite
u148/app/src/main/java/com/chenjishi/u148/widget/TabPageIndicator.java
// Path: u148/app/src/main/java/com/chenjishi/u148/utils/Constants.java // public interface Constants { // // String KEY_FEED = "feed"; // String KEY_FEED_LIST = "feed_list"; // String KEY_FEED_INDEX = "index"; // // int MODE_DAY = 0; // int MODE_NIGHT = 1; // // String EVENT_ARTICLE_SHARE = "ArticleShare"; // String EVENT_IMAGE_SHARE = "ArticleShare"; // // String PARAM_TITLE = "title"; // String PARAM_URL = "url"; // // String BASE_URL = "http://api.u148.net/json/"; // // String API_FEED_LIST = BASE_URL + "%1$d/%2$d"; // String API_ARTICLE = BASE_URL + "article/%1$s"; // String API_ADD_FAVORITE = BASE_URL + "favourite?id=%1$s&token=%2$s"; // String API_DELETE_FAVORITE = BASE_URL + "del_favourite?id=%1$s&token=%2$s"; // String API_LOGIN = BASE_URL + "login"; // String API_REGISTER = BASE_URL + "register"; // String API_COMMENTS_GET = BASE_URL + "get_comment/%1$s/%2$d"; // String API_COMMENT_POST = BASE_URL + "comment"; // String API_FAVORITE_GET = BASE_URL + "get_favourite/0/%1$d?token=%2$s"; // String API_UPGRADE = BASE_URL + "version"; // String API_SEARCH = BASE_URL + "search/%1$d?keyword=%2$s"; // String XIAO_MI = "http://app.mi.com/details?id=com.chenjishi.u148&ref=search"; // }
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.HorizontalScrollView; import android.widget.LinearLayout; import android.widget.TextView; import com.chenjishi.u148.R; import com.chenjishi.u148.utils.Constants;
setCurrentItem(mSelectedTabIndex); requestLayout(); } @Override public void setViewPager(ViewPager view, int initialPosition) { setViewPager(view); setCurrentItem(initialPosition); } @Override public void setCurrentItem(int item) { if (mViewPager == null) { throw new IllegalStateException("ViewPager has not been bound."); } mSelectedTabIndex = item; mViewPager.setCurrentItem(item); final int tabCount = mTabLayout.getChildCount(); for (int i = 0; i < tabCount; i++) { final View child = mTabLayout.getChildAt(i); final boolean isSelected = (i == item); child.setSelected(isSelected); if (isSelected) { animateToTab(item); } } } public void setTheme(int theme) {
// Path: u148/app/src/main/java/com/chenjishi/u148/utils/Constants.java // public interface Constants { // // String KEY_FEED = "feed"; // String KEY_FEED_LIST = "feed_list"; // String KEY_FEED_INDEX = "index"; // // int MODE_DAY = 0; // int MODE_NIGHT = 1; // // String EVENT_ARTICLE_SHARE = "ArticleShare"; // String EVENT_IMAGE_SHARE = "ArticleShare"; // // String PARAM_TITLE = "title"; // String PARAM_URL = "url"; // // String BASE_URL = "http://api.u148.net/json/"; // // String API_FEED_LIST = BASE_URL + "%1$d/%2$d"; // String API_ARTICLE = BASE_URL + "article/%1$s"; // String API_ADD_FAVORITE = BASE_URL + "favourite?id=%1$s&token=%2$s"; // String API_DELETE_FAVORITE = BASE_URL + "del_favourite?id=%1$s&token=%2$s"; // String API_LOGIN = BASE_URL + "login"; // String API_REGISTER = BASE_URL + "register"; // String API_COMMENTS_GET = BASE_URL + "get_comment/%1$s/%2$d"; // String API_COMMENT_POST = BASE_URL + "comment"; // String API_FAVORITE_GET = BASE_URL + "get_favourite/0/%1$d?token=%2$s"; // String API_UPGRADE = BASE_URL + "version"; // String API_SEARCH = BASE_URL + "search/%1$d?keyword=%2$s"; // String XIAO_MI = "http://app.mi.com/details?id=com.chenjishi.u148&ref=search"; // } // Path: u148/app/src/main/java/com/chenjishi/u148/widget/TabPageIndicator.java import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.HorizontalScrollView; import android.widget.LinearLayout; import android.widget.TextView; import com.chenjishi.u148.R; import com.chenjishi.u148.utils.Constants; setCurrentItem(mSelectedTabIndex); requestLayout(); } @Override public void setViewPager(ViewPager view, int initialPosition) { setViewPager(view); setCurrentItem(initialPosition); } @Override public void setCurrentItem(int item) { if (mViewPager == null) { throw new IllegalStateException("ViewPager has not been bound."); } mSelectedTabIndex = item; mViewPager.setCurrentItem(item); final int tabCount = mTabLayout.getChildCount(); for (int i = 0; i < tabCount; i++) { final View child = mTabLayout.getChildAt(i); final boolean isSelected = (i == item); child.setSelected(isSelected); if (isSelected) { animateToTab(item); } } } public void setTheme(int theme) {
final boolean isNight = theme == Constants.MODE_NIGHT;
spring-projects/spring-data-keyvalue
src/test/java/org/springframework/data/keyvalue/core/mapping/context/KeyValueMappingContextUnitTests.java
// Path: src/main/java/org/springframework/data/keyvalue/core/mapping/KeyValuePersistentEntity.java // public interface KeyValuePersistentEntity<T, P extends KeyValuePersistentProperty<P>> // extends MutablePersistentEntity<T, P> { // // /** // * Get the {@literal keySpace} a given entity assigns to. // * // * @return can be {@literal null}. // */ // @Nullable // String getKeySpace(); // } // // Path: src/main/java/org/springframework/data/keyvalue/core/mapping/KeyValuePersistentProperty.java // public class KeyValuePersistentProperty<P extends KeyValuePersistentProperty<P>> // extends AnnotationBasedPersistentProperty<P> { // // public KeyValuePersistentProperty(Property property, PersistentEntity<?, P> owner, // SimpleTypeHolder simpleTypeHolder) { // super(property, owner, simpleTypeHolder); // } // // /* // * (non-Javadoc) // * @see org.springframework.data.mapping.model.AbstractPersistentProperty#createAssociation() // */ // @Override // @SuppressWarnings("unchecked") // protected Association<P> createAssociation() { // return new Association<>((P) this, null); // } // }
import static org.assertj.core.api.Assertions.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.UUID; import org.junit.jupiter.api.Test; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentProperty;
/* * Copyright 2021-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core.mapping.context; /** * Unit test for {@link KeyValueMappingContext}. * * @author Mark Paluch */ class KeyValueMappingContextUnitTests<P extends KeyValuePersistentProperty<P>> { @Test void shouldNotCreateEntitiesForJavaStandardTypes() {
// Path: src/main/java/org/springframework/data/keyvalue/core/mapping/KeyValuePersistentEntity.java // public interface KeyValuePersistentEntity<T, P extends KeyValuePersistentProperty<P>> // extends MutablePersistentEntity<T, P> { // // /** // * Get the {@literal keySpace} a given entity assigns to. // * // * @return can be {@literal null}. // */ // @Nullable // String getKeySpace(); // } // // Path: src/main/java/org/springframework/data/keyvalue/core/mapping/KeyValuePersistentProperty.java // public class KeyValuePersistentProperty<P extends KeyValuePersistentProperty<P>> // extends AnnotationBasedPersistentProperty<P> { // // public KeyValuePersistentProperty(Property property, PersistentEntity<?, P> owner, // SimpleTypeHolder simpleTypeHolder) { // super(property, owner, simpleTypeHolder); // } // // /* // * (non-Javadoc) // * @see org.springframework.data.mapping.model.AbstractPersistentProperty#createAssociation() // */ // @Override // @SuppressWarnings("unchecked") // protected Association<P> createAssociation() { // return new Association<>((P) this, null); // } // } // Path: src/test/java/org/springframework/data/keyvalue/core/mapping/context/KeyValueMappingContextUnitTests.java import static org.assertj.core.api.Assertions.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.UUID; import org.junit.jupiter.api.Test; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentProperty; /* * Copyright 2021-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core.mapping.context; /** * Unit test for {@link KeyValueMappingContext}. * * @author Mark Paluch */ class KeyValueMappingContextUnitTests<P extends KeyValuePersistentProperty<P>> { @Test void shouldNotCreateEntitiesForJavaStandardTypes() {
KeyValueMappingContext<KeyValuePersistentEntity<?, P>, P> mappingContext = new KeyValueMappingContext<>();
spring-projects/spring-data-keyvalue
src/main/java/org/springframework/data/keyvalue/core/mapping/context/KeyValueMappingContext.java
// Path: src/main/java/org/springframework/data/keyvalue/core/mapping/BasicKeyValuePersistentEntity.java // public class BasicKeyValuePersistentEntity<T, P extends KeyValuePersistentProperty<P>> // extends BasicPersistentEntity<T, P> implements KeyValuePersistentEntity<T, P> { // // private static final SpelExpressionParser PARSER = new SpelExpressionParser(); // // private static final KeySpaceResolver DEFAULT_FALLBACK_RESOLVER = ClassNameKeySpaceResolver.INSTANCE; // // private final @Nullable Expression keyspaceExpression; // private final @Nullable String keyspace; // // /** // * @param information must not be {@literal null}. // * @param fallbackKeySpaceResolver can be {@literal null}. // */ // public BasicKeyValuePersistentEntity(TypeInformation<T> information, // @Nullable KeySpaceResolver fallbackKeySpaceResolver) { // // super(information); // // Class<T> type = information.getType(); // String keySpace = AnnotationBasedKeySpaceResolver.INSTANCE.resolveKeySpace(type); // // if (StringUtils.hasText(keySpace)) { // // this.keyspace = keySpace; // this.keyspaceExpression = detectExpression(keySpace); // } else { // // this.keyspace = resolveKeyspace(fallbackKeySpaceResolver, type); // this.keyspaceExpression = null; // } // } // // /** // * Returns a SpEL {@link Expression} if the given {@link String} is actually an expression that does not evaluate to a // * {@link LiteralExpression} (indicating that no subsequent evaluation is necessary). // * // * @param potentialExpression must not be {@literal null} // * @return the parsed {@link Expression} or {@literal null}. // */ // @Nullable // private static Expression detectExpression(String potentialExpression) { // // Expression expression = PARSER.parseExpression(potentialExpression, ParserContext.TEMPLATE_EXPRESSION); // return expression instanceof LiteralExpression ? null : expression; // } // // @Nullable // private static String resolveKeyspace(@Nullable KeySpaceResolver fallbackKeySpaceResolver, Class<?> type) { // return (fallbackKeySpaceResolver == null ? DEFAULT_FALLBACK_RESOLVER : fallbackKeySpaceResolver) // .resolveKeySpace(type); // } // // /* // * (non-Javadoc) // * @see org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity#getKeySpace() // */ // @Override // public String getKeySpace() { // return keyspaceExpression == null // // ? keyspace // // : keyspaceExpression.getValue(getEvaluationContext(null), String.class); // } // } // // Path: src/main/java/org/springframework/data/keyvalue/core/mapping/KeySpaceResolver.java // public interface KeySpaceResolver { // // /** // * Determine the {@literal keySpace} to use for a given type. // * // * @param type must not be {@literal null}. // * @return // */ // @Nullable // String resolveKeySpace(Class<?> type); // } // // Path: src/main/java/org/springframework/data/keyvalue/core/mapping/KeyValuePersistentEntity.java // public interface KeyValuePersistentEntity<T, P extends KeyValuePersistentProperty<P>> // extends MutablePersistentEntity<T, P> { // // /** // * Get the {@literal keySpace} a given entity assigns to. // * // * @return can be {@literal null}. // */ // @Nullable // String getKeySpace(); // } // // Path: src/main/java/org/springframework/data/keyvalue/core/mapping/KeyValuePersistentProperty.java // public class KeyValuePersistentProperty<P extends KeyValuePersistentProperty<P>> // extends AnnotationBasedPersistentProperty<P> { // // public KeyValuePersistentProperty(Property property, PersistentEntity<?, P> owner, // SimpleTypeHolder simpleTypeHolder) { // super(property, owner, simpleTypeHolder); // } // // /* // * (non-Javadoc) // * @see org.springframework.data.mapping.model.AbstractPersistentProperty#createAssociation() // */ // @Override // @SuppressWarnings("unchecked") // protected Association<P> createAssociation() { // return new Association<>((P) this, null); // } // }
import java.util.Collections; import org.springframework.data.keyvalue.core.mapping.BasicKeyValuePersistentEntity; import org.springframework.data.keyvalue.core.mapping.KeySpaceResolver; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentProperty; import org.springframework.data.mapping.context.AbstractMappingContext; import org.springframework.data.mapping.context.MappingContext; import org.springframework.data.mapping.model.Property; import org.springframework.data.mapping.model.SimpleTypeHolder; import org.springframework.data.util.TypeInformation; import org.springframework.lang.Nullable;
/* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core.mapping.context; /** * Default implementation of a {@link MappingContext} using {@link KeyValuePersistentEntity} and * {@link KeyValuePersistentProperty} as primary abstractions. * * @author Christoph Strobl * @author Oliver Gierke * @author Mark Paluch */ public class KeyValueMappingContext<E extends KeyValuePersistentEntity<?, P>, P extends KeyValuePersistentProperty<P>> extends AbstractMappingContext<E, P> {
// Path: src/main/java/org/springframework/data/keyvalue/core/mapping/BasicKeyValuePersistentEntity.java // public class BasicKeyValuePersistentEntity<T, P extends KeyValuePersistentProperty<P>> // extends BasicPersistentEntity<T, P> implements KeyValuePersistentEntity<T, P> { // // private static final SpelExpressionParser PARSER = new SpelExpressionParser(); // // private static final KeySpaceResolver DEFAULT_FALLBACK_RESOLVER = ClassNameKeySpaceResolver.INSTANCE; // // private final @Nullable Expression keyspaceExpression; // private final @Nullable String keyspace; // // /** // * @param information must not be {@literal null}. // * @param fallbackKeySpaceResolver can be {@literal null}. // */ // public BasicKeyValuePersistentEntity(TypeInformation<T> information, // @Nullable KeySpaceResolver fallbackKeySpaceResolver) { // // super(information); // // Class<T> type = information.getType(); // String keySpace = AnnotationBasedKeySpaceResolver.INSTANCE.resolveKeySpace(type); // // if (StringUtils.hasText(keySpace)) { // // this.keyspace = keySpace; // this.keyspaceExpression = detectExpression(keySpace); // } else { // // this.keyspace = resolveKeyspace(fallbackKeySpaceResolver, type); // this.keyspaceExpression = null; // } // } // // /** // * Returns a SpEL {@link Expression} if the given {@link String} is actually an expression that does not evaluate to a // * {@link LiteralExpression} (indicating that no subsequent evaluation is necessary). // * // * @param potentialExpression must not be {@literal null} // * @return the parsed {@link Expression} or {@literal null}. // */ // @Nullable // private static Expression detectExpression(String potentialExpression) { // // Expression expression = PARSER.parseExpression(potentialExpression, ParserContext.TEMPLATE_EXPRESSION); // return expression instanceof LiteralExpression ? null : expression; // } // // @Nullable // private static String resolveKeyspace(@Nullable KeySpaceResolver fallbackKeySpaceResolver, Class<?> type) { // return (fallbackKeySpaceResolver == null ? DEFAULT_FALLBACK_RESOLVER : fallbackKeySpaceResolver) // .resolveKeySpace(type); // } // // /* // * (non-Javadoc) // * @see org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity#getKeySpace() // */ // @Override // public String getKeySpace() { // return keyspaceExpression == null // // ? keyspace // // : keyspaceExpression.getValue(getEvaluationContext(null), String.class); // } // } // // Path: src/main/java/org/springframework/data/keyvalue/core/mapping/KeySpaceResolver.java // public interface KeySpaceResolver { // // /** // * Determine the {@literal keySpace} to use for a given type. // * // * @param type must not be {@literal null}. // * @return // */ // @Nullable // String resolveKeySpace(Class<?> type); // } // // Path: src/main/java/org/springframework/data/keyvalue/core/mapping/KeyValuePersistentEntity.java // public interface KeyValuePersistentEntity<T, P extends KeyValuePersistentProperty<P>> // extends MutablePersistentEntity<T, P> { // // /** // * Get the {@literal keySpace} a given entity assigns to. // * // * @return can be {@literal null}. // */ // @Nullable // String getKeySpace(); // } // // Path: src/main/java/org/springframework/data/keyvalue/core/mapping/KeyValuePersistentProperty.java // public class KeyValuePersistentProperty<P extends KeyValuePersistentProperty<P>> // extends AnnotationBasedPersistentProperty<P> { // // public KeyValuePersistentProperty(Property property, PersistentEntity<?, P> owner, // SimpleTypeHolder simpleTypeHolder) { // super(property, owner, simpleTypeHolder); // } // // /* // * (non-Javadoc) // * @see org.springframework.data.mapping.model.AbstractPersistentProperty#createAssociation() // */ // @Override // @SuppressWarnings("unchecked") // protected Association<P> createAssociation() { // return new Association<>((P) this, null); // } // } // Path: src/main/java/org/springframework/data/keyvalue/core/mapping/context/KeyValueMappingContext.java import java.util.Collections; import org.springframework.data.keyvalue.core.mapping.BasicKeyValuePersistentEntity; import org.springframework.data.keyvalue.core.mapping.KeySpaceResolver; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentProperty; import org.springframework.data.mapping.context.AbstractMappingContext; import org.springframework.data.mapping.context.MappingContext; import org.springframework.data.mapping.model.Property; import org.springframework.data.mapping.model.SimpleTypeHolder; import org.springframework.data.util.TypeInformation; import org.springframework.lang.Nullable; /* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core.mapping.context; /** * Default implementation of a {@link MappingContext} using {@link KeyValuePersistentEntity} and * {@link KeyValuePersistentProperty} as primary abstractions. * * @author Christoph Strobl * @author Oliver Gierke * @author Mark Paluch */ public class KeyValueMappingContext<E extends KeyValuePersistentEntity<?, P>, P extends KeyValuePersistentProperty<P>> extends AbstractMappingContext<E, P> {
private @Nullable KeySpaceResolver fallbackKeySpaceResolver;
spring-projects/spring-data-keyvalue
src/main/java/org/springframework/data/keyvalue/core/SpelSortAccessor.java
// Path: src/main/java/org/springframework/data/keyvalue/core/query/KeyValueQuery.java // public class KeyValueQuery<T> { // // private Sort sort = Sort.unsorted(); // private long offset = -1; // private int rows = -1; // private final @Nullable T criteria; // // /** // * Creates new instance of {@link KeyValueQuery}. // */ // public KeyValueQuery() { // this((T) null); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria. // * // * @param criteria can be {@literal null}. // */ // public KeyValueQuery(@Nullable T criteria) { // this.criteria = criteria; // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria and {@link Sort}. // * // * @param criteria can be {@literal null}. // * @param sort must not be {@literal null}. // * @since 2.4 // */ // public KeyValueQuery(@Nullable T criteria, Sort sort) { // this.criteria = criteria; // setSort(sort); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given {@link Sort}. // * // * @param sort must not be {@literal null}. // */ // public KeyValueQuery(Sort sort) { // this(); // setSort(sort); // } // // /** // * Get the criteria object. // * // * @return // * @since 2.0 // */ // @Nullable // public T getCriteria() { // return criteria; // } // // /** // * Get {@link Sort}. // * // * @return // */ // public Sort getSort() { // return sort; // } // // /** // * Number of elements to skip. // * // * @return negative value if not set. // */ // public long getOffset() { // return this.offset; // } // // /** // * Number of elements to read. // * // * @return negative value if not set. // */ // public int getRows() { // return this.rows; // } // // /** // * Set the number of elements to skip. // * // * @param offset use negative value for none. // */ // public void setOffset(long offset) { // this.offset = offset; // } // // /** // * Set the number of elements to read. // * // * @param rows use negative value for all. // */ // public void setRows(int rows) { // this.rows = rows; // } // // /** // * Set {@link Sort} to be applied. // * // * @param sort // */ // public void setSort(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // this.sort = sort; // } // // /** // * Add given {@link Sort}. // * // * @param sort must not be {@literal null}. // * @return // */ // public KeyValueQuery<T> orderBy(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // if (this.sort.isSorted()) { // this.sort = this.sort.and(sort); // } else { // this.sort = sort; // } // // return this; // } // // /** // * @see KeyValueQuery#setOffset(long) // * @param offset // * @return // */ // public KeyValueQuery<T> skip(long offset) { // // setOffset(offset); // // return this; // } // // /** // * @see KeyValueQuery#setRows(int) // * @param rows // * @return // */ // public KeyValueQuery<T> limit(int rows) { // setRows(rows); // return this; // } // // }
import java.util.Comparator; import java.util.Optional; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.NullHandling; import org.springframework.data.domain.Sort.Order; import org.springframework.data.keyvalue.core.query.KeyValueQuery; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.util.Assert;
/* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core; /** * {@link SortAccessor} implementation capable of creating {@link SpelPropertyComparator}. * * @author Christoph Strobl * @author Oliver Gierke * @author Mark Paluch */ public class SpelSortAccessor implements SortAccessor<Comparator<?>> { private final SpelExpressionParser parser; /** * Creates a new {@link SpelSortAccessor} given {@link SpelExpressionParser}. * * @param parser must not be {@literal null}. */ public SpelSortAccessor(SpelExpressionParser parser) { Assert.notNull(parser, "SpelExpressionParser must not be null!"); this.parser = parser; } /* * (non-Javadoc) * @see org.springframework.data.keyvalue.core.SortAccessor#resolve(org.springframework.data.keyvalue.core.query.KeyValueQuery) */ @Override
// Path: src/main/java/org/springframework/data/keyvalue/core/query/KeyValueQuery.java // public class KeyValueQuery<T> { // // private Sort sort = Sort.unsorted(); // private long offset = -1; // private int rows = -1; // private final @Nullable T criteria; // // /** // * Creates new instance of {@link KeyValueQuery}. // */ // public KeyValueQuery() { // this((T) null); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria. // * // * @param criteria can be {@literal null}. // */ // public KeyValueQuery(@Nullable T criteria) { // this.criteria = criteria; // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria and {@link Sort}. // * // * @param criteria can be {@literal null}. // * @param sort must not be {@literal null}. // * @since 2.4 // */ // public KeyValueQuery(@Nullable T criteria, Sort sort) { // this.criteria = criteria; // setSort(sort); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given {@link Sort}. // * // * @param sort must not be {@literal null}. // */ // public KeyValueQuery(Sort sort) { // this(); // setSort(sort); // } // // /** // * Get the criteria object. // * // * @return // * @since 2.0 // */ // @Nullable // public T getCriteria() { // return criteria; // } // // /** // * Get {@link Sort}. // * // * @return // */ // public Sort getSort() { // return sort; // } // // /** // * Number of elements to skip. // * // * @return negative value if not set. // */ // public long getOffset() { // return this.offset; // } // // /** // * Number of elements to read. // * // * @return negative value if not set. // */ // public int getRows() { // return this.rows; // } // // /** // * Set the number of elements to skip. // * // * @param offset use negative value for none. // */ // public void setOffset(long offset) { // this.offset = offset; // } // // /** // * Set the number of elements to read. // * // * @param rows use negative value for all. // */ // public void setRows(int rows) { // this.rows = rows; // } // // /** // * Set {@link Sort} to be applied. // * // * @param sort // */ // public void setSort(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // this.sort = sort; // } // // /** // * Add given {@link Sort}. // * // * @param sort must not be {@literal null}. // * @return // */ // public KeyValueQuery<T> orderBy(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // if (this.sort.isSorted()) { // this.sort = this.sort.and(sort); // } else { // this.sort = sort; // } // // return this; // } // // /** // * @see KeyValueQuery#setOffset(long) // * @param offset // * @return // */ // public KeyValueQuery<T> skip(long offset) { // // setOffset(offset); // // return this; // } // // /** // * @see KeyValueQuery#setRows(int) // * @param rows // * @return // */ // public KeyValueQuery<T> limit(int rows) { // setRows(rows); // return this; // } // // } // Path: src/main/java/org/springframework/data/keyvalue/core/SpelSortAccessor.java import java.util.Comparator; import java.util.Optional; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.NullHandling; import org.springframework.data.domain.Sort.Order; import org.springframework.data.keyvalue.core.query.KeyValueQuery; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.util.Assert; /* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core; /** * {@link SortAccessor} implementation capable of creating {@link SpelPropertyComparator}. * * @author Christoph Strobl * @author Oliver Gierke * @author Mark Paluch */ public class SpelSortAccessor implements SortAccessor<Comparator<?>> { private final SpelExpressionParser parser; /** * Creates a new {@link SpelSortAccessor} given {@link SpelExpressionParser}. * * @param parser must not be {@literal null}. */ public SpelSortAccessor(SpelExpressionParser parser) { Assert.notNull(parser, "SpelExpressionParser must not be null!"); this.parser = parser; } /* * (non-Javadoc) * @see org.springframework.data.keyvalue.core.SortAccessor#resolve(org.springframework.data.keyvalue.core.query.KeyValueQuery) */ @Override
public Comparator<?> resolve(KeyValueQuery<?> query) {
spring-projects/spring-data-keyvalue
src/main/java/org/springframework/data/keyvalue/core/SortAccessor.java
// Path: src/main/java/org/springframework/data/keyvalue/core/query/KeyValueQuery.java // public class KeyValueQuery<T> { // // private Sort sort = Sort.unsorted(); // private long offset = -1; // private int rows = -1; // private final @Nullable T criteria; // // /** // * Creates new instance of {@link KeyValueQuery}. // */ // public KeyValueQuery() { // this((T) null); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria. // * // * @param criteria can be {@literal null}. // */ // public KeyValueQuery(@Nullable T criteria) { // this.criteria = criteria; // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria and {@link Sort}. // * // * @param criteria can be {@literal null}. // * @param sort must not be {@literal null}. // * @since 2.4 // */ // public KeyValueQuery(@Nullable T criteria, Sort sort) { // this.criteria = criteria; // setSort(sort); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given {@link Sort}. // * // * @param sort must not be {@literal null}. // */ // public KeyValueQuery(Sort sort) { // this(); // setSort(sort); // } // // /** // * Get the criteria object. // * // * @return // * @since 2.0 // */ // @Nullable // public T getCriteria() { // return criteria; // } // // /** // * Get {@link Sort}. // * // * @return // */ // public Sort getSort() { // return sort; // } // // /** // * Number of elements to skip. // * // * @return negative value if not set. // */ // public long getOffset() { // return this.offset; // } // // /** // * Number of elements to read. // * // * @return negative value if not set. // */ // public int getRows() { // return this.rows; // } // // /** // * Set the number of elements to skip. // * // * @param offset use negative value for none. // */ // public void setOffset(long offset) { // this.offset = offset; // } // // /** // * Set the number of elements to read. // * // * @param rows use negative value for all. // */ // public void setRows(int rows) { // this.rows = rows; // } // // /** // * Set {@link Sort} to be applied. // * // * @param sort // */ // public void setSort(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // this.sort = sort; // } // // /** // * Add given {@link Sort}. // * // * @param sort must not be {@literal null}. // * @return // */ // public KeyValueQuery<T> orderBy(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // if (this.sort.isSorted()) { // this.sort = this.sort.and(sort); // } else { // this.sort = sort; // } // // return this; // } // // /** // * @see KeyValueQuery#setOffset(long) // * @param offset // * @return // */ // public KeyValueQuery<T> skip(long offset) { // // setOffset(offset); // // return this; // } // // /** // * @see KeyValueQuery#setRows(int) // * @param rows // * @return // */ // public KeyValueQuery<T> limit(int rows) { // setRows(rows); // return this; // } // // }
import org.springframework.data.domain.Sort; import org.springframework.data.keyvalue.core.query.KeyValueQuery; import org.springframework.lang.Nullable;
/* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core; /** * Resolves the {@link Sort} object from given {@link KeyValueQuery} and potentially converts it into a store specific * representation that can be used by the {@link QueryEngine} implementation. * * @author Christoph Strobl * @author Mark Paluch * @param <T> */ public interface SortAccessor<T> { /** * Reads {@link KeyValueQuery#getSort()} of given {@link KeyValueQuery} and applies required transformation to match * the desired type. * * @param query must not be {@literal null}. * @return {@literal null} in case {@link Sort} has not been defined on {@link KeyValueQuery}. */ @Nullable
// Path: src/main/java/org/springframework/data/keyvalue/core/query/KeyValueQuery.java // public class KeyValueQuery<T> { // // private Sort sort = Sort.unsorted(); // private long offset = -1; // private int rows = -1; // private final @Nullable T criteria; // // /** // * Creates new instance of {@link KeyValueQuery}. // */ // public KeyValueQuery() { // this((T) null); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria. // * // * @param criteria can be {@literal null}. // */ // public KeyValueQuery(@Nullable T criteria) { // this.criteria = criteria; // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria and {@link Sort}. // * // * @param criteria can be {@literal null}. // * @param sort must not be {@literal null}. // * @since 2.4 // */ // public KeyValueQuery(@Nullable T criteria, Sort sort) { // this.criteria = criteria; // setSort(sort); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given {@link Sort}. // * // * @param sort must not be {@literal null}. // */ // public KeyValueQuery(Sort sort) { // this(); // setSort(sort); // } // // /** // * Get the criteria object. // * // * @return // * @since 2.0 // */ // @Nullable // public T getCriteria() { // return criteria; // } // // /** // * Get {@link Sort}. // * // * @return // */ // public Sort getSort() { // return sort; // } // // /** // * Number of elements to skip. // * // * @return negative value if not set. // */ // public long getOffset() { // return this.offset; // } // // /** // * Number of elements to read. // * // * @return negative value if not set. // */ // public int getRows() { // return this.rows; // } // // /** // * Set the number of elements to skip. // * // * @param offset use negative value for none. // */ // public void setOffset(long offset) { // this.offset = offset; // } // // /** // * Set the number of elements to read. // * // * @param rows use negative value for all. // */ // public void setRows(int rows) { // this.rows = rows; // } // // /** // * Set {@link Sort} to be applied. // * // * @param sort // */ // public void setSort(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // this.sort = sort; // } // // /** // * Add given {@link Sort}. // * // * @param sort must not be {@literal null}. // * @return // */ // public KeyValueQuery<T> orderBy(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // if (this.sort.isSorted()) { // this.sort = this.sort.and(sort); // } else { // this.sort = sort; // } // // return this; // } // // /** // * @see KeyValueQuery#setOffset(long) // * @param offset // * @return // */ // public KeyValueQuery<T> skip(long offset) { // // setOffset(offset); // // return this; // } // // /** // * @see KeyValueQuery#setRows(int) // * @param rows // * @return // */ // public KeyValueQuery<T> limit(int rows) { // setRows(rows); // return this; // } // // } // Path: src/main/java/org/springframework/data/keyvalue/core/SortAccessor.java import org.springframework.data.domain.Sort; import org.springframework.data.keyvalue.core.query.KeyValueQuery; import org.springframework.lang.Nullable; /* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core; /** * Resolves the {@link Sort} object from given {@link KeyValueQuery} and potentially converts it into a store specific * representation that can be used by the {@link QueryEngine} implementation. * * @author Christoph Strobl * @author Mark Paluch * @param <T> */ public interface SortAccessor<T> { /** * Reads {@link KeyValueQuery#getSort()} of given {@link KeyValueQuery} and applies required transformation to match * the desired type. * * @param query must not be {@literal null}. * @return {@literal null} in case {@link Sort} has not been defined on {@link KeyValueQuery}. */ @Nullable
T resolve(KeyValueQuery<?> query);
spring-projects/spring-data-keyvalue
src/main/java/org/springframework/data/keyvalue/core/SpelCriteriaAccessor.java
// Path: src/main/java/org/springframework/data/keyvalue/core/query/KeyValueQuery.java // public class KeyValueQuery<T> { // // private Sort sort = Sort.unsorted(); // private long offset = -1; // private int rows = -1; // private final @Nullable T criteria; // // /** // * Creates new instance of {@link KeyValueQuery}. // */ // public KeyValueQuery() { // this((T) null); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria. // * // * @param criteria can be {@literal null}. // */ // public KeyValueQuery(@Nullable T criteria) { // this.criteria = criteria; // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria and {@link Sort}. // * // * @param criteria can be {@literal null}. // * @param sort must not be {@literal null}. // * @since 2.4 // */ // public KeyValueQuery(@Nullable T criteria, Sort sort) { // this.criteria = criteria; // setSort(sort); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given {@link Sort}. // * // * @param sort must not be {@literal null}. // */ // public KeyValueQuery(Sort sort) { // this(); // setSort(sort); // } // // /** // * Get the criteria object. // * // * @return // * @since 2.0 // */ // @Nullable // public T getCriteria() { // return criteria; // } // // /** // * Get {@link Sort}. // * // * @return // */ // public Sort getSort() { // return sort; // } // // /** // * Number of elements to skip. // * // * @return negative value if not set. // */ // public long getOffset() { // return this.offset; // } // // /** // * Number of elements to read. // * // * @return negative value if not set. // */ // public int getRows() { // return this.rows; // } // // /** // * Set the number of elements to skip. // * // * @param offset use negative value for none. // */ // public void setOffset(long offset) { // this.offset = offset; // } // // /** // * Set the number of elements to read. // * // * @param rows use negative value for all. // */ // public void setRows(int rows) { // this.rows = rows; // } // // /** // * Set {@link Sort} to be applied. // * // * @param sort // */ // public void setSort(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // this.sort = sort; // } // // /** // * Add given {@link Sort}. // * // * @param sort must not be {@literal null}. // * @return // */ // public KeyValueQuery<T> orderBy(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // if (this.sort.isSorted()) { // this.sort = this.sort.and(sort); // } else { // this.sort = sort; // } // // return this; // } // // /** // * @see KeyValueQuery#setOffset(long) // * @param offset // * @return // */ // public KeyValueQuery<T> skip(long offset) { // // setOffset(offset); // // return this; // } // // /** // * @see KeyValueQuery#setRows(int) // * @param rows // * @return // */ // public KeyValueQuery<T> limit(int rows) { // setRows(rows); // return this; // } // // }
import org.springframework.data.keyvalue.core.query.KeyValueQuery; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.util.Assert;
/* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core; /** * {@link CriteriaAccessor} implementation capable of {@link SpelExpression}s. * * @author Christoph Strobl * @author Oliver Gierke */ class SpelCriteriaAccessor implements CriteriaAccessor<SpelCriteria> { private final SpelExpressionParser parser; /** * Creates a new {@link SpelCriteriaAccessor} using the given {@link SpelExpressionParser}. * * @param parser must not be {@literal null}. */ public SpelCriteriaAccessor(SpelExpressionParser parser) { Assert.notNull(parser, "SpelExpressionParser must not be null!"); this.parser = parser; } /* * (non-Javadoc) * @see org.springframework.data.keyvalue.core.CriteriaAccessor#resolve(org.springframework.data.keyvalue.core.query.KeyValueQuery) */ @Override
// Path: src/main/java/org/springframework/data/keyvalue/core/query/KeyValueQuery.java // public class KeyValueQuery<T> { // // private Sort sort = Sort.unsorted(); // private long offset = -1; // private int rows = -1; // private final @Nullable T criteria; // // /** // * Creates new instance of {@link KeyValueQuery}. // */ // public KeyValueQuery() { // this((T) null); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria. // * // * @param criteria can be {@literal null}. // */ // public KeyValueQuery(@Nullable T criteria) { // this.criteria = criteria; // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria and {@link Sort}. // * // * @param criteria can be {@literal null}. // * @param sort must not be {@literal null}. // * @since 2.4 // */ // public KeyValueQuery(@Nullable T criteria, Sort sort) { // this.criteria = criteria; // setSort(sort); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given {@link Sort}. // * // * @param sort must not be {@literal null}. // */ // public KeyValueQuery(Sort sort) { // this(); // setSort(sort); // } // // /** // * Get the criteria object. // * // * @return // * @since 2.0 // */ // @Nullable // public T getCriteria() { // return criteria; // } // // /** // * Get {@link Sort}. // * // * @return // */ // public Sort getSort() { // return sort; // } // // /** // * Number of elements to skip. // * // * @return negative value if not set. // */ // public long getOffset() { // return this.offset; // } // // /** // * Number of elements to read. // * // * @return negative value if not set. // */ // public int getRows() { // return this.rows; // } // // /** // * Set the number of elements to skip. // * // * @param offset use negative value for none. // */ // public void setOffset(long offset) { // this.offset = offset; // } // // /** // * Set the number of elements to read. // * // * @param rows use negative value for all. // */ // public void setRows(int rows) { // this.rows = rows; // } // // /** // * Set {@link Sort} to be applied. // * // * @param sort // */ // public void setSort(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // this.sort = sort; // } // // /** // * Add given {@link Sort}. // * // * @param sort must not be {@literal null}. // * @return // */ // public KeyValueQuery<T> orderBy(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // if (this.sort.isSorted()) { // this.sort = this.sort.and(sort); // } else { // this.sort = sort; // } // // return this; // } // // /** // * @see KeyValueQuery#setOffset(long) // * @param offset // * @return // */ // public KeyValueQuery<T> skip(long offset) { // // setOffset(offset); // // return this; // } // // /** // * @see KeyValueQuery#setRows(int) // * @param rows // * @return // */ // public KeyValueQuery<T> limit(int rows) { // setRows(rows); // return this; // } // // } // Path: src/main/java/org/springframework/data/keyvalue/core/SpelCriteriaAccessor.java import org.springframework.data.keyvalue.core.query.KeyValueQuery; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.util.Assert; /* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core; /** * {@link CriteriaAccessor} implementation capable of {@link SpelExpression}s. * * @author Christoph Strobl * @author Oliver Gierke */ class SpelCriteriaAccessor implements CriteriaAccessor<SpelCriteria> { private final SpelExpressionParser parser; /** * Creates a new {@link SpelCriteriaAccessor} using the given {@link SpelExpressionParser}. * * @param parser must not be {@literal null}. */ public SpelCriteriaAccessor(SpelExpressionParser parser) { Assert.notNull(parser, "SpelExpressionParser must not be null!"); this.parser = parser; } /* * (non-Javadoc) * @see org.springframework.data.keyvalue.core.CriteriaAccessor#resolve(org.springframework.data.keyvalue.core.query.KeyValueQuery) */ @Override
public SpelCriteria resolve(KeyValueQuery<?> query) {
spring-projects/spring-data-keyvalue
src/main/java/org/springframework/data/keyvalue/core/CriteriaAccessor.java
// Path: src/main/java/org/springframework/data/keyvalue/core/query/KeyValueQuery.java // public class KeyValueQuery<T> { // // private Sort sort = Sort.unsorted(); // private long offset = -1; // private int rows = -1; // private final @Nullable T criteria; // // /** // * Creates new instance of {@link KeyValueQuery}. // */ // public KeyValueQuery() { // this((T) null); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria. // * // * @param criteria can be {@literal null}. // */ // public KeyValueQuery(@Nullable T criteria) { // this.criteria = criteria; // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria and {@link Sort}. // * // * @param criteria can be {@literal null}. // * @param sort must not be {@literal null}. // * @since 2.4 // */ // public KeyValueQuery(@Nullable T criteria, Sort sort) { // this.criteria = criteria; // setSort(sort); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given {@link Sort}. // * // * @param sort must not be {@literal null}. // */ // public KeyValueQuery(Sort sort) { // this(); // setSort(sort); // } // // /** // * Get the criteria object. // * // * @return // * @since 2.0 // */ // @Nullable // public T getCriteria() { // return criteria; // } // // /** // * Get {@link Sort}. // * // * @return // */ // public Sort getSort() { // return sort; // } // // /** // * Number of elements to skip. // * // * @return negative value if not set. // */ // public long getOffset() { // return this.offset; // } // // /** // * Number of elements to read. // * // * @return negative value if not set. // */ // public int getRows() { // return this.rows; // } // // /** // * Set the number of elements to skip. // * // * @param offset use negative value for none. // */ // public void setOffset(long offset) { // this.offset = offset; // } // // /** // * Set the number of elements to read. // * // * @param rows use negative value for all. // */ // public void setRows(int rows) { // this.rows = rows; // } // // /** // * Set {@link Sort} to be applied. // * // * @param sort // */ // public void setSort(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // this.sort = sort; // } // // /** // * Add given {@link Sort}. // * // * @param sort must not be {@literal null}. // * @return // */ // public KeyValueQuery<T> orderBy(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // if (this.sort.isSorted()) { // this.sort = this.sort.and(sort); // } else { // this.sort = sort; // } // // return this; // } // // /** // * @see KeyValueQuery#setOffset(long) // * @param offset // * @return // */ // public KeyValueQuery<T> skip(long offset) { // // setOffset(offset); // // return this; // } // // /** // * @see KeyValueQuery#setRows(int) // * @param rows // * @return // */ // public KeyValueQuery<T> limit(int rows) { // setRows(rows); // return this; // } // // }
import org.springframework.data.keyvalue.core.query.KeyValueQuery; import org.springframework.lang.Nullable;
/* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core; /** * Resolves the criteria object from given {@link KeyValueQuery}. * * @author Christoph Strobl * @author Mark Paluch * @param <T> */ public interface CriteriaAccessor<T> { /** * Checks and reads {@link KeyValueQuery#getCriteria()} of given {@link KeyValueQuery}. Might also apply additional * transformation to match the desired type. * * @param query must not be {@literal null}. * @return the criteria extracted from the query. Can be {@literal null}. * @throws IllegalArgumentException in case the criteria is not valid for usage with specific * {@link CriteriaAccessor}. */ @Nullable
// Path: src/main/java/org/springframework/data/keyvalue/core/query/KeyValueQuery.java // public class KeyValueQuery<T> { // // private Sort sort = Sort.unsorted(); // private long offset = -1; // private int rows = -1; // private final @Nullable T criteria; // // /** // * Creates new instance of {@link KeyValueQuery}. // */ // public KeyValueQuery() { // this((T) null); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria. // * // * @param criteria can be {@literal null}. // */ // public KeyValueQuery(@Nullable T criteria) { // this.criteria = criteria; // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria and {@link Sort}. // * // * @param criteria can be {@literal null}. // * @param sort must not be {@literal null}. // * @since 2.4 // */ // public KeyValueQuery(@Nullable T criteria, Sort sort) { // this.criteria = criteria; // setSort(sort); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given {@link Sort}. // * // * @param sort must not be {@literal null}. // */ // public KeyValueQuery(Sort sort) { // this(); // setSort(sort); // } // // /** // * Get the criteria object. // * // * @return // * @since 2.0 // */ // @Nullable // public T getCriteria() { // return criteria; // } // // /** // * Get {@link Sort}. // * // * @return // */ // public Sort getSort() { // return sort; // } // // /** // * Number of elements to skip. // * // * @return negative value if not set. // */ // public long getOffset() { // return this.offset; // } // // /** // * Number of elements to read. // * // * @return negative value if not set. // */ // public int getRows() { // return this.rows; // } // // /** // * Set the number of elements to skip. // * // * @param offset use negative value for none. // */ // public void setOffset(long offset) { // this.offset = offset; // } // // /** // * Set the number of elements to read. // * // * @param rows use negative value for all. // */ // public void setRows(int rows) { // this.rows = rows; // } // // /** // * Set {@link Sort} to be applied. // * // * @param sort // */ // public void setSort(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // this.sort = sort; // } // // /** // * Add given {@link Sort}. // * // * @param sort must not be {@literal null}. // * @return // */ // public KeyValueQuery<T> orderBy(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // if (this.sort.isSorted()) { // this.sort = this.sort.and(sort); // } else { // this.sort = sort; // } // // return this; // } // // /** // * @see KeyValueQuery#setOffset(long) // * @param offset // * @return // */ // public KeyValueQuery<T> skip(long offset) { // // setOffset(offset); // // return this; // } // // /** // * @see KeyValueQuery#setRows(int) // * @param rows // * @return // */ // public KeyValueQuery<T> limit(int rows) { // setRows(rows); // return this; // } // // } // Path: src/main/java/org/springframework/data/keyvalue/core/CriteriaAccessor.java import org.springframework.data.keyvalue.core.query.KeyValueQuery; import org.springframework.lang.Nullable; /* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core; /** * Resolves the criteria object from given {@link KeyValueQuery}. * * @author Christoph Strobl * @author Mark Paluch * @param <T> */ public interface CriteriaAccessor<T> { /** * Checks and reads {@link KeyValueQuery#getCriteria()} of given {@link KeyValueQuery}. Might also apply additional * transformation to match the desired type. * * @param query must not be {@literal null}. * @return the criteria extracted from the query. Can be {@literal null}. * @throws IllegalArgumentException in case the criteria is not valid for usage with specific * {@link CriteriaAccessor}. */ @Nullable
T resolve(KeyValueQuery<?> query);
spring-projects/spring-data-keyvalue
src/main/java/org/springframework/data/keyvalue/core/QueryEngine.java
// Path: src/main/java/org/springframework/data/keyvalue/core/query/KeyValueQuery.java // public class KeyValueQuery<T> { // // private Sort sort = Sort.unsorted(); // private long offset = -1; // private int rows = -1; // private final @Nullable T criteria; // // /** // * Creates new instance of {@link KeyValueQuery}. // */ // public KeyValueQuery() { // this((T) null); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria. // * // * @param criteria can be {@literal null}. // */ // public KeyValueQuery(@Nullable T criteria) { // this.criteria = criteria; // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria and {@link Sort}. // * // * @param criteria can be {@literal null}. // * @param sort must not be {@literal null}. // * @since 2.4 // */ // public KeyValueQuery(@Nullable T criteria, Sort sort) { // this.criteria = criteria; // setSort(sort); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given {@link Sort}. // * // * @param sort must not be {@literal null}. // */ // public KeyValueQuery(Sort sort) { // this(); // setSort(sort); // } // // /** // * Get the criteria object. // * // * @return // * @since 2.0 // */ // @Nullable // public T getCriteria() { // return criteria; // } // // /** // * Get {@link Sort}. // * // * @return // */ // public Sort getSort() { // return sort; // } // // /** // * Number of elements to skip. // * // * @return negative value if not set. // */ // public long getOffset() { // return this.offset; // } // // /** // * Number of elements to read. // * // * @return negative value if not set. // */ // public int getRows() { // return this.rows; // } // // /** // * Set the number of elements to skip. // * // * @param offset use negative value for none. // */ // public void setOffset(long offset) { // this.offset = offset; // } // // /** // * Set the number of elements to read. // * // * @param rows use negative value for all. // */ // public void setRows(int rows) { // this.rows = rows; // } // // /** // * Set {@link Sort} to be applied. // * // * @param sort // */ // public void setSort(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // this.sort = sort; // } // // /** // * Add given {@link Sort}. // * // * @param sort must not be {@literal null}. // * @return // */ // public KeyValueQuery<T> orderBy(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // if (this.sort.isSorted()) { // this.sort = this.sort.and(sort); // } else { // this.sort = sort; // } // // return this; // } // // /** // * @see KeyValueQuery#setOffset(long) // * @param offset // * @return // */ // public KeyValueQuery<T> skip(long offset) { // // setOffset(offset); // // return this; // } // // /** // * @see KeyValueQuery#setRows(int) // * @param rows // * @return // */ // public KeyValueQuery<T> limit(int rows) { // setRows(rows); // return this; // } // // }
import java.util.Collection; import java.util.Optional; import org.springframework.data.keyvalue.core.query.KeyValueQuery; import org.springframework.lang.Nullable;
/* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core; /** * Base implementation for accessing and executing {@link KeyValueQuery} against a {@link KeyValueAdapter}. * * @author Christoph Strobl * @author Mark Paluch * @param <ADAPTER> * @param <CRITERIA> * @param <SORT> */ public abstract class QueryEngine<ADAPTER extends KeyValueAdapter, CRITERIA, SORT> { private final Optional<CriteriaAccessor<CRITERIA>> criteriaAccessor; private final Optional<SortAccessor<SORT>> sortAccessor; private @Nullable ADAPTER adapter; public QueryEngine(@Nullable CriteriaAccessor<CRITERIA> criteriaAccessor, @Nullable SortAccessor<SORT> sortAccessor) { this.criteriaAccessor = Optional.ofNullable(criteriaAccessor); this.sortAccessor = Optional.ofNullable(sortAccessor); } /** * Extract query attributes and delegate to concrete execution. * * @param query * @param keyspace * @return */
// Path: src/main/java/org/springframework/data/keyvalue/core/query/KeyValueQuery.java // public class KeyValueQuery<T> { // // private Sort sort = Sort.unsorted(); // private long offset = -1; // private int rows = -1; // private final @Nullable T criteria; // // /** // * Creates new instance of {@link KeyValueQuery}. // */ // public KeyValueQuery() { // this((T) null); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria. // * // * @param criteria can be {@literal null}. // */ // public KeyValueQuery(@Nullable T criteria) { // this.criteria = criteria; // } // // /** // * Creates new instance of {@link KeyValueQuery} with given criteria and {@link Sort}. // * // * @param criteria can be {@literal null}. // * @param sort must not be {@literal null}. // * @since 2.4 // */ // public KeyValueQuery(@Nullable T criteria, Sort sort) { // this.criteria = criteria; // setSort(sort); // } // // /** // * Creates new instance of {@link KeyValueQuery} with given {@link Sort}. // * // * @param sort must not be {@literal null}. // */ // public KeyValueQuery(Sort sort) { // this(); // setSort(sort); // } // // /** // * Get the criteria object. // * // * @return // * @since 2.0 // */ // @Nullable // public T getCriteria() { // return criteria; // } // // /** // * Get {@link Sort}. // * // * @return // */ // public Sort getSort() { // return sort; // } // // /** // * Number of elements to skip. // * // * @return negative value if not set. // */ // public long getOffset() { // return this.offset; // } // // /** // * Number of elements to read. // * // * @return negative value if not set. // */ // public int getRows() { // return this.rows; // } // // /** // * Set the number of elements to skip. // * // * @param offset use negative value for none. // */ // public void setOffset(long offset) { // this.offset = offset; // } // // /** // * Set the number of elements to read. // * // * @param rows use negative value for all. // */ // public void setRows(int rows) { // this.rows = rows; // } // // /** // * Set {@link Sort} to be applied. // * // * @param sort // */ // public void setSort(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // this.sort = sort; // } // // /** // * Add given {@link Sort}. // * // * @param sort must not be {@literal null}. // * @return // */ // public KeyValueQuery<T> orderBy(Sort sort) { // // Assert.notNull(sort, "Sort must not be null!"); // // if (this.sort.isSorted()) { // this.sort = this.sort.and(sort); // } else { // this.sort = sort; // } // // return this; // } // // /** // * @see KeyValueQuery#setOffset(long) // * @param offset // * @return // */ // public KeyValueQuery<T> skip(long offset) { // // setOffset(offset); // // return this; // } // // /** // * @see KeyValueQuery#setRows(int) // * @param rows // * @return // */ // public KeyValueQuery<T> limit(int rows) { // setRows(rows); // return this; // } // // } // Path: src/main/java/org/springframework/data/keyvalue/core/QueryEngine.java import java.util.Collection; import java.util.Optional; import org.springframework.data.keyvalue.core.query.KeyValueQuery; import org.springframework.lang.Nullable; /* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core; /** * Base implementation for accessing and executing {@link KeyValueQuery} against a {@link KeyValueAdapter}. * * @author Christoph Strobl * @author Mark Paluch * @param <ADAPTER> * @param <CRITERIA> * @param <SORT> */ public abstract class QueryEngine<ADAPTER extends KeyValueAdapter, CRITERIA, SORT> { private final Optional<CriteriaAccessor<CRITERIA>> criteriaAccessor; private final Optional<SortAccessor<SORT>> sortAccessor; private @Nullable ADAPTER adapter; public QueryEngine(@Nullable CriteriaAccessor<CRITERIA> criteriaAccessor, @Nullable SortAccessor<SORT> sortAccessor) { this.criteriaAccessor = Optional.ofNullable(criteriaAccessor); this.sortAccessor = Optional.ofNullable(sortAccessor); } /** * Extract query attributes and delegate to concrete execution. * * @param query * @param keyspace * @return */
public Collection<?> execute(KeyValueQuery<?> query, String keyspace) {
spring-projects/spring-data-keyvalue
src/test/java/org/springframework/data/keyvalue/core/mapping/AnnotationBasedKeySpaceResolverUnitTests.java
// Path: src/test/java/org/springframework/data/keyvalue/TypeWithDirectKeySpaceAnnotation.java // @KeySpace("rhaegar") // public class TypeWithDirectKeySpaceAnnotation { // // } // // Path: src/test/java/org/springframework/data/keyvalue/TypeWithInhteritedPersistentAnnotationNotHavingKeySpace.java // @TypeAlias("foo") // public class TypeWithInhteritedPersistentAnnotationNotHavingKeySpace { // // } // // Path: src/test/java/org/springframework/data/keyvalue/TypeWithPersistentAnnotationNotHavingKeySpace.java // @Persistent // public class TypeWithPersistentAnnotationNotHavingKeySpace { // // }
import org.springframework.data.keyvalue.annotation.KeySpace; import static org.assertj.core.api.Assertions.*; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.annotation.AliasFor; import org.springframework.data.annotation.Persistent; import org.springframework.data.keyvalue.TypeWithDirectKeySpaceAnnotation; import org.springframework.data.keyvalue.TypeWithInhteritedPersistentAnnotationNotHavingKeySpace; import org.springframework.data.keyvalue.TypeWithPersistentAnnotationNotHavingKeySpace;
/* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core.mapping; /** * Unit tests for {@link AnnotationBasedKeySpaceResolver}. * * @author Christoph Strobl * @author Oliver Gierke */ class AnnotationBasedKeySpaceResolverUnitTests { private AnnotationBasedKeySpaceResolver resolver; @BeforeEach void setUp() { resolver = AnnotationBasedKeySpaceResolver.INSTANCE; } @Test // DATACMNS-525 void shouldResolveKeySpaceDefaultValueCorrectly() { assertThat(resolver.resolveKeySpace(EntityWithDefaultKeySpace.class)).isEqualTo("daenerys"); } @Test // DATAKV-105 void shouldReturnNullWhenNoKeySpaceFoundOnComposedPersistentAnnotation() {
// Path: src/test/java/org/springframework/data/keyvalue/TypeWithDirectKeySpaceAnnotation.java // @KeySpace("rhaegar") // public class TypeWithDirectKeySpaceAnnotation { // // } // // Path: src/test/java/org/springframework/data/keyvalue/TypeWithInhteritedPersistentAnnotationNotHavingKeySpace.java // @TypeAlias("foo") // public class TypeWithInhteritedPersistentAnnotationNotHavingKeySpace { // // } // // Path: src/test/java/org/springframework/data/keyvalue/TypeWithPersistentAnnotationNotHavingKeySpace.java // @Persistent // public class TypeWithPersistentAnnotationNotHavingKeySpace { // // } // Path: src/test/java/org/springframework/data/keyvalue/core/mapping/AnnotationBasedKeySpaceResolverUnitTests.java import org.springframework.data.keyvalue.annotation.KeySpace; import static org.assertj.core.api.Assertions.*; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.annotation.AliasFor; import org.springframework.data.annotation.Persistent; import org.springframework.data.keyvalue.TypeWithDirectKeySpaceAnnotation; import org.springframework.data.keyvalue.TypeWithInhteritedPersistentAnnotationNotHavingKeySpace; import org.springframework.data.keyvalue.TypeWithPersistentAnnotationNotHavingKeySpace; /* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core.mapping; /** * Unit tests for {@link AnnotationBasedKeySpaceResolver}. * * @author Christoph Strobl * @author Oliver Gierke */ class AnnotationBasedKeySpaceResolverUnitTests { private AnnotationBasedKeySpaceResolver resolver; @BeforeEach void setUp() { resolver = AnnotationBasedKeySpaceResolver.INSTANCE; } @Test // DATACMNS-525 void shouldResolveKeySpaceDefaultValueCorrectly() { assertThat(resolver.resolveKeySpace(EntityWithDefaultKeySpace.class)).isEqualTo("daenerys"); } @Test // DATAKV-105 void shouldReturnNullWhenNoKeySpaceFoundOnComposedPersistentAnnotation() {
assertThat(resolver.resolveKeySpace(TypeWithInhteritedPersistentAnnotationNotHavingKeySpace.class)).isNull();
spring-projects/spring-data-keyvalue
src/test/java/org/springframework/data/keyvalue/core/mapping/AnnotationBasedKeySpaceResolverUnitTests.java
// Path: src/test/java/org/springframework/data/keyvalue/TypeWithDirectKeySpaceAnnotation.java // @KeySpace("rhaegar") // public class TypeWithDirectKeySpaceAnnotation { // // } // // Path: src/test/java/org/springframework/data/keyvalue/TypeWithInhteritedPersistentAnnotationNotHavingKeySpace.java // @TypeAlias("foo") // public class TypeWithInhteritedPersistentAnnotationNotHavingKeySpace { // // } // // Path: src/test/java/org/springframework/data/keyvalue/TypeWithPersistentAnnotationNotHavingKeySpace.java // @Persistent // public class TypeWithPersistentAnnotationNotHavingKeySpace { // // }
import org.springframework.data.keyvalue.annotation.KeySpace; import static org.assertj.core.api.Assertions.*; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.annotation.AliasFor; import org.springframework.data.annotation.Persistent; import org.springframework.data.keyvalue.TypeWithDirectKeySpaceAnnotation; import org.springframework.data.keyvalue.TypeWithInhteritedPersistentAnnotationNotHavingKeySpace; import org.springframework.data.keyvalue.TypeWithPersistentAnnotationNotHavingKeySpace;
/* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core.mapping; /** * Unit tests for {@link AnnotationBasedKeySpaceResolver}. * * @author Christoph Strobl * @author Oliver Gierke */ class AnnotationBasedKeySpaceResolverUnitTests { private AnnotationBasedKeySpaceResolver resolver; @BeforeEach void setUp() { resolver = AnnotationBasedKeySpaceResolver.INSTANCE; } @Test // DATACMNS-525 void shouldResolveKeySpaceDefaultValueCorrectly() { assertThat(resolver.resolveKeySpace(EntityWithDefaultKeySpace.class)).isEqualTo("daenerys"); } @Test // DATAKV-105 void shouldReturnNullWhenNoKeySpaceFoundOnComposedPersistentAnnotation() { assertThat(resolver.resolveKeySpace(TypeWithInhteritedPersistentAnnotationNotHavingKeySpace.class)).isNull(); } @Test // DATAKV-105 void shouldReturnNullWhenPersistentIsFoundOnNonComposedAnnotation() {
// Path: src/test/java/org/springframework/data/keyvalue/TypeWithDirectKeySpaceAnnotation.java // @KeySpace("rhaegar") // public class TypeWithDirectKeySpaceAnnotation { // // } // // Path: src/test/java/org/springframework/data/keyvalue/TypeWithInhteritedPersistentAnnotationNotHavingKeySpace.java // @TypeAlias("foo") // public class TypeWithInhteritedPersistentAnnotationNotHavingKeySpace { // // } // // Path: src/test/java/org/springframework/data/keyvalue/TypeWithPersistentAnnotationNotHavingKeySpace.java // @Persistent // public class TypeWithPersistentAnnotationNotHavingKeySpace { // // } // Path: src/test/java/org/springframework/data/keyvalue/core/mapping/AnnotationBasedKeySpaceResolverUnitTests.java import org.springframework.data.keyvalue.annotation.KeySpace; import static org.assertj.core.api.Assertions.*; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.annotation.AliasFor; import org.springframework.data.annotation.Persistent; import org.springframework.data.keyvalue.TypeWithDirectKeySpaceAnnotation; import org.springframework.data.keyvalue.TypeWithInhteritedPersistentAnnotationNotHavingKeySpace; import org.springframework.data.keyvalue.TypeWithPersistentAnnotationNotHavingKeySpace; /* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core.mapping; /** * Unit tests for {@link AnnotationBasedKeySpaceResolver}. * * @author Christoph Strobl * @author Oliver Gierke */ class AnnotationBasedKeySpaceResolverUnitTests { private AnnotationBasedKeySpaceResolver resolver; @BeforeEach void setUp() { resolver = AnnotationBasedKeySpaceResolver.INSTANCE; } @Test // DATACMNS-525 void shouldResolveKeySpaceDefaultValueCorrectly() { assertThat(resolver.resolveKeySpace(EntityWithDefaultKeySpace.class)).isEqualTo("daenerys"); } @Test // DATAKV-105 void shouldReturnNullWhenNoKeySpaceFoundOnComposedPersistentAnnotation() { assertThat(resolver.resolveKeySpace(TypeWithInhteritedPersistentAnnotationNotHavingKeySpace.class)).isNull(); } @Test // DATAKV-105 void shouldReturnNullWhenPersistentIsFoundOnNonComposedAnnotation() {
assertThat(resolver.resolveKeySpace(TypeWithPersistentAnnotationNotHavingKeySpace.class)).isNull();
spring-projects/spring-data-keyvalue
src/test/java/org/springframework/data/keyvalue/core/mapping/AnnotationBasedKeySpaceResolverUnitTests.java
// Path: src/test/java/org/springframework/data/keyvalue/TypeWithDirectKeySpaceAnnotation.java // @KeySpace("rhaegar") // public class TypeWithDirectKeySpaceAnnotation { // // } // // Path: src/test/java/org/springframework/data/keyvalue/TypeWithInhteritedPersistentAnnotationNotHavingKeySpace.java // @TypeAlias("foo") // public class TypeWithInhteritedPersistentAnnotationNotHavingKeySpace { // // } // // Path: src/test/java/org/springframework/data/keyvalue/TypeWithPersistentAnnotationNotHavingKeySpace.java // @Persistent // public class TypeWithPersistentAnnotationNotHavingKeySpace { // // }
import org.springframework.data.keyvalue.annotation.KeySpace; import static org.assertj.core.api.Assertions.*; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.annotation.AliasFor; import org.springframework.data.annotation.Persistent; import org.springframework.data.keyvalue.TypeWithDirectKeySpaceAnnotation; import org.springframework.data.keyvalue.TypeWithInhteritedPersistentAnnotationNotHavingKeySpace; import org.springframework.data.keyvalue.TypeWithPersistentAnnotationNotHavingKeySpace;
/* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core.mapping; /** * Unit tests for {@link AnnotationBasedKeySpaceResolver}. * * @author Christoph Strobl * @author Oliver Gierke */ class AnnotationBasedKeySpaceResolverUnitTests { private AnnotationBasedKeySpaceResolver resolver; @BeforeEach void setUp() { resolver = AnnotationBasedKeySpaceResolver.INSTANCE; } @Test // DATACMNS-525 void shouldResolveKeySpaceDefaultValueCorrectly() { assertThat(resolver.resolveKeySpace(EntityWithDefaultKeySpace.class)).isEqualTo("daenerys"); } @Test // DATAKV-105 void shouldReturnNullWhenNoKeySpaceFoundOnComposedPersistentAnnotation() { assertThat(resolver.resolveKeySpace(TypeWithInhteritedPersistentAnnotationNotHavingKeySpace.class)).isNull(); } @Test // DATAKV-105 void shouldReturnNullWhenPersistentIsFoundOnNonComposedAnnotation() { assertThat(resolver.resolveKeySpace(TypeWithPersistentAnnotationNotHavingKeySpace.class)).isNull(); } @Test // DATAKV-105 void shouldReturnNullWhenPersistentIsNotFound() { assertThat(resolver.resolveKeySpace(TypeWithoutKeySpace.class)).isNull(); } @Test // DATACMNS-525 void shouldResolveInheritedKeySpaceCorrectly() { assertThat(resolver.resolveKeySpace(EntityWithInheritedKeySpace.class)).isEqualTo("viserys"); } @Test // DATACMNS-525 void shouldResolveDirectKeySpaceAnnotationCorrectly() {
// Path: src/test/java/org/springframework/data/keyvalue/TypeWithDirectKeySpaceAnnotation.java // @KeySpace("rhaegar") // public class TypeWithDirectKeySpaceAnnotation { // // } // // Path: src/test/java/org/springframework/data/keyvalue/TypeWithInhteritedPersistentAnnotationNotHavingKeySpace.java // @TypeAlias("foo") // public class TypeWithInhteritedPersistentAnnotationNotHavingKeySpace { // // } // // Path: src/test/java/org/springframework/data/keyvalue/TypeWithPersistentAnnotationNotHavingKeySpace.java // @Persistent // public class TypeWithPersistentAnnotationNotHavingKeySpace { // // } // Path: src/test/java/org/springframework/data/keyvalue/core/mapping/AnnotationBasedKeySpaceResolverUnitTests.java import org.springframework.data.keyvalue.annotation.KeySpace; import static org.assertj.core.api.Assertions.*; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.annotation.AliasFor; import org.springframework.data.annotation.Persistent; import org.springframework.data.keyvalue.TypeWithDirectKeySpaceAnnotation; import org.springframework.data.keyvalue.TypeWithInhteritedPersistentAnnotationNotHavingKeySpace; import org.springframework.data.keyvalue.TypeWithPersistentAnnotationNotHavingKeySpace; /* * Copyright 2014-2022 the original author or authors. * * 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 * * https://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.springframework.data.keyvalue.core.mapping; /** * Unit tests for {@link AnnotationBasedKeySpaceResolver}. * * @author Christoph Strobl * @author Oliver Gierke */ class AnnotationBasedKeySpaceResolverUnitTests { private AnnotationBasedKeySpaceResolver resolver; @BeforeEach void setUp() { resolver = AnnotationBasedKeySpaceResolver.INSTANCE; } @Test // DATACMNS-525 void shouldResolveKeySpaceDefaultValueCorrectly() { assertThat(resolver.resolveKeySpace(EntityWithDefaultKeySpace.class)).isEqualTo("daenerys"); } @Test // DATAKV-105 void shouldReturnNullWhenNoKeySpaceFoundOnComposedPersistentAnnotation() { assertThat(resolver.resolveKeySpace(TypeWithInhteritedPersistentAnnotationNotHavingKeySpace.class)).isNull(); } @Test // DATAKV-105 void shouldReturnNullWhenPersistentIsFoundOnNonComposedAnnotation() { assertThat(resolver.resolveKeySpace(TypeWithPersistentAnnotationNotHavingKeySpace.class)).isNull(); } @Test // DATAKV-105 void shouldReturnNullWhenPersistentIsNotFound() { assertThat(resolver.resolveKeySpace(TypeWithoutKeySpace.class)).isNull(); } @Test // DATACMNS-525 void shouldResolveInheritedKeySpaceCorrectly() { assertThat(resolver.resolveKeySpace(EntityWithInheritedKeySpace.class)).isEqualTo("viserys"); } @Test // DATACMNS-525 void shouldResolveDirectKeySpaceAnnotationCorrectly() {
assertThat(resolver.resolveKeySpace(TypeWithDirectKeySpaceAnnotation.class)).isEqualTo("rhaegar");
keigohtr/apitore-sdk-java
jsoup-response/src/main/java/com/apitore/banana/response/org/jsoup/sample/Api12Url2HtmlExample.java
// Path: jsoup-response/src/main/java/com/apitore/banana/response/org/jsoup/TextResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class TextResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 5066032034986918495L; // // @ApiModelProperty(required=true, value="Text") // private String text=""; // // }
import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.org.jsoup.TextResponseEntity; import com.apitore.banana.utils.UrlFormatter;
package com.apitore.banana.response.org.jsoup.sample; /** * @author Keigo Hattori */ public class Api12Url2HtmlExample { static String ENDPOINT = "https://api.apitore.com/api/12/jsoup/url2html"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("url", "https://apitore.com/"); String url = UrlFormatter.format(ENDPOINT, params);
// Path: jsoup-response/src/main/java/com/apitore/banana/response/org/jsoup/TextResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class TextResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 5066032034986918495L; // // @ApiModelProperty(required=true, value="Text") // private String text=""; // // } // Path: jsoup-response/src/main/java/com/apitore/banana/response/org/jsoup/sample/Api12Url2HtmlExample.java import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.org.jsoup.TextResponseEntity; import com.apitore.banana.utils.UrlFormatter; package com.apitore.banana.response.org.jsoup.sample; /** * @author Keigo Hattori */ public class Api12Url2HtmlExample { static String ENDPOINT = "https://api.apitore.com/api/12/jsoup/url2html"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("url", "https://apitore.com/"); String url = UrlFormatter.format(ENDPOINT, params);
TextResponseEntity response =
keigohtr/apitore-sdk-java
clustering-response/src/main/java/com/apitore/banana/response/clustering/sample/Api49CosineSimilarityExample2.java
// Path: clustering-response/src/main/java/com/apitore/banana/response/clustering/SimilarityResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class SimilarityResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 4013846503995589485L; // // @ApiModelProperty(required=true, value="Score") // private double score; // // }
import java.io.IOException; import java.nio.charset.Charset; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.apitore.banana.request.clustering.VecwordRequestEntity; import com.apitore.banana.response.clustering.SimilarityResponseEntity; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper;
package com.apitore.banana.response.clustering.sample; /** * @author Keigo Hattori */ public class Api49CosineSimilarityExample2 { static String ENDPOINT = "https://api.apitore.com/api/49/cosine-similarity/vec-word"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String url = String.format("%s?access_token=%s", ENDPOINT, ACCESS_TOKEN); ObjectMapper mapper = new ObjectMapper(); VecwordRequestEntity req = new VecwordRequestEntity(); req.setVec(new double[]{1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0}); req.setWord("犬"); String json = mapper.writeValueAsString(req); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(json, headers);
// Path: clustering-response/src/main/java/com/apitore/banana/response/clustering/SimilarityResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class SimilarityResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 4013846503995589485L; // // @ApiModelProperty(required=true, value="Score") // private double score; // // } // Path: clustering-response/src/main/java/com/apitore/banana/response/clustering/sample/Api49CosineSimilarityExample2.java import java.io.IOException; import java.nio.charset.Charset; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.apitore.banana.request.clustering.VecwordRequestEntity; import com.apitore.banana.response.clustering.SimilarityResponseEntity; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; package com.apitore.banana.response.clustering.sample; /** * @author Keigo Hattori */ public class Api49CosineSimilarityExample2 { static String ENDPOINT = "https://api.apitore.com/api/49/cosine-similarity/vec-word"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String url = String.format("%s?access_token=%s", ENDPOINT, ACCESS_TOKEN); ObjectMapper mapper = new ObjectMapper(); VecwordRequestEntity req = new VecwordRequestEntity(); req.setVec(new double[]{1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0}); req.setWord("犬"); String json = mapper.writeValueAsString(req); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(json, headers);
ResponseEntity<SimilarityResponseEntity> response = restTemplate
keigohtr/apitore-sdk-java
clustering-response/src/main/java/com/apitore/banana/response/clustering/sample/Api49CosineSimilarityExample.java
// Path: clustering-response/src/main/java/com/apitore/banana/request/clustering/VecvecRequestEntity.java // @ApiModel // @Data // public class VecvecRequestEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -9107786130526792159L; // // @ApiModelProperty(required=true, value="Vector1") // double[] vec1; // @ApiModelProperty(required=true, value="Vector2") // double[] vec2; // // } // // Path: clustering-response/src/main/java/com/apitore/banana/response/clustering/SimilarityResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class SimilarityResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 4013846503995589485L; // // @ApiModelProperty(required=true, value="Score") // private double score; // // }
import java.io.IOException; import java.nio.charset.Charset; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.apitore.banana.request.clustering.VecvecRequestEntity; import com.apitore.banana.response.clustering.SimilarityResponseEntity; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper;
package com.apitore.banana.response.clustering.sample; /** * @author Keigo Hattori */ public class Api49CosineSimilarityExample { static String ENDPOINT = "https://api.apitore.com/api/49/cosine-similarity/vec-vec"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String url = String.format("%s?access_token=%s", ENDPOINT, ACCESS_TOKEN); ObjectMapper mapper = new ObjectMapper();
// Path: clustering-response/src/main/java/com/apitore/banana/request/clustering/VecvecRequestEntity.java // @ApiModel // @Data // public class VecvecRequestEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -9107786130526792159L; // // @ApiModelProperty(required=true, value="Vector1") // double[] vec1; // @ApiModelProperty(required=true, value="Vector2") // double[] vec2; // // } // // Path: clustering-response/src/main/java/com/apitore/banana/response/clustering/SimilarityResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class SimilarityResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 4013846503995589485L; // // @ApiModelProperty(required=true, value="Score") // private double score; // // } // Path: clustering-response/src/main/java/com/apitore/banana/response/clustering/sample/Api49CosineSimilarityExample.java import java.io.IOException; import java.nio.charset.Charset; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.apitore.banana.request.clustering.VecvecRequestEntity; import com.apitore.banana.response.clustering.SimilarityResponseEntity; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; package com.apitore.banana.response.clustering.sample; /** * @author Keigo Hattori */ public class Api49CosineSimilarityExample { static String ENDPOINT = "https://api.apitore.com/api/49/cosine-similarity/vec-vec"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String url = String.format("%s?access_token=%s", ENDPOINT, ACCESS_TOKEN); ObjectMapper mapper = new ObjectMapper();
VecvecRequestEntity req = new VecvecRequestEntity();
keigohtr/apitore-sdk-java
clustering-response/src/main/java/com/apitore/banana/response/clustering/sample/Api49CosineSimilarityExample.java
// Path: clustering-response/src/main/java/com/apitore/banana/request/clustering/VecvecRequestEntity.java // @ApiModel // @Data // public class VecvecRequestEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -9107786130526792159L; // // @ApiModelProperty(required=true, value="Vector1") // double[] vec1; // @ApiModelProperty(required=true, value="Vector2") // double[] vec2; // // } // // Path: clustering-response/src/main/java/com/apitore/banana/response/clustering/SimilarityResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class SimilarityResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 4013846503995589485L; // // @ApiModelProperty(required=true, value="Score") // private double score; // // }
import java.io.IOException; import java.nio.charset.Charset; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.apitore.banana.request.clustering.VecvecRequestEntity; import com.apitore.banana.response.clustering.SimilarityResponseEntity; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper;
package com.apitore.banana.response.clustering.sample; /** * @author Keigo Hattori */ public class Api49CosineSimilarityExample { static String ENDPOINT = "https://api.apitore.com/api/49/cosine-similarity/vec-vec"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String url = String.format("%s?access_token=%s", ENDPOINT, ACCESS_TOKEN); ObjectMapper mapper = new ObjectMapper(); VecvecRequestEntity req = new VecvecRequestEntity(); req.setVec1(new double[]{1,0,1}); req.setVec2(new double[]{1,1,1}); String json = mapper.writeValueAsString(req); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(json, headers);
// Path: clustering-response/src/main/java/com/apitore/banana/request/clustering/VecvecRequestEntity.java // @ApiModel // @Data // public class VecvecRequestEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -9107786130526792159L; // // @ApiModelProperty(required=true, value="Vector1") // double[] vec1; // @ApiModelProperty(required=true, value="Vector2") // double[] vec2; // // } // // Path: clustering-response/src/main/java/com/apitore/banana/response/clustering/SimilarityResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class SimilarityResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 4013846503995589485L; // // @ApiModelProperty(required=true, value="Score") // private double score; // // } // Path: clustering-response/src/main/java/com/apitore/banana/response/clustering/sample/Api49CosineSimilarityExample.java import java.io.IOException; import java.nio.charset.Charset; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.apitore.banana.request.clustering.VecvecRequestEntity; import com.apitore.banana.response.clustering.SimilarityResponseEntity; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; package com.apitore.banana.response.clustering.sample; /** * @author Keigo Hattori */ public class Api49CosineSimilarityExample { static String ENDPOINT = "https://api.apitore.com/api/49/cosine-similarity/vec-vec"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String url = String.format("%s?access_token=%s", ENDPOINT, ACCESS_TOKEN); ObjectMapper mapper = new ObjectMapper(); VecvecRequestEntity req = new VecvecRequestEntity(); req.setVec1(new double[]{1,0,1}); req.setVec2(new double[]{1,1,1}); String json = mapper.writeValueAsString(req); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(json, headers);
ResponseEntity<SimilarityResponseEntity> response = restTemplate
keigohtr/apitore-sdk-java
clustering-response/src/main/java/com/apitore/banana/response/clustering/SimilarityResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.clustering; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: clustering-response/src/main/java/com/apitore/banana/response/clustering/SimilarityResponseEntity.java import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.clustering; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class SimilarityResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/SynlinkResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import java.util.ArrayList; import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.de.sciss.ws4j; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/SynlinkResponseEntity.java import java.util.ArrayList; import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.de.sciss.ws4j; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class SynlinkResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
rome-response/src/main/java/com/apitore/banana/response/org/rome/sample/Api28Rss2JsonExample.java
// Path: rome-response/src/main/java/com/apitore/banana/response/org/rome/SyndFeedResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class SyndFeedResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 1612117803916011224L; // // @ApiModelProperty(required=true, value="Input RSS") // private String rss=""; // @ApiModelProperty(required=false, value="Author") // private String author=""; // @ApiModelProperty(required=true, value="Title") // private String title=""; // @ApiModelProperty(required=true, value="Link") // private String link=""; // @ApiModelProperty(required=false, value="Description") // private String description=""; // @ApiModelProperty(required=true, value="Published Date") // private Date pubDate=new Date(); // @ApiModelProperty(required=true, value="Num") // private int num=0; // @ApiModelProperty(required=true, value="Entries") // private List<SyndEntryEntity> entries=new ArrayList<>(); // // }
import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.org.rome.SyndFeedResponseEntity; import com.apitore.banana.utils.UrlFormatter;
package com.apitore.banana.response.org.rome.sample; /** * @author Keigo Hattori */ public class Api28Rss2JsonExample { static String ENDPOINT = "https://api.apitore.com/api/28/rome/rss2json"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("rss", "http://news.yahoo.co.jp/pickup/rss.xml"); String url = UrlFormatter.format(ENDPOINT, params);
// Path: rome-response/src/main/java/com/apitore/banana/response/org/rome/SyndFeedResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class SyndFeedResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 1612117803916011224L; // // @ApiModelProperty(required=true, value="Input RSS") // private String rss=""; // @ApiModelProperty(required=false, value="Author") // private String author=""; // @ApiModelProperty(required=true, value="Title") // private String title=""; // @ApiModelProperty(required=true, value="Link") // private String link=""; // @ApiModelProperty(required=false, value="Description") // private String description=""; // @ApiModelProperty(required=true, value="Published Date") // private Date pubDate=new Date(); // @ApiModelProperty(required=true, value="Num") // private int num=0; // @ApiModelProperty(required=true, value="Entries") // private List<SyndEntryEntity> entries=new ArrayList<>(); // // } // Path: rome-response/src/main/java/com/apitore/banana/response/org/rome/sample/Api28Rss2JsonExample.java import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.org.rome.SyndFeedResponseEntity; import com.apitore.banana.utils.UrlFormatter; package com.apitore.banana.response.org.rome.sample; /** * @author Keigo Hattori */ public class Api28Rss2JsonExample { static String ENDPOINT = "https://api.apitore.com/api/28/rome/rss2json"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("rss", "http://news.yahoo.co.jp/pickup/rss.xml"); String url = UrlFormatter.format(ENDPOINT, params);
SyndFeedResponseEntity response =
keigohtr/apitore-sdk-java
wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/WordnetSimilarityResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.de.sciss.ws4j; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/WordnetSimilarityResponseEntity.java import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.de.sciss.ws4j; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class WordnetSimilarityResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
summarize-response/src/main/java/com/apitore/banana/response/summarize/DocumentFrequencyResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.summarize; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: summarize-response/src/main/java/com/apitore/banana/response/summarize/DocumentFrequencyResponseEntity.java import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.summarize; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class DocumentFrequencyResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
summarize-response/src/main/java/com/apitore/banana/response/summarize/sample/Api20Url2LabelTfidfExample.java
// Path: summarize-response/src/main/java/com/apitore/banana/response/summarize/LabelResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class LabelResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = -2477423610645950392L; // // @ApiModelProperty(required=true, value="Input word") // private String input; // @ApiModelProperty(required=true, value="Input num") // private String num; // @ApiModelProperty(required=false, value="Distances") // private List<LabelEntity> labels; // // }
import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.summarize.LabelResponseEntity; import com.apitore.banana.utils.UrlFormatter;
package com.apitore.banana.response.summarize.sample; /** * @author Keigo Hattori */ public class Api20Url2LabelTfidfExample { static String ENDPOINT = "https://api.apitore.com/api/20/url2label-tfidf/get"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("url", "https://apitore.com/"); params.put("num", "5"); String url = UrlFormatter.format(ENDPOINT, params);
// Path: summarize-response/src/main/java/com/apitore/banana/response/summarize/LabelResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class LabelResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = -2477423610645950392L; // // @ApiModelProperty(required=true, value="Input word") // private String input; // @ApiModelProperty(required=true, value="Input num") // private String num; // @ApiModelProperty(required=false, value="Distances") // private List<LabelEntity> labels; // // } // Path: summarize-response/src/main/java/com/apitore/banana/response/summarize/sample/Api20Url2LabelTfidfExample.java import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.summarize.LabelResponseEntity; import com.apitore.banana.utils.UrlFormatter; package com.apitore.banana.response.summarize.sample; /** * @author Keigo Hattori */ public class Api20Url2LabelTfidfExample { static String ENDPOINT = "https://api.apitore.com/api/20/url2label-tfidf/get"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("url", "https://apitore.com/"); params.put("num", "5"); String url = UrlFormatter.format(ENDPOINT, params);
LabelResponseEntity response =
keigohtr/apitore-sdk-java
wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/sample/Api41WordNetSimpleSynonymExample.java
// Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/LinksResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class LinksResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = -2982202860771009522L; // // @ApiModelProperty(required=true, value="Input word") // private String word=""; // @ApiModelProperty(required=true, value="Entries") // private List<LinkWordsEntity> entries=new ArrayList<>(); // // }
import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.de.sciss.ws4j.LinksResponseEntity; import com.apitore.banana.utils.UrlFormatter;
package com.apitore.banana.response.de.sciss.ws4j.sample; /** * @author Keigo Hattori */ public class Api41WordNetSimpleSynonymExample { static String ENDPOINT = "https://api.apitore.com/api/41/wordnet-simple/synonym"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("word", "犬"); String url = UrlFormatter.format(ENDPOINT, params);
// Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/LinksResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class LinksResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = -2982202860771009522L; // // @ApiModelProperty(required=true, value="Input word") // private String word=""; // @ApiModelProperty(required=true, value="Entries") // private List<LinkWordsEntity> entries=new ArrayList<>(); // // } // Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/sample/Api41WordNetSimpleSynonymExample.java import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.de.sciss.ws4j.LinksResponseEntity; import com.apitore.banana.utils.UrlFormatter; package com.apitore.banana.response.de.sciss.ws4j.sample; /** * @author Keigo Hattori */ public class Api41WordNetSimpleSynonymExample { static String ENDPOINT = "https://api.apitore.com/api/41/wordnet-simple/synonym"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("word", "犬"); String url = UrlFormatter.format(ENDPOINT, params);
LinksResponseEntity response =
keigohtr/apitore-sdk-java
wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/SynsetDefResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.de.sciss.ws4j; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/SynsetDefResponseEntity.java import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.de.sciss.ws4j; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class SynsetDefResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
word2vec-response/src/main/java/com/apitore/banana/response/word2vec/WordVectorResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.word2vec; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: word2vec-response/src/main/java/com/apitore/banana/response/word2vec/WordVectorResponseEntity.java import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.word2vec; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class WordVectorResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
word2vec-response/src/main/java/com/apitore/banana/response/word2vec/VectorDistanceResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.word2vec; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: word2vec-response/src/main/java/com/apitore/banana/response/word2vec/VectorDistanceResponseEntity.java import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.word2vec; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class VectorDistanceResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
word2vec-response/src/main/java/com/apitore/banana/response/word2vec/AnalogyResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.word2vec; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: word2vec-response/src/main/java/com/apitore/banana/response/word2vec/AnalogyResponseEntity.java import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.word2vec; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class AnalogyResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/sample/Api42WordNetSimpleHypernymExample.java
// Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/LinksResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class LinksResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = -2982202860771009522L; // // @ApiModelProperty(required=true, value="Input word") // private String word=""; // @ApiModelProperty(required=true, value="Entries") // private List<LinkWordsEntity> entries=new ArrayList<>(); // // }
import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.de.sciss.ws4j.LinksResponseEntity; import com.apitore.banana.utils.UrlFormatter;
package com.apitore.banana.response.de.sciss.ws4j.sample; /** * @author Keigo Hattori */ public class Api42WordNetSimpleHypernymExample { static String ENDPOINT = "https://api.apitore.com/api/42/wordnet-simple/hypernym"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("word", "犬"); String url = UrlFormatter.format(ENDPOINT, params);
// Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/LinksResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class LinksResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = -2982202860771009522L; // // @ApiModelProperty(required=true, value="Input word") // private String word=""; // @ApiModelProperty(required=true, value="Entries") // private List<LinkWordsEntity> entries=new ArrayList<>(); // // } // Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/sample/Api42WordNetSimpleHypernymExample.java import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.de.sciss.ws4j.LinksResponseEntity; import com.apitore.banana.utils.UrlFormatter; package com.apitore.banana.response.de.sciss.ws4j.sample; /** * @author Keigo Hattori */ public class Api42WordNetSimpleHypernymExample { static String ENDPOINT = "https://api.apitore.com/api/42/wordnet-simple/hypernym"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("word", "犬"); String url = UrlFormatter.format(ENDPOINT, params);
LinksResponseEntity response =
keigohtr/apitore-sdk-java
summarize-response/src/main/java/com/apitore/banana/response/summarize/sample/Api19Text2LabelWordvectorExample.java
// Path: summarize-response/src/main/java/com/apitore/banana/response/summarize/LabelResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class LabelResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = -2477423610645950392L; // // @ApiModelProperty(required=true, value="Input word") // private String input; // @ApiModelProperty(required=true, value="Input num") // private String num; // @ApiModelProperty(required=false, value="Distances") // private List<LabelEntity> labels; // // }
import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.summarize.LabelResponseEntity; import com.apitore.banana.utils.UrlFormatter;
package com.apitore.banana.response.summarize.sample; /** * @author Keigo Hattori */ public class Api19Text2LabelWordvectorExample { static String ENDPOINT = "https://api.apitore.com/api/19/text2label-wordvector/get"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("text", "シナモンロールがめちゃくちゃ美味しい!"); params.put("num", "5"); String url = UrlFormatter.format(ENDPOINT, params);
// Path: summarize-response/src/main/java/com/apitore/banana/response/summarize/LabelResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class LabelResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = -2477423610645950392L; // // @ApiModelProperty(required=true, value="Input word") // private String input; // @ApiModelProperty(required=true, value="Input num") // private String num; // @ApiModelProperty(required=false, value="Distances") // private List<LabelEntity> labels; // // } // Path: summarize-response/src/main/java/com/apitore/banana/response/summarize/sample/Api19Text2LabelWordvectorExample.java import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.summarize.LabelResponseEntity; import com.apitore.banana.utils.UrlFormatter; package com.apitore.banana.response.summarize.sample; /** * @author Keigo Hattori */ public class Api19Text2LabelWordvectorExample { static String ENDPOINT = "https://api.apitore.com/api/19/text2label-wordvector/get"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("text", "シナモンロールがめちゃくちゃ美味しい!"); params.put("num", "5"); String url = UrlFormatter.format(ENDPOINT, params);
LabelResponseEntity response =
keigohtr/apitore-sdk-java
summarize-response/src/main/java/com/apitore/banana/response/summarize/LabelResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.summarize; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: summarize-response/src/main/java/com/apitore/banana/response/summarize/LabelResponseEntity.java import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.summarize; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class LabelResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
text-similarity-response/src/main/java/com/apitore/banana/response/textsimilarity/TextSimilarityResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.textsimilarity; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: text-similarity-response/src/main/java/com/apitore/banana/response/textsimilarity/TextSimilarityResponseEntity.java import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.textsimilarity; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class TextSimilarityResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/LinksResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import java.util.ArrayList; import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.de.sciss.ws4j; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/LinksResponseEntity.java import java.util.ArrayList; import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.de.sciss.ws4j; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class LinksResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
text-similarity-response/src/main/java/com/apitore/banana/response/textsimilarity/sample/Api53SentenceSimilarityExample.java
// Path: text-similarity-response/src/main/java/com/apitore/banana/response/textsimilarity/TextSimilarityResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class TextSimilarityResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 8870874086273031574L; // // @ApiModelProperty(required=true, value="Text1") // private String text1; // // @ApiModelProperty(required=true, value="Text2") // private String text2; // // @ApiModelProperty(required=true, value="Similarity") // private double similarity; // // }
import java.io.IOException; import java.nio.charset.Charset; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.apitore.banana.request.textsimilarity.TextRequestEntity; import com.apitore.banana.response.textsimilarity.TextSimilarityResponseEntity; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper;
package com.apitore.banana.response.textsimilarity.sample; /** * @author Keigo Hattori */ public class Api53SentenceSimilarityExample { static String ENDPOINT = "https://api.apitore.com/api/53/sentence-similarity/eval"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String url = String.format("%s?access_token=%s", ENDPOINT, ACCESS_TOKEN); ObjectMapper mapper = new ObjectMapper(); TextRequestEntity req = new TextRequestEntity(); req.setText1("私は犬と公園に行く"); req.setText1("私は柴犬と公園に行く"); String json = mapper.writeValueAsString(req); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(json, headers);
// Path: text-similarity-response/src/main/java/com/apitore/banana/response/textsimilarity/TextSimilarityResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class TextSimilarityResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 8870874086273031574L; // // @ApiModelProperty(required=true, value="Text1") // private String text1; // // @ApiModelProperty(required=true, value="Text2") // private String text2; // // @ApiModelProperty(required=true, value="Similarity") // private double similarity; // // } // Path: text-similarity-response/src/main/java/com/apitore/banana/response/textsimilarity/sample/Api53SentenceSimilarityExample.java import java.io.IOException; import java.nio.charset.Charset; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.apitore.banana.request.textsimilarity.TextRequestEntity; import com.apitore.banana.response.textsimilarity.TextSimilarityResponseEntity; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; package com.apitore.banana.response.textsimilarity.sample; /** * @author Keigo Hattori */ public class Api53SentenceSimilarityExample { static String ENDPOINT = "https://api.apitore.com/api/53/sentence-similarity/eval"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String url = String.format("%s?access_token=%s", ENDPOINT, ACCESS_TOKEN); ObjectMapper mapper = new ObjectMapper(); TextRequestEntity req = new TextRequestEntity(); req.setText1("私は犬と公園に行く"); req.setText1("私は柴犬と公園に行く"); String json = mapper.writeValueAsString(req); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(json, headers);
ResponseEntity<TextSimilarityResponseEntity> response = restTemplate
keigohtr/apitore-sdk-java
kuromoji-response/src/main/java/com/apitore/banana/response/com/atilika/kuromoji/sample/Api7KuromojiIpadicPostExample.java
// Path: kuromoji-response/src/main/java/com/apitore/banana/request/com/atilika/kuromoji/KuromojiRequestEntity.java // @ApiModel // @Data // public class KuromojiRequestEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 2336008124361026980L; // // @ApiModelProperty(required=true, value="texts [max 1MB]") // List<String> texts=new ArrayList<>(); // // }
import java.io.IOException; import java.nio.charset.Charset; import java.util.Arrays; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.apitore.banana.request.com.atilika.kuromoji.KuromojiRequestEntity; import com.apitore.banana.response.com.atilika.kuromoji.TokensResponseEntity; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper;
package com.apitore.banana.response.com.atilika.kuromoji.sample; /** * @author Keigo Hattori */ public class Api7KuromojiIpadicPostExample { static String ENDPOINT = "https://api.apitore.com/api/7/kuromoji-ipadic/tokenize"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String url = String.format("%s?access_token=%s", ENDPOINT, ACCESS_TOKEN); ObjectMapper mapper = new ObjectMapper();
// Path: kuromoji-response/src/main/java/com/apitore/banana/request/com/atilika/kuromoji/KuromojiRequestEntity.java // @ApiModel // @Data // public class KuromojiRequestEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 2336008124361026980L; // // @ApiModelProperty(required=true, value="texts [max 1MB]") // List<String> texts=new ArrayList<>(); // // } // Path: kuromoji-response/src/main/java/com/apitore/banana/response/com/atilika/kuromoji/sample/Api7KuromojiIpadicPostExample.java import java.io.IOException; import java.nio.charset.Charset; import java.util.Arrays; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.apitore.banana.request.com.atilika.kuromoji.KuromojiRequestEntity; import com.apitore.banana.response.com.atilika.kuromoji.TokensResponseEntity; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; package com.apitore.banana.response.com.atilika.kuromoji.sample; /** * @author Keigo Hattori */ public class Api7KuromojiIpadicPostExample { static String ENDPOINT = "https://api.apitore.com/api/7/kuromoji-ipadic/tokenize"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String url = String.format("%s?access_token=%s", ENDPOINT, ACCESS_TOKEN); ObjectMapper mapper = new ObjectMapper();
KuromojiRequestEntity req = new KuromojiRequestEntity();
keigohtr/apitore-sdk-java
wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/sample/Api47WordNetSimilarityExample.java
// Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/WordnetSimilarityResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class WordnetSimilarityResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 4749138420625233969L; // // @ApiModelProperty(required=true, value="Word1") // private String word1=""; // @ApiModelProperty(required=false, value="Pos1") // private String pos1=""; // @ApiModelProperty(required=true, value="Word2") // private String word2=""; // @ApiModelProperty(required=false, value="Pos2") // private String pos2=""; // @ApiModelProperty(required=true, value="Method") // private String method=""; // @ApiModelProperty(required=true, value="Similarity") // private double similarity=-1; // // }
import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.de.sciss.ws4j.WordnetSimilarityResponseEntity; import com.apitore.banana.utils.UrlFormatter;
package com.apitore.banana.response.de.sciss.ws4j.sample; /** * @author Keigo Hattori * * 単語の意味的な類似度を評価します。 * 評価手法は8種類あります。 * hirststonge, leacockchodorow, lesk, lin, path, resnik, wupalmer */ public class Api47WordNetSimilarityExample { static String ENDPOINT = "https://api.apitore.com/api/47/wordnet-similarity/hirststonge"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("word1", "犬"); params.put("pos1", "n"); params.put("word2", "猟犬"); params.put("pos2", "n"); String url = UrlFormatter.format(ENDPOINT, params);
// Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/WordnetSimilarityResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class WordnetSimilarityResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 4749138420625233969L; // // @ApiModelProperty(required=true, value="Word1") // private String word1=""; // @ApiModelProperty(required=false, value="Pos1") // private String pos1=""; // @ApiModelProperty(required=true, value="Word2") // private String word2=""; // @ApiModelProperty(required=false, value="Pos2") // private String pos2=""; // @ApiModelProperty(required=true, value="Method") // private String method=""; // @ApiModelProperty(required=true, value="Similarity") // private double similarity=-1; // // } // Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/sample/Api47WordNetSimilarityExample.java import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.de.sciss.ws4j.WordnetSimilarityResponseEntity; import com.apitore.banana.utils.UrlFormatter; package com.apitore.banana.response.de.sciss.ws4j.sample; /** * @author Keigo Hattori * * 単語の意味的な類似度を評価します。 * 評価手法は8種類あります。 * hirststonge, leacockchodorow, lesk, lin, path, resnik, wupalmer */ public class Api47WordNetSimilarityExample { static String ENDPOINT = "https://api.apitore.com/api/47/wordnet-similarity/hirststonge"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("word1", "犬"); params.put("pos1", "n"); params.put("word2", "猟犬"); params.put("pos2", "n"); String url = UrlFormatter.format(ENDPOINT, params);
WordnetSimilarityResponseEntity response =
keigohtr/apitore-sdk-java
wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/SynsetResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import java.util.ArrayList; import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.de.sciss.ws4j; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/SynsetResponseEntity.java import java.util.ArrayList; import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.de.sciss.ws4j; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class SynsetResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
rome-response/src/main/java/com/apitore/banana/response/org/rome/SyndFeedResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import java.util.ArrayList; import java.util.Date; import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.org.rome; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: rome-response/src/main/java/com/apitore/banana/response/org/rome/SyndFeedResponseEntity.java import java.util.ArrayList; import java.util.Date; import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.org.rome; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class SyndFeedResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
word2vec-response/src/main/java/com/apitore/banana/response/word2vec/sample/Api8Word2VecDistanceExample.java
// Path: word2vec-response/src/main/java/com/apitore/banana/response/word2vec/DistanceResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class DistanceResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 7070503881709006405L; // // @ApiModelProperty(required=true, value="Input word") // private String input; // @ApiModelProperty(required=true, value="Input num") // private String num; // @ApiModelProperty(required=false, value="Distances") // private List<DistanceEntity> distances; // // }
import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.word2vec.DistanceResponseEntity; import com.apitore.banana.utils.UrlFormatter;
package com.apitore.banana.response.word2vec.sample; /** * @author Keigo Hattori */ public class Api8Word2VecDistanceExample { static String ENDPOINT = "https://api.apitore.com/api/8/word2vec-neologd-jawiki/distance"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("word", "犬"); params.put("num", "5"); String url = UrlFormatter.format(ENDPOINT, params);
// Path: word2vec-response/src/main/java/com/apitore/banana/response/word2vec/DistanceResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class DistanceResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 7070503881709006405L; // // @ApiModelProperty(required=true, value="Input word") // private String input; // @ApiModelProperty(required=true, value="Input num") // private String num; // @ApiModelProperty(required=false, value="Distances") // private List<DistanceEntity> distances; // // } // Path: word2vec-response/src/main/java/com/apitore/banana/response/word2vec/sample/Api8Word2VecDistanceExample.java import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.word2vec.DistanceResponseEntity; import com.apitore.banana.utils.UrlFormatter; package com.apitore.banana.response.word2vec.sample; /** * @author Keigo Hattori */ public class Api8Word2VecDistanceExample { static String ENDPOINT = "https://api.apitore.com/api/8/word2vec-neologd-jawiki/distance"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("word", "犬"); params.put("num", "5"); String url = UrlFormatter.format(ENDPOINT, params);
DistanceResponseEntity response =
keigohtr/apitore-sdk-java
word2vec-response/src/main/java/com/apitore/banana/response/word2vec/DistanceResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.word2vec; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: word2vec-response/src/main/java/com/apitore/banana/response/word2vec/DistanceResponseEntity.java import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.word2vec; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class DistanceResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
clustering-response/src/main/java/com/apitore/banana/response/clustering/ClusterResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.clustering; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: clustering-response/src/main/java/com/apitore/banana/response/clustering/ClusterResponseEntity.java import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.clustering; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class ClusterResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
kuromoji-response/src/main/java/com/apitore/banana/response/com/atilika/kuromoji/TokenResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.com.atilika.kuromoji; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: kuromoji-response/src/main/java/com/apitore/banana/response/com/atilika/kuromoji/TokenResponseEntity.java import java.util.List; import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.com.atilika.kuromoji; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class TokenResponseEntity extends BaseResponseEntity {
keigohtr/apitore-sdk-java
wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/sample/Api46WordNetWordDBExample.java
// Path: wordnet-response/src/main/java/com/apitore/banana/de/sciss/ws4j/common/PosDef.java // public enum PosDef { // n ("n","noun"), // v ("v","verb"), // a ("a","adjective"), // r ("r","adverb"); // // private final String id; // private final String description; // private PosDef(final String id, final String description) { // this.id = id; // this.description = description; // } // public String getId() { // return id; // } // public String getDescription() { // return description; // } // // }
import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.de.sciss.ws4j.common.PosDef; import com.apitore.banana.response.de.sciss.ws4j.WordResponseEntity; import com.apitore.banana.utils.UrlFormatter;
package com.apitore.banana.response.de.sciss.ws4j.sample; /** * @author Keigo Hattori * * 日本語WordNetのすべてにアクセスできます。 */ public class Api46WordNetWordDBExample { static String ENDPOINT1 = "https://api.apitore.com/api/46/wordnet/word/bylemma"; static String ENDPOINT2 = "https://api.apitore.com/api/46/wordnet/word/bywordid"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate1 = new RestTemplate(); Map<String, String> params1 = new HashMap<String, String>(); params1.put("access_token", ACCESS_TOKEN); params1.put("lemma", "犬");
// Path: wordnet-response/src/main/java/com/apitore/banana/de/sciss/ws4j/common/PosDef.java // public enum PosDef { // n ("n","noun"), // v ("v","verb"), // a ("a","adjective"), // r ("r","adverb"); // // private final String id; // private final String description; // private PosDef(final String id, final String description) { // this.id = id; // this.description = description; // } // public String getId() { // return id; // } // public String getDescription() { // return description; // } // // } // Path: wordnet-response/src/main/java/com/apitore/banana/response/de/sciss/ws4j/sample/Api46WordNetWordDBExample.java import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.de.sciss.ws4j.common.PosDef; import com.apitore.banana.response.de.sciss.ws4j.WordResponseEntity; import com.apitore.banana.utils.UrlFormatter; package com.apitore.banana.response.de.sciss.ws4j.sample; /** * @author Keigo Hattori * * 日本語WordNetのすべてにアクセスできます。 */ public class Api46WordNetWordDBExample { static String ENDPOINT1 = "https://api.apitore.com/api/46/wordnet/word/bylemma"; static String ENDPOINT2 = "https://api.apitore.com/api/46/wordnet/word/bywordid"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate1 = new RestTemplate(); Map<String, String> params1 = new HashMap<String, String>(); params1.put("access_token", ACCESS_TOKEN); params1.put("lemma", "犬");
params1.put("pos", PosDef.n.toString());
keigohtr/apitore-sdk-java
word2vec-response/src/main/java/com/apitore/banana/response/word2vec/sample/Api8Word2VecWordVectorExample.java
// Path: word2vec-response/src/main/java/com/apitore/banana/response/word2vec/WordVectorResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class WordVectorResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 3050057956052841035L; // // @ApiModelProperty(required=true, value="Input word") // private String word; // @ApiModelProperty(required=false, value="Vector") // private double[] vector; // // }
import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.word2vec.WordVectorResponseEntity; import com.apitore.banana.utils.UrlFormatter;
package com.apitore.banana.response.word2vec.sample; /** * @author Keigo Hattori */ public class Api8Word2VecWordVectorExample { static String ENDPOINT = "https://api.apitore.com/api/8/word2vec-neologd-jawiki/wordvector"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("word", "犬"); String url = UrlFormatter.format(ENDPOINT, params);
// Path: word2vec-response/src/main/java/com/apitore/banana/response/word2vec/WordVectorResponseEntity.java // @ApiModel // @Data // @EqualsAndHashCode(callSuper=false) // public class WordVectorResponseEntity extends BaseResponseEntity { // // /** // * // */ // private static final long serialVersionUID = 3050057956052841035L; // // @ApiModelProperty(required=true, value="Input word") // private String word; // @ApiModelProperty(required=false, value="Vector") // private double[] vector; // // } // Path: word2vec-response/src/main/java/com/apitore/banana/response/word2vec/sample/Api8Word2VecWordVectorExample.java import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; import com.apitore.banana.response.word2vec.WordVectorResponseEntity; import com.apitore.banana.utils.UrlFormatter; package com.apitore.banana.response.word2vec.sample; /** * @author Keigo Hattori */ public class Api8Word2VecWordVectorExample { static String ENDPOINT = "https://api.apitore.com/api/8/word2vec-neologd-jawiki/wordvector"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("access_token", ACCESS_TOKEN); params.put("word", "犬"); String url = UrlFormatter.format(ENDPOINT, params);
WordVectorResponseEntity response =
keigohtr/apitore-sdk-java
word2vec-response/src/main/java/com/apitore/banana/response/sentiment/sample/Api52SentimentExample.java
// Path: word2vec-response/src/main/java/com/apitore/banana/request/sentiment/SentimentRequestEntity.java // @ApiModel // @Data // public class SentimentRequestEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -765216882722112691L; // // @ApiModelProperty(required=true, value="texts [max 1MB]") // List<String> texts=new ArrayList<>(); // // }
import java.io.IOException; import java.nio.charset.Charset; import java.util.Arrays; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.apitore.banana.request.sentiment.SentimentRequestEntity; import com.apitore.banana.response.sentiment.ListSentimentResponseEntity; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper;
package com.apitore.banana.response.sentiment.sample; /** * @author Keigo Hattori */ public class Api52SentimentExample { static String ENDPOINT = "https://api.apitore.com/api/52/sentiments/predict"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String url = String.format("%s?access_token=%s", ENDPOINT, ACCESS_TOKEN); ObjectMapper mapper = new ObjectMapper();
// Path: word2vec-response/src/main/java/com/apitore/banana/request/sentiment/SentimentRequestEntity.java // @ApiModel // @Data // public class SentimentRequestEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -765216882722112691L; // // @ApiModelProperty(required=true, value="texts [max 1MB]") // List<String> texts=new ArrayList<>(); // // } // Path: word2vec-response/src/main/java/com/apitore/banana/response/sentiment/sample/Api52SentimentExample.java import java.io.IOException; import java.nio.charset.Charset; import java.util.Arrays; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.apitore.banana.request.sentiment.SentimentRequestEntity; import com.apitore.banana.response.sentiment.ListSentimentResponseEntity; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; package com.apitore.banana.response.sentiment.sample; /** * @author Keigo Hattori */ public class Api52SentimentExample { static String ENDPOINT = "https://api.apitore.com/api/52/sentiments/predict"; static String ACCESS_TOKEN = "YOUR-ACCESS-TOKEN"; public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String url = String.format("%s?access_token=%s", ENDPOINT, ACCESS_TOKEN); ObjectMapper mapper = new ObjectMapper();
SentimentRequestEntity req = new SentimentRequestEntity();
keigohtr/apitore-sdk-java
jsoup-response/src/main/java/com/apitore/banana/response/org/jsoup/TextResponseEntity.java
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // }
import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode;
package com.apitore.banana.response.org.jsoup; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
// Path: base-response/src/main/java/com/apitore/banana/response/BaseResponseEntity.java // @ApiModel // @Data // public class BaseResponseEntity implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -809547399161925900L; // // @ApiModelProperty(required=true, value="Log message") // private String log=""; // @ApiModelProperty(required=true, value="Start date") // private String startTime=""; // @ApiModelProperty(required=true, value="End date") // private String endTime=""; // @ApiModelProperty(required=true, value="Process time [millisecond]") // private String processTime=""; // // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean error=false; // @JsonIgnore // @ApiModelProperty(hidden=true) // private boolean heavyUser=false; // // } // Path: jsoup-response/src/main/java/com/apitore/banana/response/org/jsoup/TextResponseEntity.java import com.apitore.banana.response.BaseResponseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; package com.apitore.banana.response.org.jsoup; @ApiModel @Data @EqualsAndHashCode(callSuper=false)
public class TextResponseEntity extends BaseResponseEntity {
ofelbaum/spb-transport-app
src/main/java/com/emal/android/transport/spb/utils/DrawHelper.java
// Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // }
import android.graphics.*; import android.support.v4.util.LruCache; import com.emal.android.transport.spb.VehicleType; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
package com.emal.android.transport.spb.utils; /** * User: alexey.emelyanenko@gmail.com * Date: 10/15/14 11:16 PM */ public class DrawHelper { private static Map<String, BitmapDescriptor> cacheTypes = new ConcurrentHashMap<String, BitmapDescriptor>(4); private static LruCache<String, BitmapDescriptor> cacheNumbers = new LruCache<String, BitmapDescriptor>((int)(Runtime.getRuntime().maxMemory() / 1024 / 16)); public static void evictCaches() { cacheTypes.clear(); cacheNumbers.evictAll(); }
// Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // Path: src/main/java/com/emal/android/transport/spb/utils/DrawHelper.java import android.graphics.*; import android.support.v4.util.LruCache; import com.emal.android.transport.spb.VehicleType; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; package com.emal.android.transport.spb.utils; /** * User: alexey.emelyanenko@gmail.com * Date: 10/15/14 11:16 PM */ public class DrawHelper { private static Map<String, BitmapDescriptor> cacheTypes = new ConcurrentHashMap<String, BitmapDescriptor>(4); private static LruCache<String, BitmapDescriptor> cacheNumbers = new LruCache<String, BitmapDescriptor>((int)(Runtime.getRuntime().maxMemory() / 1024 / 16)); public static void evictCaches() { cacheTypes.clear(); cacheNumbers.evictAll(); }
public static BitmapDescriptor getVechicleTypeBitmapDescriptor(VehicleType transportType, float scaleFactor) {
ofelbaum/spb-transport-app
src/main/java/com/emal/android/transport/spb/portal/Route.java
// Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // }
import com.emal.android.transport.spb.VehicleType; import java.io.Serializable;
package com.emal.android.transport.spb.portal; /** * @author alexey.emelyanenko@gmail.com * @since 1.5 */ public class Route implements Serializable, Comparable<Route>{ private String id;
// Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // Path: src/main/java/com/emal/android/transport/spb/portal/Route.java import com.emal.android.transport.spb.VehicleType; import java.io.Serializable; package com.emal.android.transport.spb.portal; /** * @author alexey.emelyanenko@gmail.com * @since 1.5 */ public class Route implements Serializable, Comparable<Route>{ private String id;
private VehicleType transportType;
ofelbaum/spb-transport-app
src/main/java/com/emal/android/transport/spb/model/ApplicationParams.java
// Path: src/main/java/com/emal/android/transport/spb/MapProviderType.java // public enum MapProviderType { // GMAPSV1, GMAPSV2, OSM; // // public static MapProviderType getByValue(String value) { // for (MapProviderType type: MapProviderType.values()) { // if (type.name().equals(value)) { // return type; // } // } // return null; // } // } // // Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // // Path: src/main/java/com/emal/android/transport/spb/utils/Constants.java // public final class Constants { // public static final String URL_TEMPLATE = "http://transport.orgp.spb.ru/cgi-bin/mapserv?TRANSPARENT=TRUE&FORMAT=image%2Fpng&MAP=vehicle_typed.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913&_OLSALT=0.1508798657450825"; // public static final String URL_PARAMS = "&LAYERS=%s&BBOX=%s&WIDTH=%d&HEIGHT=%d"; // public static final String SHOW_BUS_FLAG = "SHOW_BUS_FLAG"; // public static final String SHOW_TROLLEY_FLAG = "SHOW_TROLLEY_FLAG"; // public static final String SHOW_TRAM_FLAG = "SHOW_TRAM_FLAG"; // public static final String SHOW_SHIP_FLAG = "SHOW_SHIP_FLAG"; // public static final String SAT_VIEW_FLAG = "SAT_VIEW_FLAG"; // public static final String SHOW_TRAFFIC_FLAG = "SHOW_TRAFFIC_FLAG"; // public static final String MAP_PROVIDER_TYPE_FLAG = "MAP_PROVIDER_TYPE_FLAG"; // public static final String SYNC_TIME_FLAG = "SYNC_TIME_FLAG"; // public static final String ZOOM_FLAG = "ZOOM_FLAG"; // public static final String HOME_LOC_LONG_FLAG = "HOME_LOCATION_LONG_FLAG"; // public static final String HOME_LOC_LAT_FLAG = "HOME_LOCATION_LAT_FLAG"; // public static final String LAST_LOC_LONG_FLAG = "LAST_LOC_LONG_FLAG"; // public static final String LAST_LOC_LAT_FLAG = "LAST_LOC_LAT_FLAG"; // public static final String APP_SHARED_SOURCE = "SPB_TRANSPORT_APP"; // public static final int DEFAULT_ZOOM_LEVEL = 15; // public static final int MS_IN_SEC = 1000; // public static final int DEFAULT_SYNC_MS = 10000; // public static final String ROUTES_TO_TRACK = "ROUTES_TO_TRACK"; // public static final String THEME_FLAG = "THEME_FLAG"; // public static final String ICON_SIZE_FLAG = "ICON_SIZE_FLAG"; // public static final int DEFAULT_ICON_SIZE = 5; // }
import android.content.SharedPreferences; import android.util.Log; import com.emal.android.transport.spb.MapProviderType; import com.emal.android.transport.spb.VehicleType; import com.emal.android.transport.spb.utils.Constants; import com.google.android.gms.maps.model.LatLng; import com.google.android.maps.GeoPoint; import java.util.*; import java.util.concurrent.ConcurrentSkipListSet;
package com.emal.android.transport.spb.model; /** * User: alexey.emelyanenko@gmail.com * Date: 5/18/13 2:38 AM */ public class ApplicationParams { public static final int SPB_CENTER_LAT_DEF_VALUE = (int) (59.95f * 1E6); public static final int SPB_CENTER_LONG_DEF_VALUE = (int) (30.316667f * 1E6); private static final String TAG = "ApplicationParams"; private SharedPreferences sharedPreferences; private boolean showBus = false; private boolean showTrolley = false; private boolean showTram = false; private boolean showShip = false; private boolean satView = true; private boolean showTraffic = false;
// Path: src/main/java/com/emal/android/transport/spb/MapProviderType.java // public enum MapProviderType { // GMAPSV1, GMAPSV2, OSM; // // public static MapProviderType getByValue(String value) { // for (MapProviderType type: MapProviderType.values()) { // if (type.name().equals(value)) { // return type; // } // } // return null; // } // } // // Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // // Path: src/main/java/com/emal/android/transport/spb/utils/Constants.java // public final class Constants { // public static final String URL_TEMPLATE = "http://transport.orgp.spb.ru/cgi-bin/mapserv?TRANSPARENT=TRUE&FORMAT=image%2Fpng&MAP=vehicle_typed.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913&_OLSALT=0.1508798657450825"; // public static final String URL_PARAMS = "&LAYERS=%s&BBOX=%s&WIDTH=%d&HEIGHT=%d"; // public static final String SHOW_BUS_FLAG = "SHOW_BUS_FLAG"; // public static final String SHOW_TROLLEY_FLAG = "SHOW_TROLLEY_FLAG"; // public static final String SHOW_TRAM_FLAG = "SHOW_TRAM_FLAG"; // public static final String SHOW_SHIP_FLAG = "SHOW_SHIP_FLAG"; // public static final String SAT_VIEW_FLAG = "SAT_VIEW_FLAG"; // public static final String SHOW_TRAFFIC_FLAG = "SHOW_TRAFFIC_FLAG"; // public static final String MAP_PROVIDER_TYPE_FLAG = "MAP_PROVIDER_TYPE_FLAG"; // public static final String SYNC_TIME_FLAG = "SYNC_TIME_FLAG"; // public static final String ZOOM_FLAG = "ZOOM_FLAG"; // public static final String HOME_LOC_LONG_FLAG = "HOME_LOCATION_LONG_FLAG"; // public static final String HOME_LOC_LAT_FLAG = "HOME_LOCATION_LAT_FLAG"; // public static final String LAST_LOC_LONG_FLAG = "LAST_LOC_LONG_FLAG"; // public static final String LAST_LOC_LAT_FLAG = "LAST_LOC_LAT_FLAG"; // public static final String APP_SHARED_SOURCE = "SPB_TRANSPORT_APP"; // public static final int DEFAULT_ZOOM_LEVEL = 15; // public static final int MS_IN_SEC = 1000; // public static final int DEFAULT_SYNC_MS = 10000; // public static final String ROUTES_TO_TRACK = "ROUTES_TO_TRACK"; // public static final String THEME_FLAG = "THEME_FLAG"; // public static final String ICON_SIZE_FLAG = "ICON_SIZE_FLAG"; // public static final int DEFAULT_ICON_SIZE = 5; // } // Path: src/main/java/com/emal/android/transport/spb/model/ApplicationParams.java import android.content.SharedPreferences; import android.util.Log; import com.emal.android.transport.spb.MapProviderType; import com.emal.android.transport.spb.VehicleType; import com.emal.android.transport.spb.utils.Constants; import com.google.android.gms.maps.model.LatLng; import com.google.android.maps.GeoPoint; import java.util.*; import java.util.concurrent.ConcurrentSkipListSet; package com.emal.android.transport.spb.model; /** * User: alexey.emelyanenko@gmail.com * Date: 5/18/13 2:38 AM */ public class ApplicationParams { public static final int SPB_CENTER_LAT_DEF_VALUE = (int) (59.95f * 1E6); public static final int SPB_CENTER_LONG_DEF_VALUE = (int) (30.316667f * 1E6); private static final String TAG = "ApplicationParams"; private SharedPreferences sharedPreferences; private boolean showBus = false; private boolean showTrolley = false; private boolean showTram = false; private boolean showShip = false; private boolean satView = true; private boolean showTraffic = false;
private MapProviderType mapProviderType;
ofelbaum/spb-transport-app
src/main/java/com/emal/android/transport/spb/model/ApplicationParams.java
// Path: src/main/java/com/emal/android/transport/spb/MapProviderType.java // public enum MapProviderType { // GMAPSV1, GMAPSV2, OSM; // // public static MapProviderType getByValue(String value) { // for (MapProviderType type: MapProviderType.values()) { // if (type.name().equals(value)) { // return type; // } // } // return null; // } // } // // Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // // Path: src/main/java/com/emal/android/transport/spb/utils/Constants.java // public final class Constants { // public static final String URL_TEMPLATE = "http://transport.orgp.spb.ru/cgi-bin/mapserv?TRANSPARENT=TRUE&FORMAT=image%2Fpng&MAP=vehicle_typed.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913&_OLSALT=0.1508798657450825"; // public static final String URL_PARAMS = "&LAYERS=%s&BBOX=%s&WIDTH=%d&HEIGHT=%d"; // public static final String SHOW_BUS_FLAG = "SHOW_BUS_FLAG"; // public static final String SHOW_TROLLEY_FLAG = "SHOW_TROLLEY_FLAG"; // public static final String SHOW_TRAM_FLAG = "SHOW_TRAM_FLAG"; // public static final String SHOW_SHIP_FLAG = "SHOW_SHIP_FLAG"; // public static final String SAT_VIEW_FLAG = "SAT_VIEW_FLAG"; // public static final String SHOW_TRAFFIC_FLAG = "SHOW_TRAFFIC_FLAG"; // public static final String MAP_PROVIDER_TYPE_FLAG = "MAP_PROVIDER_TYPE_FLAG"; // public static final String SYNC_TIME_FLAG = "SYNC_TIME_FLAG"; // public static final String ZOOM_FLAG = "ZOOM_FLAG"; // public static final String HOME_LOC_LONG_FLAG = "HOME_LOCATION_LONG_FLAG"; // public static final String HOME_LOC_LAT_FLAG = "HOME_LOCATION_LAT_FLAG"; // public static final String LAST_LOC_LONG_FLAG = "LAST_LOC_LONG_FLAG"; // public static final String LAST_LOC_LAT_FLAG = "LAST_LOC_LAT_FLAG"; // public static final String APP_SHARED_SOURCE = "SPB_TRANSPORT_APP"; // public static final int DEFAULT_ZOOM_LEVEL = 15; // public static final int MS_IN_SEC = 1000; // public static final int DEFAULT_SYNC_MS = 10000; // public static final String ROUTES_TO_TRACK = "ROUTES_TO_TRACK"; // public static final String THEME_FLAG = "THEME_FLAG"; // public static final String ICON_SIZE_FLAG = "ICON_SIZE_FLAG"; // public static final int DEFAULT_ICON_SIZE = 5; // }
import android.content.SharedPreferences; import android.util.Log; import com.emal.android.transport.spb.MapProviderType; import com.emal.android.transport.spb.VehicleType; import com.emal.android.transport.spb.utils.Constants; import com.google.android.gms.maps.model.LatLng; import com.google.android.maps.GeoPoint; import java.util.*; import java.util.concurrent.ConcurrentSkipListSet;
package com.emal.android.transport.spb.model; /** * User: alexey.emelyanenko@gmail.com * Date: 5/18/13 2:38 AM */ public class ApplicationParams { public static final int SPB_CENTER_LAT_DEF_VALUE = (int) (59.95f * 1E6); public static final int SPB_CENTER_LONG_DEF_VALUE = (int) (30.316667f * 1E6); private static final String TAG = "ApplicationParams"; private SharedPreferences sharedPreferences; private boolean showBus = false; private boolean showTrolley = false; private boolean showTram = false; private boolean showShip = false; private boolean satView = true; private boolean showTraffic = false; private MapProviderType mapProviderType;
// Path: src/main/java/com/emal/android/transport/spb/MapProviderType.java // public enum MapProviderType { // GMAPSV1, GMAPSV2, OSM; // // public static MapProviderType getByValue(String value) { // for (MapProviderType type: MapProviderType.values()) { // if (type.name().equals(value)) { // return type; // } // } // return null; // } // } // // Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // // Path: src/main/java/com/emal/android/transport/spb/utils/Constants.java // public final class Constants { // public static final String URL_TEMPLATE = "http://transport.orgp.spb.ru/cgi-bin/mapserv?TRANSPARENT=TRUE&FORMAT=image%2Fpng&MAP=vehicle_typed.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913&_OLSALT=0.1508798657450825"; // public static final String URL_PARAMS = "&LAYERS=%s&BBOX=%s&WIDTH=%d&HEIGHT=%d"; // public static final String SHOW_BUS_FLAG = "SHOW_BUS_FLAG"; // public static final String SHOW_TROLLEY_FLAG = "SHOW_TROLLEY_FLAG"; // public static final String SHOW_TRAM_FLAG = "SHOW_TRAM_FLAG"; // public static final String SHOW_SHIP_FLAG = "SHOW_SHIP_FLAG"; // public static final String SAT_VIEW_FLAG = "SAT_VIEW_FLAG"; // public static final String SHOW_TRAFFIC_FLAG = "SHOW_TRAFFIC_FLAG"; // public static final String MAP_PROVIDER_TYPE_FLAG = "MAP_PROVIDER_TYPE_FLAG"; // public static final String SYNC_TIME_FLAG = "SYNC_TIME_FLAG"; // public static final String ZOOM_FLAG = "ZOOM_FLAG"; // public static final String HOME_LOC_LONG_FLAG = "HOME_LOCATION_LONG_FLAG"; // public static final String HOME_LOC_LAT_FLAG = "HOME_LOCATION_LAT_FLAG"; // public static final String LAST_LOC_LONG_FLAG = "LAST_LOC_LONG_FLAG"; // public static final String LAST_LOC_LAT_FLAG = "LAST_LOC_LAT_FLAG"; // public static final String APP_SHARED_SOURCE = "SPB_TRANSPORT_APP"; // public static final int DEFAULT_ZOOM_LEVEL = 15; // public static final int MS_IN_SEC = 1000; // public static final int DEFAULT_SYNC_MS = 10000; // public static final String ROUTES_TO_TRACK = "ROUTES_TO_TRACK"; // public static final String THEME_FLAG = "THEME_FLAG"; // public static final String ICON_SIZE_FLAG = "ICON_SIZE_FLAG"; // public static final int DEFAULT_ICON_SIZE = 5; // } // Path: src/main/java/com/emal/android/transport/spb/model/ApplicationParams.java import android.content.SharedPreferences; import android.util.Log; import com.emal.android.transport.spb.MapProviderType; import com.emal.android.transport.spb.VehicleType; import com.emal.android.transport.spb.utils.Constants; import com.google.android.gms.maps.model.LatLng; import com.google.android.maps.GeoPoint; import java.util.*; import java.util.concurrent.ConcurrentSkipListSet; package com.emal.android.transport.spb.model; /** * User: alexey.emelyanenko@gmail.com * Date: 5/18/13 2:38 AM */ public class ApplicationParams { public static final int SPB_CENTER_LAT_DEF_VALUE = (int) (59.95f * 1E6); public static final int SPB_CENTER_LONG_DEF_VALUE = (int) (30.316667f * 1E6); private static final String TAG = "ApplicationParams"; private SharedPreferences sharedPreferences; private boolean showBus = false; private boolean showTrolley = false; private boolean showTram = false; private boolean showShip = false; private boolean satView = true; private boolean showTraffic = false; private MapProviderType mapProviderType;
private int syncTime = Constants.DEFAULT_SYNC_MS;
ofelbaum/spb-transport-app
src/main/java/com/emal/android/transport/spb/model/ApplicationParams.java
// Path: src/main/java/com/emal/android/transport/spb/MapProviderType.java // public enum MapProviderType { // GMAPSV1, GMAPSV2, OSM; // // public static MapProviderType getByValue(String value) { // for (MapProviderType type: MapProviderType.values()) { // if (type.name().equals(value)) { // return type; // } // } // return null; // } // } // // Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // // Path: src/main/java/com/emal/android/transport/spb/utils/Constants.java // public final class Constants { // public static final String URL_TEMPLATE = "http://transport.orgp.spb.ru/cgi-bin/mapserv?TRANSPARENT=TRUE&FORMAT=image%2Fpng&MAP=vehicle_typed.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913&_OLSALT=0.1508798657450825"; // public static final String URL_PARAMS = "&LAYERS=%s&BBOX=%s&WIDTH=%d&HEIGHT=%d"; // public static final String SHOW_BUS_FLAG = "SHOW_BUS_FLAG"; // public static final String SHOW_TROLLEY_FLAG = "SHOW_TROLLEY_FLAG"; // public static final String SHOW_TRAM_FLAG = "SHOW_TRAM_FLAG"; // public static final String SHOW_SHIP_FLAG = "SHOW_SHIP_FLAG"; // public static final String SAT_VIEW_FLAG = "SAT_VIEW_FLAG"; // public static final String SHOW_TRAFFIC_FLAG = "SHOW_TRAFFIC_FLAG"; // public static final String MAP_PROVIDER_TYPE_FLAG = "MAP_PROVIDER_TYPE_FLAG"; // public static final String SYNC_TIME_FLAG = "SYNC_TIME_FLAG"; // public static final String ZOOM_FLAG = "ZOOM_FLAG"; // public static final String HOME_LOC_LONG_FLAG = "HOME_LOCATION_LONG_FLAG"; // public static final String HOME_LOC_LAT_FLAG = "HOME_LOCATION_LAT_FLAG"; // public static final String LAST_LOC_LONG_FLAG = "LAST_LOC_LONG_FLAG"; // public static final String LAST_LOC_LAT_FLAG = "LAST_LOC_LAT_FLAG"; // public static final String APP_SHARED_SOURCE = "SPB_TRANSPORT_APP"; // public static final int DEFAULT_ZOOM_LEVEL = 15; // public static final int MS_IN_SEC = 1000; // public static final int DEFAULT_SYNC_MS = 10000; // public static final String ROUTES_TO_TRACK = "ROUTES_TO_TRACK"; // public static final String THEME_FLAG = "THEME_FLAG"; // public static final String ICON_SIZE_FLAG = "ICON_SIZE_FLAG"; // public static final int DEFAULT_ICON_SIZE = 5; // }
import android.content.SharedPreferences; import android.util.Log; import com.emal.android.transport.spb.MapProviderType; import com.emal.android.transport.spb.VehicleType; import com.emal.android.transport.spb.utils.Constants; import com.google.android.gms.maps.model.LatLng; import com.google.android.maps.GeoPoint; import java.util.*; import java.util.concurrent.ConcurrentSkipListSet;
} public void setMapProviderType(MapProviderType mapProviderType) { this.mapProviderType = mapProviderType; } public void setSyncTime(int syncTime) { this.syncTime = syncTime; } public void setZoomSize(int zoomSize) { this.zoomSize = zoomSize; } public void setHomeLocation(GeoPoint homeLocation) { this.homeLocation = homeLocation; } public void setLastLocation(GeoPoint lastLocation) { this.lastLocation = lastLocation; } public Set<String> getRoutesToTrack() { Log.d(TAG, "getRoutesToTrack: " + routesToTrack.getClass().getCanonicalName()); for (String s : routesToTrack) { Log.d(TAG, s); } return routesToTrack; }
// Path: src/main/java/com/emal/android/transport/spb/MapProviderType.java // public enum MapProviderType { // GMAPSV1, GMAPSV2, OSM; // // public static MapProviderType getByValue(String value) { // for (MapProviderType type: MapProviderType.values()) { // if (type.name().equals(value)) { // return type; // } // } // return null; // } // } // // Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // // Path: src/main/java/com/emal/android/transport/spb/utils/Constants.java // public final class Constants { // public static final String URL_TEMPLATE = "http://transport.orgp.spb.ru/cgi-bin/mapserv?TRANSPARENT=TRUE&FORMAT=image%2Fpng&MAP=vehicle_typed.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913&_OLSALT=0.1508798657450825"; // public static final String URL_PARAMS = "&LAYERS=%s&BBOX=%s&WIDTH=%d&HEIGHT=%d"; // public static final String SHOW_BUS_FLAG = "SHOW_BUS_FLAG"; // public static final String SHOW_TROLLEY_FLAG = "SHOW_TROLLEY_FLAG"; // public static final String SHOW_TRAM_FLAG = "SHOW_TRAM_FLAG"; // public static final String SHOW_SHIP_FLAG = "SHOW_SHIP_FLAG"; // public static final String SAT_VIEW_FLAG = "SAT_VIEW_FLAG"; // public static final String SHOW_TRAFFIC_FLAG = "SHOW_TRAFFIC_FLAG"; // public static final String MAP_PROVIDER_TYPE_FLAG = "MAP_PROVIDER_TYPE_FLAG"; // public static final String SYNC_TIME_FLAG = "SYNC_TIME_FLAG"; // public static final String ZOOM_FLAG = "ZOOM_FLAG"; // public static final String HOME_LOC_LONG_FLAG = "HOME_LOCATION_LONG_FLAG"; // public static final String HOME_LOC_LAT_FLAG = "HOME_LOCATION_LAT_FLAG"; // public static final String LAST_LOC_LONG_FLAG = "LAST_LOC_LONG_FLAG"; // public static final String LAST_LOC_LAT_FLAG = "LAST_LOC_LAT_FLAG"; // public static final String APP_SHARED_SOURCE = "SPB_TRANSPORT_APP"; // public static final int DEFAULT_ZOOM_LEVEL = 15; // public static final int MS_IN_SEC = 1000; // public static final int DEFAULT_SYNC_MS = 10000; // public static final String ROUTES_TO_TRACK = "ROUTES_TO_TRACK"; // public static final String THEME_FLAG = "THEME_FLAG"; // public static final String ICON_SIZE_FLAG = "ICON_SIZE_FLAG"; // public static final int DEFAULT_ICON_SIZE = 5; // } // Path: src/main/java/com/emal/android/transport/spb/model/ApplicationParams.java import android.content.SharedPreferences; import android.util.Log; import com.emal.android.transport.spb.MapProviderType; import com.emal.android.transport.spb.VehicleType; import com.emal.android.transport.spb.utils.Constants; import com.google.android.gms.maps.model.LatLng; import com.google.android.maps.GeoPoint; import java.util.*; import java.util.concurrent.ConcurrentSkipListSet; } public void setMapProviderType(MapProviderType mapProviderType) { this.mapProviderType = mapProviderType; } public void setSyncTime(int syncTime) { this.syncTime = syncTime; } public void setZoomSize(int zoomSize) { this.zoomSize = zoomSize; } public void setHomeLocation(GeoPoint homeLocation) { this.homeLocation = homeLocation; } public void setLastLocation(GeoPoint lastLocation) { this.lastLocation = lastLocation; } public Set<String> getRoutesToTrack() { Log.d(TAG, "getRoutesToTrack: " + routesToTrack.getClass().getCanonicalName()); for (String s : routesToTrack) { Log.d(TAG, s); } return routesToTrack; }
public List<VehicleType> getSelectedVehicleTypes() {
ofelbaum/spb-transport-app
src/main/java/com/emal/android/transport/spb/portal/PortalClient.java
// Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // }
import android.util.Log; import com.emal.android.transport.spb.VehicleType; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnManagerPNames; import org.apache.http.conn.params.ConnPerRouteBean; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.*; import org.codehaus.jackson.map.ObjectMapper; import java.io.*; import java.net.URI; import java.net.URLEncoder; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern;
private static String readResponse(HttpResponse httpResponse) { StringBuffer respBuf = new StringBuffer(); HttpEntity httpEntity = httpResponse.getEntity(); InputStream inputStream = null; try { inputStream = httpEntity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String strLine; while ((strLine = br.readLine()) != null) { respBuf.append(strLine); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return respBuf.toString(); } public List<Route> findAllRoutes() throws IOException { if (allRoutes == null) { Log.d(TAG, "Retrieving all routes");
// Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // Path: src/main/java/com/emal/android/transport/spb/portal/PortalClient.java import android.util.Log; import com.emal.android.transport.spb.VehicleType; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnManagerPNames; import org.apache.http.conn.params.ConnPerRouteBean; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.*; import org.codehaus.jackson.map.ObjectMapper; import java.io.*; import java.net.URI; import java.net.URLEncoder; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; private static String readResponse(HttpResponse httpResponse) { StringBuffer respBuf = new StringBuffer(); HttpEntity httpEntity = httpResponse.getEntity(); InputStream inputStream = null; try { inputStream = httpEntity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String strLine; while ((strLine = br.readLine()) != null) { respBuf.append(strLine); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return respBuf.toString(); } public List<Route> findAllRoutes() throws IOException { if (allRoutes == null) { Log.d(TAG, "Retrieving all routes");
allRoutes = internalFindRoutes("", VehicleType.values());
ofelbaum/spb-transport-app
src/main/java/com/emal/android/transport/spb/portal/Geometry.java
// Path: src/main/java/com/emal/android/transport/spb/utils/GeoConverter.java // public class GeoConverter { // /** // * Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913 // */ // public static Pair<Double, Double> fromLatLonToMeters(double lat, double lon) { // // // double originShift = 2 * Math.PI * 6378137 / 2.0; // Double mx = lon * originShift / 180.0; // Double my = Math.log(Math.tan((90 + lat) * Math.PI / 360.0)) / (Math.PI / 180.0); // // my = my * originShift / 180.0; // return new Pair<Double, Double>(mx, my); // } // // /** // * Get BBOX parameter from map view // * // * @param mapView // * @return // */ // public static String calculateBBox(MapView mapView) { // int latitudeSpan = mapView.getLatitudeSpan(); // int longitudeSpan = mapView.getLongitudeSpan(); // int latitudeE6 = mapView.getMapCenter().getLatitudeE6(); // int longitudeE6 = mapView.getMapCenter().getLongitudeE6(); // // int x1 = latitudeE6 - latitudeSpan / 2; // int y1 = longitudeE6 - longitudeSpan / 2; // int x2 = latitudeE6 + latitudeSpan / 2; // int y2 = longitudeE6 + longitudeSpan / 2; // // // Pair<Double, Double> p1 = GeoConverter.fromLatLonToMeters(x1 / 1E6, y1 / 1E6); // Pair<Double, Double> p2 = GeoConverter.fromLatLonToMeters(x2 / 1E6, y2 / 1E6); // // return p1.first.toString() + "," + p1.second.toString() + "," + p2.first.toString() + "," + p2.second.toString(); // } // // public static String convert(Address address) { // StringBuffer buffer = new StringBuffer(); // int maxAddressLineIndex = address.getMaxAddressLineIndex(); // for (int i = 0; i <= maxAddressLineIndex; i++) { // buffer.append(address.getAddressLine(i).trim()); // if (i < maxAddressLineIndex) { // buffer.append(", "); // } // } // return buffer.toString(); // } // // public static String calculateBBox(LatLngBounds latLngBounds) { // LatLng southwest = latLngBounds.southwest; // LatLng northeast = latLngBounds.northeast; // Pair<Double, Double> p1 = GeoConverter.fromLatLonToMeters(southwest.latitude, southwest.longitude); // Pair<Double, Double> p2 = GeoConverter.fromLatLonToMeters(northeast.latitude, northeast.longitude); // // return p1.first.toString() + "," + p1.second.toString() + "," + p2.first.toString() + "," + p2.second.toString(); // } // // /* // "Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum" // */ // public static Double[] convertMetersToLatLon(double mx, double my) { // double originShift = 2 * Math.PI * 6378137 / 2.0; // double lon = (mx / originShift) * 180.0; // double lat = (my / originShift) * 180.0; // lat = 180 / Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180.0)) - Math.PI / 2.0); // return new Double[]{lat, lon}; // } // // public static double distance(double lat1, double lon1, double lat2, double lon2) { // double lat1r = lat1 * Math.PI / 180; // double lon1r = lon1 * Math.PI / 180; // double lat2r = lat2 * Math.PI / 180; // double lon2r = lon2 * Math.PI / 180; // // double lonDelta = lon2r - lon1r; // // double up = Math.sqrt(Math.pow(Math.cos(lat2r) * Math.sin(lonDelta), 2) + Math.pow(Math.cos(lat1r) * Math.sin(lat2r) - Math.sin(lat1r) * Math.cos(lat2r) * Math.cos(lonDelta), 2)); // double down = Math.sin(lat1r) * Math.sin(lat2r) + Math.cos(lat1r) * Math.cos(lat2r) * Math.cos(lonDelta); // double res = Math.atan(up / down) * 6367444.6571225; // return res; // } // // public static CameraUpdate toCameraUpdate(GeoPoint geoPoint, float zoom) { // LatLng latLng = new LatLng(geoPoint.getLatitudeE6() / 1E6, geoPoint.getLongitudeE6() / 1E6); // return CameraUpdateFactory.newLatLngZoom(latLng, zoom); // } // }
import com.emal.android.transport.spb.utils.GeoConverter; import org.codehaus.jackson.annotate.JsonProperty; import java.util.Arrays; import java.util.List;
package com.emal.android.transport.spb.portal; /** * @author alexey.emelyanenko@gmail.com * @since 1.5 */ public class Geometry { @JsonProperty(value = "type") private String type; private Double longtitude; private Double latitude; public Geometry() { } public Geometry(Double latitude, Double longtitude) { setCoordinates(Arrays.asList(longtitude, latitude)); } public String getType() { return type; } public void setType(String type) { this.type = type; } @JsonProperty(value = "coordinates") public void setCoordinates(List<Double> coordinates) {
// Path: src/main/java/com/emal/android/transport/spb/utils/GeoConverter.java // public class GeoConverter { // /** // * Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913 // */ // public static Pair<Double, Double> fromLatLonToMeters(double lat, double lon) { // // // double originShift = 2 * Math.PI * 6378137 / 2.0; // Double mx = lon * originShift / 180.0; // Double my = Math.log(Math.tan((90 + lat) * Math.PI / 360.0)) / (Math.PI / 180.0); // // my = my * originShift / 180.0; // return new Pair<Double, Double>(mx, my); // } // // /** // * Get BBOX parameter from map view // * // * @param mapView // * @return // */ // public static String calculateBBox(MapView mapView) { // int latitudeSpan = mapView.getLatitudeSpan(); // int longitudeSpan = mapView.getLongitudeSpan(); // int latitudeE6 = mapView.getMapCenter().getLatitudeE6(); // int longitudeE6 = mapView.getMapCenter().getLongitudeE6(); // // int x1 = latitudeE6 - latitudeSpan / 2; // int y1 = longitudeE6 - longitudeSpan / 2; // int x2 = latitudeE6 + latitudeSpan / 2; // int y2 = longitudeE6 + longitudeSpan / 2; // // // Pair<Double, Double> p1 = GeoConverter.fromLatLonToMeters(x1 / 1E6, y1 / 1E6); // Pair<Double, Double> p2 = GeoConverter.fromLatLonToMeters(x2 / 1E6, y2 / 1E6); // // return p1.first.toString() + "," + p1.second.toString() + "," + p2.first.toString() + "," + p2.second.toString(); // } // // public static String convert(Address address) { // StringBuffer buffer = new StringBuffer(); // int maxAddressLineIndex = address.getMaxAddressLineIndex(); // for (int i = 0; i <= maxAddressLineIndex; i++) { // buffer.append(address.getAddressLine(i).trim()); // if (i < maxAddressLineIndex) { // buffer.append(", "); // } // } // return buffer.toString(); // } // // public static String calculateBBox(LatLngBounds latLngBounds) { // LatLng southwest = latLngBounds.southwest; // LatLng northeast = latLngBounds.northeast; // Pair<Double, Double> p1 = GeoConverter.fromLatLonToMeters(southwest.latitude, southwest.longitude); // Pair<Double, Double> p2 = GeoConverter.fromLatLonToMeters(northeast.latitude, northeast.longitude); // // return p1.first.toString() + "," + p1.second.toString() + "," + p2.first.toString() + "," + p2.second.toString(); // } // // /* // "Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum" // */ // public static Double[] convertMetersToLatLon(double mx, double my) { // double originShift = 2 * Math.PI * 6378137 / 2.0; // double lon = (mx / originShift) * 180.0; // double lat = (my / originShift) * 180.0; // lat = 180 / Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180.0)) - Math.PI / 2.0); // return new Double[]{lat, lon}; // } // // public static double distance(double lat1, double lon1, double lat2, double lon2) { // double lat1r = lat1 * Math.PI / 180; // double lon1r = lon1 * Math.PI / 180; // double lat2r = lat2 * Math.PI / 180; // double lon2r = lon2 * Math.PI / 180; // // double lonDelta = lon2r - lon1r; // // double up = Math.sqrt(Math.pow(Math.cos(lat2r) * Math.sin(lonDelta), 2) + Math.pow(Math.cos(lat1r) * Math.sin(lat2r) - Math.sin(lat1r) * Math.cos(lat2r) * Math.cos(lonDelta), 2)); // double down = Math.sin(lat1r) * Math.sin(lat2r) + Math.cos(lat1r) * Math.cos(lat2r) * Math.cos(lonDelta); // double res = Math.atan(up / down) * 6367444.6571225; // return res; // } // // public static CameraUpdate toCameraUpdate(GeoPoint geoPoint, float zoom) { // LatLng latLng = new LatLng(geoPoint.getLatitudeE6() / 1E6, geoPoint.getLongitudeE6() / 1E6); // return CameraUpdateFactory.newLatLngZoom(latLng, zoom); // } // } // Path: src/main/java/com/emal/android/transport/spb/portal/Geometry.java import com.emal.android.transport.spb.utils.GeoConverter; import org.codehaus.jackson.annotate.JsonProperty; import java.util.Arrays; import java.util.List; package com.emal.android.transport.spb.portal; /** * @author alexey.emelyanenko@gmail.com * @since 1.5 */ public class Geometry { @JsonProperty(value = "type") private String type; private Double longtitude; private Double latitude; public Geometry() { } public Geometry(Double latitude, Double longtitude) { setCoordinates(Arrays.asList(longtitude, latitude)); } public String getType() { return type; } public void setType(String type) { this.type = type; } @JsonProperty(value = "coordinates") public void setCoordinates(List<Double> coordinates) {
Double[] doubleDoublePair = GeoConverter.convertMetersToLatLon(coordinates.get(0), coordinates.get(1));
ofelbaum/spb-transport-app
src/main/java/com/emal/android/transport/spb/task/SyncVehiclePositionTask.java
// Path: src/main/java/com/emal/android/transport/spb/VehicleSyncAdapter.java // public interface VehicleSyncAdapter { // void beforeSync(boolean clearBeforeUpdate); // // void afterSync(Bitmap result); // // void afterSync(boolean result); // // int getScaledWidth(); // // int getScaledHeight(); // // String getBBox(); // // void setBBox(); // // void clearOverlay(); // // Marker addMarker(MarkerOptions title); // // PortalClient getPortalClient(); // // void hideError(); // // void showError(); // // void moveCamera(CameraUpdate cameraUpdate); // // float getScaleFactor(); // // void setIconSize(int iconSize); // // int getSyncTime(); // // void setSyncTime(int syncTime); // // void updateMarkers(Route route, List<Marker[]> markers); // // void removeMarkers(Route key); // // int getScreenHeight(); // // int getScreenWidth(); // } // // Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // // Path: src/main/java/com/emal/android/transport/spb/utils/Constants.java // public final class Constants { // public static final String URL_TEMPLATE = "http://transport.orgp.spb.ru/cgi-bin/mapserv?TRANSPARENT=TRUE&FORMAT=image%2Fpng&MAP=vehicle_typed.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913&_OLSALT=0.1508798657450825"; // public static final String URL_PARAMS = "&LAYERS=%s&BBOX=%s&WIDTH=%d&HEIGHT=%d"; // public static final String SHOW_BUS_FLAG = "SHOW_BUS_FLAG"; // public static final String SHOW_TROLLEY_FLAG = "SHOW_TROLLEY_FLAG"; // public static final String SHOW_TRAM_FLAG = "SHOW_TRAM_FLAG"; // public static final String SHOW_SHIP_FLAG = "SHOW_SHIP_FLAG"; // public static final String SAT_VIEW_FLAG = "SAT_VIEW_FLAG"; // public static final String SHOW_TRAFFIC_FLAG = "SHOW_TRAFFIC_FLAG"; // public static final String MAP_PROVIDER_TYPE_FLAG = "MAP_PROVIDER_TYPE_FLAG"; // public static final String SYNC_TIME_FLAG = "SYNC_TIME_FLAG"; // public static final String ZOOM_FLAG = "ZOOM_FLAG"; // public static final String HOME_LOC_LONG_FLAG = "HOME_LOCATION_LONG_FLAG"; // public static final String HOME_LOC_LAT_FLAG = "HOME_LOCATION_LAT_FLAG"; // public static final String LAST_LOC_LONG_FLAG = "LAST_LOC_LONG_FLAG"; // public static final String LAST_LOC_LAT_FLAG = "LAST_LOC_LAT_FLAG"; // public static final String APP_SHARED_SOURCE = "SPB_TRANSPORT_APP"; // public static final int DEFAULT_ZOOM_LEVEL = 15; // public static final int MS_IN_SEC = 1000; // public static final int DEFAULT_SYNC_MS = 10000; // public static final String ROUTES_TO_TRACK = "ROUTES_TO_TRACK"; // public static final String THEME_FLAG = "THEME_FLAG"; // public static final String ICON_SIZE_FLAG = "ICON_SIZE_FLAG"; // public static final int DEFAULT_ICON_SIZE = 5; // }
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import com.emal.android.transport.spb.VehicleSyncAdapter; import com.emal.android.transport.spb.VehicleType; import com.emal.android.transport.spb.utils.Constants; import java.io.InputStream; import java.util.Iterator; import java.util.Set;
package com.emal.android.transport.spb.task; /** * User: alexey.emelyanenko@gmail.com * Date: 5/18/13 5:11 AM */ public class SyncVehiclePositionTask extends AsyncTask<Object, Void, Bitmap> { private static final String TAG = SyncVehiclePositionTask.class.getName();
// Path: src/main/java/com/emal/android/transport/spb/VehicleSyncAdapter.java // public interface VehicleSyncAdapter { // void beforeSync(boolean clearBeforeUpdate); // // void afterSync(Bitmap result); // // void afterSync(boolean result); // // int getScaledWidth(); // // int getScaledHeight(); // // String getBBox(); // // void setBBox(); // // void clearOverlay(); // // Marker addMarker(MarkerOptions title); // // PortalClient getPortalClient(); // // void hideError(); // // void showError(); // // void moveCamera(CameraUpdate cameraUpdate); // // float getScaleFactor(); // // void setIconSize(int iconSize); // // int getSyncTime(); // // void setSyncTime(int syncTime); // // void updateMarkers(Route route, List<Marker[]> markers); // // void removeMarkers(Route key); // // int getScreenHeight(); // // int getScreenWidth(); // } // // Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // // Path: src/main/java/com/emal/android/transport/spb/utils/Constants.java // public final class Constants { // public static final String URL_TEMPLATE = "http://transport.orgp.spb.ru/cgi-bin/mapserv?TRANSPARENT=TRUE&FORMAT=image%2Fpng&MAP=vehicle_typed.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913&_OLSALT=0.1508798657450825"; // public static final String URL_PARAMS = "&LAYERS=%s&BBOX=%s&WIDTH=%d&HEIGHT=%d"; // public static final String SHOW_BUS_FLAG = "SHOW_BUS_FLAG"; // public static final String SHOW_TROLLEY_FLAG = "SHOW_TROLLEY_FLAG"; // public static final String SHOW_TRAM_FLAG = "SHOW_TRAM_FLAG"; // public static final String SHOW_SHIP_FLAG = "SHOW_SHIP_FLAG"; // public static final String SAT_VIEW_FLAG = "SAT_VIEW_FLAG"; // public static final String SHOW_TRAFFIC_FLAG = "SHOW_TRAFFIC_FLAG"; // public static final String MAP_PROVIDER_TYPE_FLAG = "MAP_PROVIDER_TYPE_FLAG"; // public static final String SYNC_TIME_FLAG = "SYNC_TIME_FLAG"; // public static final String ZOOM_FLAG = "ZOOM_FLAG"; // public static final String HOME_LOC_LONG_FLAG = "HOME_LOCATION_LONG_FLAG"; // public static final String HOME_LOC_LAT_FLAG = "HOME_LOCATION_LAT_FLAG"; // public static final String LAST_LOC_LONG_FLAG = "LAST_LOC_LONG_FLAG"; // public static final String LAST_LOC_LAT_FLAG = "LAST_LOC_LAT_FLAG"; // public static final String APP_SHARED_SOURCE = "SPB_TRANSPORT_APP"; // public static final int DEFAULT_ZOOM_LEVEL = 15; // public static final int MS_IN_SEC = 1000; // public static final int DEFAULT_SYNC_MS = 10000; // public static final String ROUTES_TO_TRACK = "ROUTES_TO_TRACK"; // public static final String THEME_FLAG = "THEME_FLAG"; // public static final String ICON_SIZE_FLAG = "ICON_SIZE_FLAG"; // public static final int DEFAULT_ICON_SIZE = 5; // } // Path: src/main/java/com/emal/android/transport/spb/task/SyncVehiclePositionTask.java import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import com.emal.android.transport.spb.VehicleSyncAdapter; import com.emal.android.transport.spb.VehicleType; import com.emal.android.transport.spb.utils.Constants; import java.io.InputStream; import java.util.Iterator; import java.util.Set; package com.emal.android.transport.spb.task; /** * User: alexey.emelyanenko@gmail.com * Date: 5/18/13 5:11 AM */ public class SyncVehiclePositionTask extends AsyncTask<Object, Void, Bitmap> { private static final String TAG = SyncVehiclePositionTask.class.getName();
private VehicleSyncAdapter vehicleSyncAdapter;
ofelbaum/spb-transport-app
src/main/java/com/emal/android/transport/spb/task/SyncVehiclePositionTask.java
// Path: src/main/java/com/emal/android/transport/spb/VehicleSyncAdapter.java // public interface VehicleSyncAdapter { // void beforeSync(boolean clearBeforeUpdate); // // void afterSync(Bitmap result); // // void afterSync(boolean result); // // int getScaledWidth(); // // int getScaledHeight(); // // String getBBox(); // // void setBBox(); // // void clearOverlay(); // // Marker addMarker(MarkerOptions title); // // PortalClient getPortalClient(); // // void hideError(); // // void showError(); // // void moveCamera(CameraUpdate cameraUpdate); // // float getScaleFactor(); // // void setIconSize(int iconSize); // // int getSyncTime(); // // void setSyncTime(int syncTime); // // void updateMarkers(Route route, List<Marker[]> markers); // // void removeMarkers(Route key); // // int getScreenHeight(); // // int getScreenWidth(); // } // // Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // // Path: src/main/java/com/emal/android/transport/spb/utils/Constants.java // public final class Constants { // public static final String URL_TEMPLATE = "http://transport.orgp.spb.ru/cgi-bin/mapserv?TRANSPARENT=TRUE&FORMAT=image%2Fpng&MAP=vehicle_typed.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913&_OLSALT=0.1508798657450825"; // public static final String URL_PARAMS = "&LAYERS=%s&BBOX=%s&WIDTH=%d&HEIGHT=%d"; // public static final String SHOW_BUS_FLAG = "SHOW_BUS_FLAG"; // public static final String SHOW_TROLLEY_FLAG = "SHOW_TROLLEY_FLAG"; // public static final String SHOW_TRAM_FLAG = "SHOW_TRAM_FLAG"; // public static final String SHOW_SHIP_FLAG = "SHOW_SHIP_FLAG"; // public static final String SAT_VIEW_FLAG = "SAT_VIEW_FLAG"; // public static final String SHOW_TRAFFIC_FLAG = "SHOW_TRAFFIC_FLAG"; // public static final String MAP_PROVIDER_TYPE_FLAG = "MAP_PROVIDER_TYPE_FLAG"; // public static final String SYNC_TIME_FLAG = "SYNC_TIME_FLAG"; // public static final String ZOOM_FLAG = "ZOOM_FLAG"; // public static final String HOME_LOC_LONG_FLAG = "HOME_LOCATION_LONG_FLAG"; // public static final String HOME_LOC_LAT_FLAG = "HOME_LOCATION_LAT_FLAG"; // public static final String LAST_LOC_LONG_FLAG = "LAST_LOC_LONG_FLAG"; // public static final String LAST_LOC_LAT_FLAG = "LAST_LOC_LAT_FLAG"; // public static final String APP_SHARED_SOURCE = "SPB_TRANSPORT_APP"; // public static final int DEFAULT_ZOOM_LEVEL = 15; // public static final int MS_IN_SEC = 1000; // public static final int DEFAULT_SYNC_MS = 10000; // public static final String ROUTES_TO_TRACK = "ROUTES_TO_TRACK"; // public static final String THEME_FLAG = "THEME_FLAG"; // public static final String ICON_SIZE_FLAG = "ICON_SIZE_FLAG"; // public static final int DEFAULT_ICON_SIZE = 5; // }
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import com.emal.android.transport.spb.VehicleSyncAdapter; import com.emal.android.transport.spb.VehicleType; import com.emal.android.transport.spb.utils.Constants; import java.io.InputStream; import java.util.Iterator; import java.util.Set;
package com.emal.android.transport.spb.task; /** * User: alexey.emelyanenko@gmail.com * Date: 5/18/13 5:11 AM */ public class SyncVehiclePositionTask extends AsyncTask<Object, Void, Bitmap> { private static final String TAG = SyncVehiclePositionTask.class.getName(); private VehicleSyncAdapter vehicleSyncAdapter; private String vehiclesStr;
// Path: src/main/java/com/emal/android/transport/spb/VehicleSyncAdapter.java // public interface VehicleSyncAdapter { // void beforeSync(boolean clearBeforeUpdate); // // void afterSync(Bitmap result); // // void afterSync(boolean result); // // int getScaledWidth(); // // int getScaledHeight(); // // String getBBox(); // // void setBBox(); // // void clearOverlay(); // // Marker addMarker(MarkerOptions title); // // PortalClient getPortalClient(); // // void hideError(); // // void showError(); // // void moveCamera(CameraUpdate cameraUpdate); // // float getScaleFactor(); // // void setIconSize(int iconSize); // // int getSyncTime(); // // void setSyncTime(int syncTime); // // void updateMarkers(Route route, List<Marker[]> markers); // // void removeMarkers(Route key); // // int getScreenHeight(); // // int getScreenWidth(); // } // // Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // // Path: src/main/java/com/emal/android/transport/spb/utils/Constants.java // public final class Constants { // public static final String URL_TEMPLATE = "http://transport.orgp.spb.ru/cgi-bin/mapserv?TRANSPARENT=TRUE&FORMAT=image%2Fpng&MAP=vehicle_typed.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913&_OLSALT=0.1508798657450825"; // public static final String URL_PARAMS = "&LAYERS=%s&BBOX=%s&WIDTH=%d&HEIGHT=%d"; // public static final String SHOW_BUS_FLAG = "SHOW_BUS_FLAG"; // public static final String SHOW_TROLLEY_FLAG = "SHOW_TROLLEY_FLAG"; // public static final String SHOW_TRAM_FLAG = "SHOW_TRAM_FLAG"; // public static final String SHOW_SHIP_FLAG = "SHOW_SHIP_FLAG"; // public static final String SAT_VIEW_FLAG = "SAT_VIEW_FLAG"; // public static final String SHOW_TRAFFIC_FLAG = "SHOW_TRAFFIC_FLAG"; // public static final String MAP_PROVIDER_TYPE_FLAG = "MAP_PROVIDER_TYPE_FLAG"; // public static final String SYNC_TIME_FLAG = "SYNC_TIME_FLAG"; // public static final String ZOOM_FLAG = "ZOOM_FLAG"; // public static final String HOME_LOC_LONG_FLAG = "HOME_LOCATION_LONG_FLAG"; // public static final String HOME_LOC_LAT_FLAG = "HOME_LOCATION_LAT_FLAG"; // public static final String LAST_LOC_LONG_FLAG = "LAST_LOC_LONG_FLAG"; // public static final String LAST_LOC_LAT_FLAG = "LAST_LOC_LAT_FLAG"; // public static final String APP_SHARED_SOURCE = "SPB_TRANSPORT_APP"; // public static final int DEFAULT_ZOOM_LEVEL = 15; // public static final int MS_IN_SEC = 1000; // public static final int DEFAULT_SYNC_MS = 10000; // public static final String ROUTES_TO_TRACK = "ROUTES_TO_TRACK"; // public static final String THEME_FLAG = "THEME_FLAG"; // public static final String ICON_SIZE_FLAG = "ICON_SIZE_FLAG"; // public static final int DEFAULT_ICON_SIZE = 5; // } // Path: src/main/java/com/emal/android/transport/spb/task/SyncVehiclePositionTask.java import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import com.emal.android.transport.spb.VehicleSyncAdapter; import com.emal.android.transport.spb.VehicleType; import com.emal.android.transport.spb.utils.Constants; import java.io.InputStream; import java.util.Iterator; import java.util.Set; package com.emal.android.transport.spb.task; /** * User: alexey.emelyanenko@gmail.com * Date: 5/18/13 5:11 AM */ public class SyncVehiclePositionTask extends AsyncTask<Object, Void, Bitmap> { private static final String TAG = SyncVehiclePositionTask.class.getName(); private VehicleSyncAdapter vehicleSyncAdapter; private String vehiclesStr;
private Set<VehicleType> vehicleTypes;
ofelbaum/spb-transport-app
src/main/java/com/emal/android/transport/spb/task/SyncVehiclePositionTask.java
// Path: src/main/java/com/emal/android/transport/spb/VehicleSyncAdapter.java // public interface VehicleSyncAdapter { // void beforeSync(boolean clearBeforeUpdate); // // void afterSync(Bitmap result); // // void afterSync(boolean result); // // int getScaledWidth(); // // int getScaledHeight(); // // String getBBox(); // // void setBBox(); // // void clearOverlay(); // // Marker addMarker(MarkerOptions title); // // PortalClient getPortalClient(); // // void hideError(); // // void showError(); // // void moveCamera(CameraUpdate cameraUpdate); // // float getScaleFactor(); // // void setIconSize(int iconSize); // // int getSyncTime(); // // void setSyncTime(int syncTime); // // void updateMarkers(Route route, List<Marker[]> markers); // // void removeMarkers(Route key); // // int getScreenHeight(); // // int getScreenWidth(); // } // // Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // // Path: src/main/java/com/emal/android/transport/spb/utils/Constants.java // public final class Constants { // public static final String URL_TEMPLATE = "http://transport.orgp.spb.ru/cgi-bin/mapserv?TRANSPARENT=TRUE&FORMAT=image%2Fpng&MAP=vehicle_typed.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913&_OLSALT=0.1508798657450825"; // public static final String URL_PARAMS = "&LAYERS=%s&BBOX=%s&WIDTH=%d&HEIGHT=%d"; // public static final String SHOW_BUS_FLAG = "SHOW_BUS_FLAG"; // public static final String SHOW_TROLLEY_FLAG = "SHOW_TROLLEY_FLAG"; // public static final String SHOW_TRAM_FLAG = "SHOW_TRAM_FLAG"; // public static final String SHOW_SHIP_FLAG = "SHOW_SHIP_FLAG"; // public static final String SAT_VIEW_FLAG = "SAT_VIEW_FLAG"; // public static final String SHOW_TRAFFIC_FLAG = "SHOW_TRAFFIC_FLAG"; // public static final String MAP_PROVIDER_TYPE_FLAG = "MAP_PROVIDER_TYPE_FLAG"; // public static final String SYNC_TIME_FLAG = "SYNC_TIME_FLAG"; // public static final String ZOOM_FLAG = "ZOOM_FLAG"; // public static final String HOME_LOC_LONG_FLAG = "HOME_LOCATION_LONG_FLAG"; // public static final String HOME_LOC_LAT_FLAG = "HOME_LOCATION_LAT_FLAG"; // public static final String LAST_LOC_LONG_FLAG = "LAST_LOC_LONG_FLAG"; // public static final String LAST_LOC_LAT_FLAG = "LAST_LOC_LAT_FLAG"; // public static final String APP_SHARED_SOURCE = "SPB_TRANSPORT_APP"; // public static final int DEFAULT_ZOOM_LEVEL = 15; // public static final int MS_IN_SEC = 1000; // public static final int DEFAULT_SYNC_MS = 10000; // public static final String ROUTES_TO_TRACK = "ROUTES_TO_TRACK"; // public static final String THEME_FLAG = "THEME_FLAG"; // public static final String ICON_SIZE_FLAG = "ICON_SIZE_FLAG"; // public static final int DEFAULT_ICON_SIZE = 5; // }
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import com.emal.android.transport.spb.VehicleSyncAdapter; import com.emal.android.transport.spb.VehicleType; import com.emal.android.transport.spb.utils.Constants; import java.io.InputStream; import java.util.Iterator; import java.util.Set;
this.vehicleSyncAdapter = vehicleSyncAdapter; this.vehicleTypes = vehicleTypes; } @Override protected void onPreExecute() { vehicleSyncAdapter.beforeSync(false); } @Override protected Bitmap doInBackground(Object... params) { long start = System.currentTimeMillis(); Log.d(TAG, "Download " + vehiclesStr + " START for " + Thread.currentThread().getName()); try { String bbox = vehicleSyncAdapter.getBBox(); StringBuffer vs = new StringBuffer(); Iterator<VehicleType> iterator = vehicleTypes.iterator(); while (iterator.hasNext()) { VehicleType next = iterator.next(); vs.append(next.getCode()); if (iterator.hasNext()) { vs.append(","); } } vehiclesStr = vs.toString(); Object[] paramss = new Object[]{vehiclesStr, bbox, vehicleSyncAdapter.getScaledWidth(), vehicleSyncAdapter.getScaledHeight()};
// Path: src/main/java/com/emal/android/transport/spb/VehicleSyncAdapter.java // public interface VehicleSyncAdapter { // void beforeSync(boolean clearBeforeUpdate); // // void afterSync(Bitmap result); // // void afterSync(boolean result); // // int getScaledWidth(); // // int getScaledHeight(); // // String getBBox(); // // void setBBox(); // // void clearOverlay(); // // Marker addMarker(MarkerOptions title); // // PortalClient getPortalClient(); // // void hideError(); // // void showError(); // // void moveCamera(CameraUpdate cameraUpdate); // // float getScaleFactor(); // // void setIconSize(int iconSize); // // int getSyncTime(); // // void setSyncTime(int syncTime); // // void updateMarkers(Route route, List<Marker[]> markers); // // void removeMarkers(Route key); // // int getScreenHeight(); // // int getScreenWidth(); // } // // Path: src/main/java/com/emal/android/transport/spb/VehicleType.java // public enum VehicleType { // BUS("vehicle_bus", "0", "A", false, Color.BLUE), // TROLLEY("vehicle_trolley", "1", "Ш", true, Color.GREEN), // TRAM("vehicle_tram", "2", "T", false, Color.RED), // SHIP("vehicle_ship", "46", "S", false, Color.YELLOW); // // private String code; // private String id; // private String letter; // private boolean upsideDown; // private int color; // // private VehicleType(String code, String id, String letter, boolean upsideDown, int color) { // this.code = code; // this.id = id; // this.letter = letter; // this.color = color; // this.upsideDown = upsideDown; // } // // public String getCode() { // return code; // } // // public String getId() { // return id; // } // // public String getLetter() { // return letter; // } // // public int getColor() { // return color; // } // // public boolean isUpsideDown() { // return upsideDown; // } // // public static VehicleType getType(String value) { // if ("bus".equals(value)) { // return BUS; // } // if ("tram".equals(value)) { // return TRAM; // } // if ("trolley".equals(value)) { // return TROLLEY; // } // if ("ship".equals(value)) { // return SHIP; // } // throw new IllegalStateException("Wrong vehicle type"); // } // } // // Path: src/main/java/com/emal/android/transport/spb/utils/Constants.java // public final class Constants { // public static final String URL_TEMPLATE = "http://transport.orgp.spb.ru/cgi-bin/mapserv?TRANSPARENT=TRUE&FORMAT=image%2Fpng&MAP=vehicle_typed.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913&_OLSALT=0.1508798657450825"; // public static final String URL_PARAMS = "&LAYERS=%s&BBOX=%s&WIDTH=%d&HEIGHT=%d"; // public static final String SHOW_BUS_FLAG = "SHOW_BUS_FLAG"; // public static final String SHOW_TROLLEY_FLAG = "SHOW_TROLLEY_FLAG"; // public static final String SHOW_TRAM_FLAG = "SHOW_TRAM_FLAG"; // public static final String SHOW_SHIP_FLAG = "SHOW_SHIP_FLAG"; // public static final String SAT_VIEW_FLAG = "SAT_VIEW_FLAG"; // public static final String SHOW_TRAFFIC_FLAG = "SHOW_TRAFFIC_FLAG"; // public static final String MAP_PROVIDER_TYPE_FLAG = "MAP_PROVIDER_TYPE_FLAG"; // public static final String SYNC_TIME_FLAG = "SYNC_TIME_FLAG"; // public static final String ZOOM_FLAG = "ZOOM_FLAG"; // public static final String HOME_LOC_LONG_FLAG = "HOME_LOCATION_LONG_FLAG"; // public static final String HOME_LOC_LAT_FLAG = "HOME_LOCATION_LAT_FLAG"; // public static final String LAST_LOC_LONG_FLAG = "LAST_LOC_LONG_FLAG"; // public static final String LAST_LOC_LAT_FLAG = "LAST_LOC_LAT_FLAG"; // public static final String APP_SHARED_SOURCE = "SPB_TRANSPORT_APP"; // public static final int DEFAULT_ZOOM_LEVEL = 15; // public static final int MS_IN_SEC = 1000; // public static final int DEFAULT_SYNC_MS = 10000; // public static final String ROUTES_TO_TRACK = "ROUTES_TO_TRACK"; // public static final String THEME_FLAG = "THEME_FLAG"; // public static final String ICON_SIZE_FLAG = "ICON_SIZE_FLAG"; // public static final int DEFAULT_ICON_SIZE = 5; // } // Path: src/main/java/com/emal/android/transport/spb/task/SyncVehiclePositionTask.java import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import com.emal.android.transport.spb.VehicleSyncAdapter; import com.emal.android.transport.spb.VehicleType; import com.emal.android.transport.spb.utils.Constants; import java.io.InputStream; import java.util.Iterator; import java.util.Set; this.vehicleSyncAdapter = vehicleSyncAdapter; this.vehicleTypes = vehicleTypes; } @Override protected void onPreExecute() { vehicleSyncAdapter.beforeSync(false); } @Override protected Bitmap doInBackground(Object... params) { long start = System.currentTimeMillis(); Log.d(TAG, "Download " + vehiclesStr + " START for " + Thread.currentThread().getName()); try { String bbox = vehicleSyncAdapter.getBBox(); StringBuffer vs = new StringBuffer(); Iterator<VehicleType> iterator = vehicleTypes.iterator(); while (iterator.hasNext()) { VehicleType next = iterator.next(); vs.append(next.getCode()); if (iterator.hasNext()) { vs.append(","); } } vehiclesStr = vs.toString(); Object[] paramss = new Object[]{vehiclesStr, bbox, vehicleSyncAdapter.getScaledWidth(), vehicleSyncAdapter.getScaledHeight()};
String url = Constants.URL_TEMPLATE + String.format(Constants.URL_PARAMS, paramss);
martino2k6/StoreBox
storebox-lib/src/main/java/net/orange_box/storebox/annotations/type/FilePreferences.java
// Path: storebox-lib/src/main/java/net/orange_box/storebox/enums/PreferencesMode.java // public enum PreferencesMode { // // /** // * Default. // * // * @see android.content.Context#MODE_PRIVATE // */ // MODE_PRIVATE(Context.MODE_PRIVATE), // // /** // * @see android.content.Context#MODE_MULTI_PROCESS // */ // MODE_MULTI_PROCESS(Context.MODE_MULTI_PROCESS), // // /** // * @see android.content.Context#MODE_WORLD_READABLE // */ // @Deprecated // MODE_WORLD_READABLE(Context.MODE_WORLD_READABLE), // // /** // * @see android.content.Context#MODE_WORLD_WRITEABLE // */ // @Deprecated // MODE_WORLD_WRITEABLE(Context.MODE_WORLD_WRITEABLE); // // private final int value; // // private PreferencesMode(int value) { // this.value = value; // } // // public int value() { // return value; // } // }
import net.orange_box.storebox.enums.PreferencesMode; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
/* * Copyright 2015 Martin Bella * * 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.orange_box.storebox.annotations.type; /** * Annotation which should be used at interface-level to define that the * preferences should be opened from a file name. * <p> * When this annotation is used a file name needs to be specified using * {@link #value()}. * * @see net.orange_box.storebox.enums.PreferencesType#FILE * @see android.content.Context#getSharedPreferences(String, int) */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface FilePreferences { String value();
// Path: storebox-lib/src/main/java/net/orange_box/storebox/enums/PreferencesMode.java // public enum PreferencesMode { // // /** // * Default. // * // * @see android.content.Context#MODE_PRIVATE // */ // MODE_PRIVATE(Context.MODE_PRIVATE), // // /** // * @see android.content.Context#MODE_MULTI_PROCESS // */ // MODE_MULTI_PROCESS(Context.MODE_MULTI_PROCESS), // // /** // * @see android.content.Context#MODE_WORLD_READABLE // */ // @Deprecated // MODE_WORLD_READABLE(Context.MODE_WORLD_READABLE), // // /** // * @see android.content.Context#MODE_WORLD_WRITEABLE // */ // @Deprecated // MODE_WORLD_WRITEABLE(Context.MODE_WORLD_WRITEABLE); // // private final int value; // // private PreferencesMode(int value) { // this.value = value; // } // // public int value() { // return value; // } // } // Path: storebox-lib/src/main/java/net/orange_box/storebox/annotations/type/FilePreferences.java import net.orange_box.storebox.enums.PreferencesMode; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * Copyright 2015 Martin Bella * * 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.orange_box.storebox.annotations.type; /** * Annotation which should be used at interface-level to define that the * preferences should be opened from a file name. * <p> * When this annotation is used a file name needs to be specified using * {@link #value()}. * * @see net.orange_box.storebox.enums.PreferencesType#FILE * @see android.content.Context#getSharedPreferences(String, int) */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface FilePreferences { String value();
PreferencesMode mode() default PreferencesMode.MODE_PRIVATE;
martino2k6/StoreBox
storebox-harness/src/androidTest/java/net/orange_box/storebox/harness/ChainingMethodsTestCase.java
// Path: storebox-lib/src/main/java/net/orange_box/storebox/StoreBox.java // public final class StoreBox { // // /** // * @param context - the context under which the // * {@link android.content.SharedPreferences} should be opened // * @param cls - the interface class which should be instantiated // * @return new instance of class {@code cls} using {@code context} // */ // public static <T> T create(Context context, Class<T> cls) { // return new Builder<>(context, cls).build(); // } // // private StoreBox() {} // // /** // * Can be used to provide a customised instance of the supplied interface, // * by setting custom options through builder methods. // * // * @param <T> // */ // public static final class Builder<T> { // // private final Context context; // private final Class<T> cls; // // private PreferencesType preferencesType = PreferencesType.DEFAULT_SHARED; // private String preferencesName = ""; // private PreferencesMode preferencesMode = PreferencesMode.MODE_PRIVATE; // private SaveMode saveMode = SaveMode.APPLY; // // public Builder(Context context, Class<T> cls) { // this.context = context; // this.cls = cls; // // readAnnotations(); // } // // public Builder preferencesType(PreferencesType value) { // preferencesType = value; // return this; // } // // public Builder preferencesType( // PreferencesType value, String name) { // // preferencesType = value; // preferencesName = name; // return this; // } // // public Builder preferencesMode(PreferencesMode value) { // preferencesMode = value; // return this; // } // // public Builder saveMode(SaveMode value) { // saveMode = value; // return this; // } // // /** // * @return new instance of class {@code cls} using {@code context} // */ // @SuppressWarnings("unchecked") // public T build() { // validate(); // // return (T) Proxy.newProxyInstance( // cls.getClassLoader(), // new Class[]{cls}, // new StoreBoxInvocationHandler( // context, // preferencesType, // preferencesName, // preferencesMode, // saveMode)); // } // // private void readAnnotations() { // // type/mode option // if (cls.isAnnotationPresent(DefaultSharedPreferences.class)) { // preferencesType(PreferencesType.DEFAULT_SHARED); // } else if (cls.isAnnotationPresent(ActivityPreferences.class)) { // final ActivityPreferences annotation = // cls.getAnnotation(ActivityPreferences.class); // // preferencesType(PreferencesType.ACTIVITY); // preferencesMode(annotation.mode()); // } else if (cls.isAnnotationPresent(FilePreferences.class)) { // final FilePreferences annotation = // cls.getAnnotation(FilePreferences.class); // // preferencesType(PreferencesType.FILE, annotation.value()); // preferencesMode(annotation.mode()); // } // // save option // if (cls.isAnnotationPresent(SaveOption.class)) { // saveMode(cls.getAnnotation(SaveOption.class).value()); // } // } // // private void validate() { // if (context == null) { // throw new IllegalArgumentException( // "Context cannot be null"); // } // if (cls == null) { // throw new IllegalArgumentException( // "Class cannot be null"); // } else if (!cls.isInterface()) { // throw new IllegalArgumentException( // "Class needs to be an interface"); // } // // if (preferencesType == PreferencesType.ACTIVITY) { // if (!(context instanceof Activity)) { // throw new IllegalArgumentException(String.format( // Locale.ENGLISH, // "Cannot use %1$s without an Activity context", // PreferencesType.ACTIVITY.name())); // } // } else if (preferencesType == PreferencesType.FILE) { // if (TextUtils.isEmpty(preferencesName)) { // throw new IllegalArgumentException(String.format( // Locale.ENGLISH, // "Cannot use %1$s with an empty file name", // PreferencesType.FILE.name())); // } // } // } // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/interfaces/ChainingMethodsInterface.java // public interface ChainingMethodsInterface { // // @KeyByString("first") // SharedPreferences.Editor setFirstValue(String value); // // @KeyByString("second") // ChainingMethodsInterface setSecondValue(String value); // // @KeyByString("first") // @RemoveMethod // SharedPreferences.Editor removeFirstValue(); // // @KeyByString("second") // @RemoveMethod // ChainingMethodsInterface removeSecondValue(); // }
import android.annotation.SuppressLint; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.SmallTest; import net.orange_box.storebox.StoreBox; import net.orange_box.storebox.harness.interfaces.ChainingMethodsInterface;
/* * Copyright 2015 Martin Bella * * 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.orange_box.storebox.harness; public class ChainingMethodsTestCase extends InstrumentationTestCase { private ChainingMethodsInterface uut; private SharedPreferences prefs; @Override protected void setUp() throws Exception { super.setUp();
// Path: storebox-lib/src/main/java/net/orange_box/storebox/StoreBox.java // public final class StoreBox { // // /** // * @param context - the context under which the // * {@link android.content.SharedPreferences} should be opened // * @param cls - the interface class which should be instantiated // * @return new instance of class {@code cls} using {@code context} // */ // public static <T> T create(Context context, Class<T> cls) { // return new Builder<>(context, cls).build(); // } // // private StoreBox() {} // // /** // * Can be used to provide a customised instance of the supplied interface, // * by setting custom options through builder methods. // * // * @param <T> // */ // public static final class Builder<T> { // // private final Context context; // private final Class<T> cls; // // private PreferencesType preferencesType = PreferencesType.DEFAULT_SHARED; // private String preferencesName = ""; // private PreferencesMode preferencesMode = PreferencesMode.MODE_PRIVATE; // private SaveMode saveMode = SaveMode.APPLY; // // public Builder(Context context, Class<T> cls) { // this.context = context; // this.cls = cls; // // readAnnotations(); // } // // public Builder preferencesType(PreferencesType value) { // preferencesType = value; // return this; // } // // public Builder preferencesType( // PreferencesType value, String name) { // // preferencesType = value; // preferencesName = name; // return this; // } // // public Builder preferencesMode(PreferencesMode value) { // preferencesMode = value; // return this; // } // // public Builder saveMode(SaveMode value) { // saveMode = value; // return this; // } // // /** // * @return new instance of class {@code cls} using {@code context} // */ // @SuppressWarnings("unchecked") // public T build() { // validate(); // // return (T) Proxy.newProxyInstance( // cls.getClassLoader(), // new Class[]{cls}, // new StoreBoxInvocationHandler( // context, // preferencesType, // preferencesName, // preferencesMode, // saveMode)); // } // // private void readAnnotations() { // // type/mode option // if (cls.isAnnotationPresent(DefaultSharedPreferences.class)) { // preferencesType(PreferencesType.DEFAULT_SHARED); // } else if (cls.isAnnotationPresent(ActivityPreferences.class)) { // final ActivityPreferences annotation = // cls.getAnnotation(ActivityPreferences.class); // // preferencesType(PreferencesType.ACTIVITY); // preferencesMode(annotation.mode()); // } else if (cls.isAnnotationPresent(FilePreferences.class)) { // final FilePreferences annotation = // cls.getAnnotation(FilePreferences.class); // // preferencesType(PreferencesType.FILE, annotation.value()); // preferencesMode(annotation.mode()); // } // // save option // if (cls.isAnnotationPresent(SaveOption.class)) { // saveMode(cls.getAnnotation(SaveOption.class).value()); // } // } // // private void validate() { // if (context == null) { // throw new IllegalArgumentException( // "Context cannot be null"); // } // if (cls == null) { // throw new IllegalArgumentException( // "Class cannot be null"); // } else if (!cls.isInterface()) { // throw new IllegalArgumentException( // "Class needs to be an interface"); // } // // if (preferencesType == PreferencesType.ACTIVITY) { // if (!(context instanceof Activity)) { // throw new IllegalArgumentException(String.format( // Locale.ENGLISH, // "Cannot use %1$s without an Activity context", // PreferencesType.ACTIVITY.name())); // } // } else if (preferencesType == PreferencesType.FILE) { // if (TextUtils.isEmpty(preferencesName)) { // throw new IllegalArgumentException(String.format( // Locale.ENGLISH, // "Cannot use %1$s with an empty file name", // PreferencesType.FILE.name())); // } // } // } // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/interfaces/ChainingMethodsInterface.java // public interface ChainingMethodsInterface { // // @KeyByString("first") // SharedPreferences.Editor setFirstValue(String value); // // @KeyByString("second") // ChainingMethodsInterface setSecondValue(String value); // // @KeyByString("first") // @RemoveMethod // SharedPreferences.Editor removeFirstValue(); // // @KeyByString("second") // @RemoveMethod // ChainingMethodsInterface removeSecondValue(); // } // Path: storebox-harness/src/androidTest/java/net/orange_box/storebox/harness/ChainingMethodsTestCase.java import android.annotation.SuppressLint; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.SmallTest; import net.orange_box.storebox.StoreBox; import net.orange_box.storebox.harness.interfaces.ChainingMethodsInterface; /* * Copyright 2015 Martin Bella * * 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.orange_box.storebox.harness; public class ChainingMethodsTestCase extends InstrumentationTestCase { private ChainingMethodsInterface uut; private SharedPreferences prefs; @Override protected void setUp() throws Exception { super.setUp();
uut = StoreBox.create(
martino2k6/StoreBox
storebox-harness/src/main/java/net/orange_box/storebox/harness/interfaces/types/CustomTypesInterface.java
// Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomClass.java // public class CustomClass { // // private int hashCode; // // private final String one; // private final String two; // // public CustomClass() { // this("", ""); // } // // public CustomClass(String one, String two) { // this.one = one; // this.two = two; // } // // public String getOne() { // return one; // } // // public String getTwo() { // return two; // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof CustomClass)) { // return false; // } // // final CustomClass other = (CustomClass) o; // return (one.equals(other.one) && two.equals(other.two)); // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = Arrays.hashCode(new String[] {one, two}); // } // // return hashCode; // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomEnum.java // public enum CustomEnum { // // ONE, // TWO // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassListTypeAdapter.java // public class CustomClassListTypeAdapter extends // BaseStringTypeAdapter<List<CustomClass>> { // // private static final Gson GSON = new Gson(); // // @Nullable // @Override // public String adaptForPreferences(@Nullable List<CustomClass> value) { // return GSON.toJson(value); // } // // @Nullable // @Override // public List<CustomClass> adaptFromPreferences(@Nullable String value) { // return GSON.fromJson(value, new TypeToken<List<CustomClass>>(){}.getType()); // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassTypeAdapter.java // public class CustomClassTypeAdapter extends BaseStringTypeAdapter<CustomClass> { // // @Nullable // @Override // public String adaptForPreferences(@Nullable CustomClass value) { // if (value == null) { // return null; // } // // return value.getOne() + "|" + value.getTwo(); // } // // @Nullable // @Override // public CustomClass adaptFromPreferences(@Nullable String value) { // if (value == null) { // return null; // } // // if (value.length() == 1) { // return new CustomClass(); // } else { // final String split[] = value.split("\\|"); // // return new CustomClass(split[0], split[1]); // } // } // }
import android.net.Uri; import net.orange_box.storebox.annotations.method.KeyByString; import net.orange_box.storebox.annotations.method.TypeAdapter; import net.orange_box.storebox.harness.types.CustomClass; import net.orange_box.storebox.harness.types.CustomEnum; import net.orange_box.storebox.harness.types.adapters.CustomClassListTypeAdapter; import net.orange_box.storebox.harness.types.adapters.CustomClassTypeAdapter; import java.util.Date; import java.util.List;
/* * Copyright 2015 Martin Bella * * 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.orange_box.storebox.harness.interfaces.types; public interface CustomTypesInterface { @KeyByString("key_custom_enum")
// Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomClass.java // public class CustomClass { // // private int hashCode; // // private final String one; // private final String two; // // public CustomClass() { // this("", ""); // } // // public CustomClass(String one, String two) { // this.one = one; // this.two = two; // } // // public String getOne() { // return one; // } // // public String getTwo() { // return two; // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof CustomClass)) { // return false; // } // // final CustomClass other = (CustomClass) o; // return (one.equals(other.one) && two.equals(other.two)); // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = Arrays.hashCode(new String[] {one, two}); // } // // return hashCode; // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomEnum.java // public enum CustomEnum { // // ONE, // TWO // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassListTypeAdapter.java // public class CustomClassListTypeAdapter extends // BaseStringTypeAdapter<List<CustomClass>> { // // private static final Gson GSON = new Gson(); // // @Nullable // @Override // public String adaptForPreferences(@Nullable List<CustomClass> value) { // return GSON.toJson(value); // } // // @Nullable // @Override // public List<CustomClass> adaptFromPreferences(@Nullable String value) { // return GSON.fromJson(value, new TypeToken<List<CustomClass>>(){}.getType()); // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassTypeAdapter.java // public class CustomClassTypeAdapter extends BaseStringTypeAdapter<CustomClass> { // // @Nullable // @Override // public String adaptForPreferences(@Nullable CustomClass value) { // if (value == null) { // return null; // } // // return value.getOne() + "|" + value.getTwo(); // } // // @Nullable // @Override // public CustomClass adaptFromPreferences(@Nullable String value) { // if (value == null) { // return null; // } // // if (value.length() == 1) { // return new CustomClass(); // } else { // final String split[] = value.split("\\|"); // // return new CustomClass(split[0], split[1]); // } // } // } // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/interfaces/types/CustomTypesInterface.java import android.net.Uri; import net.orange_box.storebox.annotations.method.KeyByString; import net.orange_box.storebox.annotations.method.TypeAdapter; import net.orange_box.storebox.harness.types.CustomClass; import net.orange_box.storebox.harness.types.CustomEnum; import net.orange_box.storebox.harness.types.adapters.CustomClassListTypeAdapter; import net.orange_box.storebox.harness.types.adapters.CustomClassTypeAdapter; import java.util.Date; import java.util.List; /* * Copyright 2015 Martin Bella * * 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.orange_box.storebox.harness.interfaces.types; public interface CustomTypesInterface { @KeyByString("key_custom_enum")
CustomEnum getCustomEnum();
martino2k6/StoreBox
storebox-harness/src/main/java/net/orange_box/storebox/harness/interfaces/types/CustomTypesInterface.java
// Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomClass.java // public class CustomClass { // // private int hashCode; // // private final String one; // private final String two; // // public CustomClass() { // this("", ""); // } // // public CustomClass(String one, String two) { // this.one = one; // this.two = two; // } // // public String getOne() { // return one; // } // // public String getTwo() { // return two; // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof CustomClass)) { // return false; // } // // final CustomClass other = (CustomClass) o; // return (one.equals(other.one) && two.equals(other.two)); // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = Arrays.hashCode(new String[] {one, two}); // } // // return hashCode; // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomEnum.java // public enum CustomEnum { // // ONE, // TWO // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassListTypeAdapter.java // public class CustomClassListTypeAdapter extends // BaseStringTypeAdapter<List<CustomClass>> { // // private static final Gson GSON = new Gson(); // // @Nullable // @Override // public String adaptForPreferences(@Nullable List<CustomClass> value) { // return GSON.toJson(value); // } // // @Nullable // @Override // public List<CustomClass> adaptFromPreferences(@Nullable String value) { // return GSON.fromJson(value, new TypeToken<List<CustomClass>>(){}.getType()); // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassTypeAdapter.java // public class CustomClassTypeAdapter extends BaseStringTypeAdapter<CustomClass> { // // @Nullable // @Override // public String adaptForPreferences(@Nullable CustomClass value) { // if (value == null) { // return null; // } // // return value.getOne() + "|" + value.getTwo(); // } // // @Nullable // @Override // public CustomClass adaptFromPreferences(@Nullable String value) { // if (value == null) { // return null; // } // // if (value.length() == 1) { // return new CustomClass(); // } else { // final String split[] = value.split("\\|"); // // return new CustomClass(split[0], split[1]); // } // } // }
import android.net.Uri; import net.orange_box.storebox.annotations.method.KeyByString; import net.orange_box.storebox.annotations.method.TypeAdapter; import net.orange_box.storebox.harness.types.CustomClass; import net.orange_box.storebox.harness.types.CustomEnum; import net.orange_box.storebox.harness.types.adapters.CustomClassListTypeAdapter; import net.orange_box.storebox.harness.types.adapters.CustomClassTypeAdapter; import java.util.Date; import java.util.List;
/* * Copyright 2015 Martin Bella * * 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.orange_box.storebox.harness.interfaces.types; public interface CustomTypesInterface { @KeyByString("key_custom_enum") CustomEnum getCustomEnum(); @KeyByString("key_custom_enum") CustomEnum getCustomEnum(CustomEnum defValue); @KeyByString("key_custom_enum") void setCustomEnum(CustomEnum value); @KeyByString("key_date") Date getDate(); @KeyByString("key_date") Date getDate(Date defValue); @KeyByString("key_date") void setDate(Date value); @KeyByString("key_double") double getDouble(); @KeyByString("key_double") double getDouble(double defValue); @KeyByString("key_double") void setDouble(double value); @KeyByString("key_uri") Uri getUri(); @KeyByString("key_uri") Uri getUri(Uri defValue); @KeyByString("key_uri") void setUri(Uri value);
// Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomClass.java // public class CustomClass { // // private int hashCode; // // private final String one; // private final String two; // // public CustomClass() { // this("", ""); // } // // public CustomClass(String one, String two) { // this.one = one; // this.two = two; // } // // public String getOne() { // return one; // } // // public String getTwo() { // return two; // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof CustomClass)) { // return false; // } // // final CustomClass other = (CustomClass) o; // return (one.equals(other.one) && two.equals(other.two)); // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = Arrays.hashCode(new String[] {one, two}); // } // // return hashCode; // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomEnum.java // public enum CustomEnum { // // ONE, // TWO // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassListTypeAdapter.java // public class CustomClassListTypeAdapter extends // BaseStringTypeAdapter<List<CustomClass>> { // // private static final Gson GSON = new Gson(); // // @Nullable // @Override // public String adaptForPreferences(@Nullable List<CustomClass> value) { // return GSON.toJson(value); // } // // @Nullable // @Override // public List<CustomClass> adaptFromPreferences(@Nullable String value) { // return GSON.fromJson(value, new TypeToken<List<CustomClass>>(){}.getType()); // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassTypeAdapter.java // public class CustomClassTypeAdapter extends BaseStringTypeAdapter<CustomClass> { // // @Nullable // @Override // public String adaptForPreferences(@Nullable CustomClass value) { // if (value == null) { // return null; // } // // return value.getOne() + "|" + value.getTwo(); // } // // @Nullable // @Override // public CustomClass adaptFromPreferences(@Nullable String value) { // if (value == null) { // return null; // } // // if (value.length() == 1) { // return new CustomClass(); // } else { // final String split[] = value.split("\\|"); // // return new CustomClass(split[0], split[1]); // } // } // } // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/interfaces/types/CustomTypesInterface.java import android.net.Uri; import net.orange_box.storebox.annotations.method.KeyByString; import net.orange_box.storebox.annotations.method.TypeAdapter; import net.orange_box.storebox.harness.types.CustomClass; import net.orange_box.storebox.harness.types.CustomEnum; import net.orange_box.storebox.harness.types.adapters.CustomClassListTypeAdapter; import net.orange_box.storebox.harness.types.adapters.CustomClassTypeAdapter; import java.util.Date; import java.util.List; /* * Copyright 2015 Martin Bella * * 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.orange_box.storebox.harness.interfaces.types; public interface CustomTypesInterface { @KeyByString("key_custom_enum") CustomEnum getCustomEnum(); @KeyByString("key_custom_enum") CustomEnum getCustomEnum(CustomEnum defValue); @KeyByString("key_custom_enum") void setCustomEnum(CustomEnum value); @KeyByString("key_date") Date getDate(); @KeyByString("key_date") Date getDate(Date defValue); @KeyByString("key_date") void setDate(Date value); @KeyByString("key_double") double getDouble(); @KeyByString("key_double") double getDouble(double defValue); @KeyByString("key_double") void setDouble(double value); @KeyByString("key_uri") Uri getUri(); @KeyByString("key_uri") Uri getUri(Uri defValue); @KeyByString("key_uri") void setUri(Uri value);
@TypeAdapter(CustomClassTypeAdapter.class)
martino2k6/StoreBox
storebox-harness/src/main/java/net/orange_box/storebox/harness/interfaces/types/CustomTypesInterface.java
// Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomClass.java // public class CustomClass { // // private int hashCode; // // private final String one; // private final String two; // // public CustomClass() { // this("", ""); // } // // public CustomClass(String one, String two) { // this.one = one; // this.two = two; // } // // public String getOne() { // return one; // } // // public String getTwo() { // return two; // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof CustomClass)) { // return false; // } // // final CustomClass other = (CustomClass) o; // return (one.equals(other.one) && two.equals(other.two)); // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = Arrays.hashCode(new String[] {one, two}); // } // // return hashCode; // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomEnum.java // public enum CustomEnum { // // ONE, // TWO // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassListTypeAdapter.java // public class CustomClassListTypeAdapter extends // BaseStringTypeAdapter<List<CustomClass>> { // // private static final Gson GSON = new Gson(); // // @Nullable // @Override // public String adaptForPreferences(@Nullable List<CustomClass> value) { // return GSON.toJson(value); // } // // @Nullable // @Override // public List<CustomClass> adaptFromPreferences(@Nullable String value) { // return GSON.fromJson(value, new TypeToken<List<CustomClass>>(){}.getType()); // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassTypeAdapter.java // public class CustomClassTypeAdapter extends BaseStringTypeAdapter<CustomClass> { // // @Nullable // @Override // public String adaptForPreferences(@Nullable CustomClass value) { // if (value == null) { // return null; // } // // return value.getOne() + "|" + value.getTwo(); // } // // @Nullable // @Override // public CustomClass adaptFromPreferences(@Nullable String value) { // if (value == null) { // return null; // } // // if (value.length() == 1) { // return new CustomClass(); // } else { // final String split[] = value.split("\\|"); // // return new CustomClass(split[0], split[1]); // } // } // }
import android.net.Uri; import net.orange_box.storebox.annotations.method.KeyByString; import net.orange_box.storebox.annotations.method.TypeAdapter; import net.orange_box.storebox.harness.types.CustomClass; import net.orange_box.storebox.harness.types.CustomEnum; import net.orange_box.storebox.harness.types.adapters.CustomClassListTypeAdapter; import net.orange_box.storebox.harness.types.adapters.CustomClassTypeAdapter; import java.util.Date; import java.util.List;
/* * Copyright 2015 Martin Bella * * 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.orange_box.storebox.harness.interfaces.types; public interface CustomTypesInterface { @KeyByString("key_custom_enum") CustomEnum getCustomEnum(); @KeyByString("key_custom_enum") CustomEnum getCustomEnum(CustomEnum defValue); @KeyByString("key_custom_enum") void setCustomEnum(CustomEnum value); @KeyByString("key_date") Date getDate(); @KeyByString("key_date") Date getDate(Date defValue); @KeyByString("key_date") void setDate(Date value); @KeyByString("key_double") double getDouble(); @KeyByString("key_double") double getDouble(double defValue); @KeyByString("key_double") void setDouble(double value); @KeyByString("key_uri") Uri getUri(); @KeyByString("key_uri") Uri getUri(Uri defValue); @KeyByString("key_uri") void setUri(Uri value); @TypeAdapter(CustomClassTypeAdapter.class) @KeyByString("key_custom_class")
// Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomClass.java // public class CustomClass { // // private int hashCode; // // private final String one; // private final String two; // // public CustomClass() { // this("", ""); // } // // public CustomClass(String one, String two) { // this.one = one; // this.two = two; // } // // public String getOne() { // return one; // } // // public String getTwo() { // return two; // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof CustomClass)) { // return false; // } // // final CustomClass other = (CustomClass) o; // return (one.equals(other.one) && two.equals(other.two)); // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = Arrays.hashCode(new String[] {one, two}); // } // // return hashCode; // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomEnum.java // public enum CustomEnum { // // ONE, // TWO // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassListTypeAdapter.java // public class CustomClassListTypeAdapter extends // BaseStringTypeAdapter<List<CustomClass>> { // // private static final Gson GSON = new Gson(); // // @Nullable // @Override // public String adaptForPreferences(@Nullable List<CustomClass> value) { // return GSON.toJson(value); // } // // @Nullable // @Override // public List<CustomClass> adaptFromPreferences(@Nullable String value) { // return GSON.fromJson(value, new TypeToken<List<CustomClass>>(){}.getType()); // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassTypeAdapter.java // public class CustomClassTypeAdapter extends BaseStringTypeAdapter<CustomClass> { // // @Nullable // @Override // public String adaptForPreferences(@Nullable CustomClass value) { // if (value == null) { // return null; // } // // return value.getOne() + "|" + value.getTwo(); // } // // @Nullable // @Override // public CustomClass adaptFromPreferences(@Nullable String value) { // if (value == null) { // return null; // } // // if (value.length() == 1) { // return new CustomClass(); // } else { // final String split[] = value.split("\\|"); // // return new CustomClass(split[0], split[1]); // } // } // } // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/interfaces/types/CustomTypesInterface.java import android.net.Uri; import net.orange_box.storebox.annotations.method.KeyByString; import net.orange_box.storebox.annotations.method.TypeAdapter; import net.orange_box.storebox.harness.types.CustomClass; import net.orange_box.storebox.harness.types.CustomEnum; import net.orange_box.storebox.harness.types.adapters.CustomClassListTypeAdapter; import net.orange_box.storebox.harness.types.adapters.CustomClassTypeAdapter; import java.util.Date; import java.util.List; /* * Copyright 2015 Martin Bella * * 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.orange_box.storebox.harness.interfaces.types; public interface CustomTypesInterface { @KeyByString("key_custom_enum") CustomEnum getCustomEnum(); @KeyByString("key_custom_enum") CustomEnum getCustomEnum(CustomEnum defValue); @KeyByString("key_custom_enum") void setCustomEnum(CustomEnum value); @KeyByString("key_date") Date getDate(); @KeyByString("key_date") Date getDate(Date defValue); @KeyByString("key_date") void setDate(Date value); @KeyByString("key_double") double getDouble(); @KeyByString("key_double") double getDouble(double defValue); @KeyByString("key_double") void setDouble(double value); @KeyByString("key_uri") Uri getUri(); @KeyByString("key_uri") Uri getUri(Uri defValue); @KeyByString("key_uri") void setUri(Uri value); @TypeAdapter(CustomClassTypeAdapter.class) @KeyByString("key_custom_class")
CustomClass getCustomClass();
martino2k6/StoreBox
storebox-harness/src/main/java/net/orange_box/storebox/harness/interfaces/types/CustomTypesInterface.java
// Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomClass.java // public class CustomClass { // // private int hashCode; // // private final String one; // private final String two; // // public CustomClass() { // this("", ""); // } // // public CustomClass(String one, String two) { // this.one = one; // this.two = two; // } // // public String getOne() { // return one; // } // // public String getTwo() { // return two; // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof CustomClass)) { // return false; // } // // final CustomClass other = (CustomClass) o; // return (one.equals(other.one) && two.equals(other.two)); // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = Arrays.hashCode(new String[] {one, two}); // } // // return hashCode; // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomEnum.java // public enum CustomEnum { // // ONE, // TWO // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassListTypeAdapter.java // public class CustomClassListTypeAdapter extends // BaseStringTypeAdapter<List<CustomClass>> { // // private static final Gson GSON = new Gson(); // // @Nullable // @Override // public String adaptForPreferences(@Nullable List<CustomClass> value) { // return GSON.toJson(value); // } // // @Nullable // @Override // public List<CustomClass> adaptFromPreferences(@Nullable String value) { // return GSON.fromJson(value, new TypeToken<List<CustomClass>>(){}.getType()); // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassTypeAdapter.java // public class CustomClassTypeAdapter extends BaseStringTypeAdapter<CustomClass> { // // @Nullable // @Override // public String adaptForPreferences(@Nullable CustomClass value) { // if (value == null) { // return null; // } // // return value.getOne() + "|" + value.getTwo(); // } // // @Nullable // @Override // public CustomClass adaptFromPreferences(@Nullable String value) { // if (value == null) { // return null; // } // // if (value.length() == 1) { // return new CustomClass(); // } else { // final String split[] = value.split("\\|"); // // return new CustomClass(split[0], split[1]); // } // } // }
import android.net.Uri; import net.orange_box.storebox.annotations.method.KeyByString; import net.orange_box.storebox.annotations.method.TypeAdapter; import net.orange_box.storebox.harness.types.CustomClass; import net.orange_box.storebox.harness.types.CustomEnum; import net.orange_box.storebox.harness.types.adapters.CustomClassListTypeAdapter; import net.orange_box.storebox.harness.types.adapters.CustomClassTypeAdapter; import java.util.Date; import java.util.List;
@KeyByString("key_double") double getDouble(double defValue); @KeyByString("key_double") void setDouble(double value); @KeyByString("key_uri") Uri getUri(); @KeyByString("key_uri") Uri getUri(Uri defValue); @KeyByString("key_uri") void setUri(Uri value); @TypeAdapter(CustomClassTypeAdapter.class) @KeyByString("key_custom_class") CustomClass getCustomClass(); @TypeAdapter(CustomClassTypeAdapter.class) @KeyByString("key_custom_class") CustomClass getCustomClass(CustomClass defValue); @TypeAdapter(CustomClassTypeAdapter.class) @KeyByString("key_custom_class") void setCustomClass(CustomClass value);
// Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomClass.java // public class CustomClass { // // private int hashCode; // // private final String one; // private final String two; // // public CustomClass() { // this("", ""); // } // // public CustomClass(String one, String two) { // this.one = one; // this.two = two; // } // // public String getOne() { // return one; // } // // public String getTwo() { // return two; // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof CustomClass)) { // return false; // } // // final CustomClass other = (CustomClass) o; // return (one.equals(other.one) && two.equals(other.two)); // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = Arrays.hashCode(new String[] {one, two}); // } // // return hashCode; // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomEnum.java // public enum CustomEnum { // // ONE, // TWO // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassListTypeAdapter.java // public class CustomClassListTypeAdapter extends // BaseStringTypeAdapter<List<CustomClass>> { // // private static final Gson GSON = new Gson(); // // @Nullable // @Override // public String adaptForPreferences(@Nullable List<CustomClass> value) { // return GSON.toJson(value); // } // // @Nullable // @Override // public List<CustomClass> adaptFromPreferences(@Nullable String value) { // return GSON.fromJson(value, new TypeToken<List<CustomClass>>(){}.getType()); // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/adapters/CustomClassTypeAdapter.java // public class CustomClassTypeAdapter extends BaseStringTypeAdapter<CustomClass> { // // @Nullable // @Override // public String adaptForPreferences(@Nullable CustomClass value) { // if (value == null) { // return null; // } // // return value.getOne() + "|" + value.getTwo(); // } // // @Nullable // @Override // public CustomClass adaptFromPreferences(@Nullable String value) { // if (value == null) { // return null; // } // // if (value.length() == 1) { // return new CustomClass(); // } else { // final String split[] = value.split("\\|"); // // return new CustomClass(split[0], split[1]); // } // } // } // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/interfaces/types/CustomTypesInterface.java import android.net.Uri; import net.orange_box.storebox.annotations.method.KeyByString; import net.orange_box.storebox.annotations.method.TypeAdapter; import net.orange_box.storebox.harness.types.CustomClass; import net.orange_box.storebox.harness.types.CustomEnum; import net.orange_box.storebox.harness.types.adapters.CustomClassListTypeAdapter; import net.orange_box.storebox.harness.types.adapters.CustomClassTypeAdapter; import java.util.Date; import java.util.List; @KeyByString("key_double") double getDouble(double defValue); @KeyByString("key_double") void setDouble(double value); @KeyByString("key_uri") Uri getUri(); @KeyByString("key_uri") Uri getUri(Uri defValue); @KeyByString("key_uri") void setUri(Uri value); @TypeAdapter(CustomClassTypeAdapter.class) @KeyByString("key_custom_class") CustomClass getCustomClass(); @TypeAdapter(CustomClassTypeAdapter.class) @KeyByString("key_custom_class") CustomClass getCustomClass(CustomClass defValue); @TypeAdapter(CustomClassTypeAdapter.class) @KeyByString("key_custom_class") void setCustomClass(CustomClass value);
@TypeAdapter(CustomClassListTypeAdapter.class)
martino2k6/StoreBox
storebox-harness/src/androidTest/java/net/orange_box/storebox/harness/changes/ChangesListenersTestCase.java
// Path: storebox-harness/src/androidTest/java/net/orange_box/storebox/harness/base/PreferencesTestCase.java // public abstract class PreferencesTestCase<T> extends InstrumentationTestCase { // // protected T uut; // private SharedPreferences prefs; // // protected abstract Class<T> getInterface(); // // @Override // protected void setUp() throws Exception { // super.setUp(); // // uut = StoreBox.create( // getInstrumentation().getTargetContext(), // getInterface()); // // prefs = PreferenceManager.getDefaultSharedPreferences( // getInstrumentation().getTargetContext()); // } // // @SuppressLint("CommitPrefEdits") // @Override // protected void tearDown() throws Exception { // uut = null; // // // we are saving to the actual preferences so let's clear them // prefs.edit().clear().commit(); // prefs = null; // // super.tearDown(); // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/interfaces/changes/ChangeListenersInterface.java // public interface ChangeListenersInterface { // // @KeyByString("key_int") // void setInt(int value); // // @KeyByString("key_int") // @RegisterChangeListenerMethod // void registerIntChangeListener( // OnPreferenceValueChangedListener<Integer> listener); // // @KeyByString("key_int") // @RegisterChangeListenerMethod // void registerIntChangeListenerVarArgs( // OnPreferenceValueChangedListener<Integer>... listeners); // // @KeyByString("key_int") // @UnregisterChangeListenerMethod // void unregisterIntChangeListener( // OnPreferenceValueChangedListener<Integer> listener); // // @KeyByString("key_int") // @UnregisterChangeListenerMethod // void unregisterIntChangeListenerVarArgs( // OnPreferenceValueChangedListener<Integer>... listeners); // // // @KeyByString("key_custom_class") // @TypeAdapter(CustomClassTypeAdapter.class) // void setCustomClass(CustomClass value); // // @KeyByString("key_custom_class") // @RegisterChangeListenerMethod // @TypeAdapter(CustomClassTypeAdapter.class) // void registerCustomClassChangeListener( // OnPreferenceValueChangedListener<CustomClass> listener); // // @KeyByString("key_custom_class") // @UnregisterChangeListenerMethod // @TypeAdapter(CustomClassTypeAdapter.class) // void unregisterCustomClassChangeListener( // OnPreferenceValueChangedListener<CustomClass> listener); // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomClass.java // public class CustomClass { // // private int hashCode; // // private final String one; // private final String two; // // public CustomClass() { // this("", ""); // } // // public CustomClass(String one, String two) { // this.one = one; // this.two = two; // } // // public String getOne() { // return one; // } // // public String getTwo() { // return two; // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof CustomClass)) { // return false; // } // // final CustomClass other = (CustomClass) o; // return (one.equals(other.one) && two.equals(other.two)); // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = Arrays.hashCode(new String[] {one, two}); // } // // return hashCode; // } // } // // Path: storebox-lib/src/main/java/net/orange_box/storebox/listeners/OnPreferenceValueChangedListener.java // public interface OnPreferenceValueChangedListener<T> { // // void onChanged(T newValue); // }
import android.test.UiThreadTest; import android.test.suitebuilder.annotation.SmallTest; import net.orange_box.storebox.harness.base.PreferencesTestCase; import net.orange_box.storebox.harness.interfaces.changes.ChangeListenersInterface; import net.orange_box.storebox.harness.types.CustomClass; import net.orange_box.storebox.listeners.OnPreferenceValueChangedListener; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference;
/* * Copyright 2015 Martin Bella * * 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.orange_box.storebox.harness.changes; public class ChangesListenersTestCase extends PreferencesTestCase<ChangeListenersInterface> { @Override protected Class<ChangeListenersInterface> getInterface() { return ChangeListenersInterface.class; } @UiThreadTest @SmallTest public void testIntChanged() { final AtomicInteger value = new AtomicInteger(-1);
// Path: storebox-harness/src/androidTest/java/net/orange_box/storebox/harness/base/PreferencesTestCase.java // public abstract class PreferencesTestCase<T> extends InstrumentationTestCase { // // protected T uut; // private SharedPreferences prefs; // // protected abstract Class<T> getInterface(); // // @Override // protected void setUp() throws Exception { // super.setUp(); // // uut = StoreBox.create( // getInstrumentation().getTargetContext(), // getInterface()); // // prefs = PreferenceManager.getDefaultSharedPreferences( // getInstrumentation().getTargetContext()); // } // // @SuppressLint("CommitPrefEdits") // @Override // protected void tearDown() throws Exception { // uut = null; // // // we are saving to the actual preferences so let's clear them // prefs.edit().clear().commit(); // prefs = null; // // super.tearDown(); // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/interfaces/changes/ChangeListenersInterface.java // public interface ChangeListenersInterface { // // @KeyByString("key_int") // void setInt(int value); // // @KeyByString("key_int") // @RegisterChangeListenerMethod // void registerIntChangeListener( // OnPreferenceValueChangedListener<Integer> listener); // // @KeyByString("key_int") // @RegisterChangeListenerMethod // void registerIntChangeListenerVarArgs( // OnPreferenceValueChangedListener<Integer>... listeners); // // @KeyByString("key_int") // @UnregisterChangeListenerMethod // void unregisterIntChangeListener( // OnPreferenceValueChangedListener<Integer> listener); // // @KeyByString("key_int") // @UnregisterChangeListenerMethod // void unregisterIntChangeListenerVarArgs( // OnPreferenceValueChangedListener<Integer>... listeners); // // // @KeyByString("key_custom_class") // @TypeAdapter(CustomClassTypeAdapter.class) // void setCustomClass(CustomClass value); // // @KeyByString("key_custom_class") // @RegisterChangeListenerMethod // @TypeAdapter(CustomClassTypeAdapter.class) // void registerCustomClassChangeListener( // OnPreferenceValueChangedListener<CustomClass> listener); // // @KeyByString("key_custom_class") // @UnregisterChangeListenerMethod // @TypeAdapter(CustomClassTypeAdapter.class) // void unregisterCustomClassChangeListener( // OnPreferenceValueChangedListener<CustomClass> listener); // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomClass.java // public class CustomClass { // // private int hashCode; // // private final String one; // private final String two; // // public CustomClass() { // this("", ""); // } // // public CustomClass(String one, String two) { // this.one = one; // this.two = two; // } // // public String getOne() { // return one; // } // // public String getTwo() { // return two; // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof CustomClass)) { // return false; // } // // final CustomClass other = (CustomClass) o; // return (one.equals(other.one) && two.equals(other.two)); // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = Arrays.hashCode(new String[] {one, two}); // } // // return hashCode; // } // } // // Path: storebox-lib/src/main/java/net/orange_box/storebox/listeners/OnPreferenceValueChangedListener.java // public interface OnPreferenceValueChangedListener<T> { // // void onChanged(T newValue); // } // Path: storebox-harness/src/androidTest/java/net/orange_box/storebox/harness/changes/ChangesListenersTestCase.java import android.test.UiThreadTest; import android.test.suitebuilder.annotation.SmallTest; import net.orange_box.storebox.harness.base.PreferencesTestCase; import net.orange_box.storebox.harness.interfaces.changes.ChangeListenersInterface; import net.orange_box.storebox.harness.types.CustomClass; import net.orange_box.storebox.listeners.OnPreferenceValueChangedListener; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; /* * Copyright 2015 Martin Bella * * 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.orange_box.storebox.harness.changes; public class ChangesListenersTestCase extends PreferencesTestCase<ChangeListenersInterface> { @Override protected Class<ChangeListenersInterface> getInterface() { return ChangeListenersInterface.class; } @UiThreadTest @SmallTest public void testIntChanged() { final AtomicInteger value = new AtomicInteger(-1);
final OnPreferenceValueChangedListener<Integer> listener =
martino2k6/StoreBox
storebox-harness/src/androidTest/java/net/orange_box/storebox/harness/changes/ChangesListenersTestCase.java
// Path: storebox-harness/src/androidTest/java/net/orange_box/storebox/harness/base/PreferencesTestCase.java // public abstract class PreferencesTestCase<T> extends InstrumentationTestCase { // // protected T uut; // private SharedPreferences prefs; // // protected abstract Class<T> getInterface(); // // @Override // protected void setUp() throws Exception { // super.setUp(); // // uut = StoreBox.create( // getInstrumentation().getTargetContext(), // getInterface()); // // prefs = PreferenceManager.getDefaultSharedPreferences( // getInstrumentation().getTargetContext()); // } // // @SuppressLint("CommitPrefEdits") // @Override // protected void tearDown() throws Exception { // uut = null; // // // we are saving to the actual preferences so let's clear them // prefs.edit().clear().commit(); // prefs = null; // // super.tearDown(); // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/interfaces/changes/ChangeListenersInterface.java // public interface ChangeListenersInterface { // // @KeyByString("key_int") // void setInt(int value); // // @KeyByString("key_int") // @RegisterChangeListenerMethod // void registerIntChangeListener( // OnPreferenceValueChangedListener<Integer> listener); // // @KeyByString("key_int") // @RegisterChangeListenerMethod // void registerIntChangeListenerVarArgs( // OnPreferenceValueChangedListener<Integer>... listeners); // // @KeyByString("key_int") // @UnregisterChangeListenerMethod // void unregisterIntChangeListener( // OnPreferenceValueChangedListener<Integer> listener); // // @KeyByString("key_int") // @UnregisterChangeListenerMethod // void unregisterIntChangeListenerVarArgs( // OnPreferenceValueChangedListener<Integer>... listeners); // // // @KeyByString("key_custom_class") // @TypeAdapter(CustomClassTypeAdapter.class) // void setCustomClass(CustomClass value); // // @KeyByString("key_custom_class") // @RegisterChangeListenerMethod // @TypeAdapter(CustomClassTypeAdapter.class) // void registerCustomClassChangeListener( // OnPreferenceValueChangedListener<CustomClass> listener); // // @KeyByString("key_custom_class") // @UnregisterChangeListenerMethod // @TypeAdapter(CustomClassTypeAdapter.class) // void unregisterCustomClassChangeListener( // OnPreferenceValueChangedListener<CustomClass> listener); // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomClass.java // public class CustomClass { // // private int hashCode; // // private final String one; // private final String two; // // public CustomClass() { // this("", ""); // } // // public CustomClass(String one, String two) { // this.one = one; // this.two = two; // } // // public String getOne() { // return one; // } // // public String getTwo() { // return two; // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof CustomClass)) { // return false; // } // // final CustomClass other = (CustomClass) o; // return (one.equals(other.one) && two.equals(other.two)); // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = Arrays.hashCode(new String[] {one, two}); // } // // return hashCode; // } // } // // Path: storebox-lib/src/main/java/net/orange_box/storebox/listeners/OnPreferenceValueChangedListener.java // public interface OnPreferenceValueChangedListener<T> { // // void onChanged(T newValue); // }
import android.test.UiThreadTest; import android.test.suitebuilder.annotation.SmallTest; import net.orange_box.storebox.harness.base.PreferencesTestCase; import net.orange_box.storebox.harness.interfaces.changes.ChangeListenersInterface; import net.orange_box.storebox.harness.types.CustomClass; import net.orange_box.storebox.listeners.OnPreferenceValueChangedListener; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference;
@UiThreadTest @SmallTest public void testIntUnregisteredVarArgs() { final AtomicInteger count = new AtomicInteger(2); final OnPreferenceValueChangedListener<Integer> one = new OnPreferenceValueChangedListener<Integer>() { @Override public void onChanged(Integer newValue) { count.decrementAndGet(); } }; final OnPreferenceValueChangedListener<Integer> two = new OnPreferenceValueChangedListener<Integer>() { @Override public void onChanged(Integer newValue) { count.decrementAndGet(); } }; uut.registerIntChangeListenerVarArgs(one, two); uut.unregisterIntChangeListenerVarArgs(one, two); uut.setInt(1); assertEquals(2, count.get()); } @UiThreadTest @SmallTest public void testCustomClassChanged() {
// Path: storebox-harness/src/androidTest/java/net/orange_box/storebox/harness/base/PreferencesTestCase.java // public abstract class PreferencesTestCase<T> extends InstrumentationTestCase { // // protected T uut; // private SharedPreferences prefs; // // protected abstract Class<T> getInterface(); // // @Override // protected void setUp() throws Exception { // super.setUp(); // // uut = StoreBox.create( // getInstrumentation().getTargetContext(), // getInterface()); // // prefs = PreferenceManager.getDefaultSharedPreferences( // getInstrumentation().getTargetContext()); // } // // @SuppressLint("CommitPrefEdits") // @Override // protected void tearDown() throws Exception { // uut = null; // // // we are saving to the actual preferences so let's clear them // prefs.edit().clear().commit(); // prefs = null; // // super.tearDown(); // } // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/interfaces/changes/ChangeListenersInterface.java // public interface ChangeListenersInterface { // // @KeyByString("key_int") // void setInt(int value); // // @KeyByString("key_int") // @RegisterChangeListenerMethod // void registerIntChangeListener( // OnPreferenceValueChangedListener<Integer> listener); // // @KeyByString("key_int") // @RegisterChangeListenerMethod // void registerIntChangeListenerVarArgs( // OnPreferenceValueChangedListener<Integer>... listeners); // // @KeyByString("key_int") // @UnregisterChangeListenerMethod // void unregisterIntChangeListener( // OnPreferenceValueChangedListener<Integer> listener); // // @KeyByString("key_int") // @UnregisterChangeListenerMethod // void unregisterIntChangeListenerVarArgs( // OnPreferenceValueChangedListener<Integer>... listeners); // // // @KeyByString("key_custom_class") // @TypeAdapter(CustomClassTypeAdapter.class) // void setCustomClass(CustomClass value); // // @KeyByString("key_custom_class") // @RegisterChangeListenerMethod // @TypeAdapter(CustomClassTypeAdapter.class) // void registerCustomClassChangeListener( // OnPreferenceValueChangedListener<CustomClass> listener); // // @KeyByString("key_custom_class") // @UnregisterChangeListenerMethod // @TypeAdapter(CustomClassTypeAdapter.class) // void unregisterCustomClassChangeListener( // OnPreferenceValueChangedListener<CustomClass> listener); // } // // Path: storebox-harness/src/main/java/net/orange_box/storebox/harness/types/CustomClass.java // public class CustomClass { // // private int hashCode; // // private final String one; // private final String two; // // public CustomClass() { // this("", ""); // } // // public CustomClass(String one, String two) { // this.one = one; // this.two = two; // } // // public String getOne() { // return one; // } // // public String getTwo() { // return two; // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof CustomClass)) { // return false; // } // // final CustomClass other = (CustomClass) o; // return (one.equals(other.one) && two.equals(other.two)); // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = Arrays.hashCode(new String[] {one, two}); // } // // return hashCode; // } // } // // Path: storebox-lib/src/main/java/net/orange_box/storebox/listeners/OnPreferenceValueChangedListener.java // public interface OnPreferenceValueChangedListener<T> { // // void onChanged(T newValue); // } // Path: storebox-harness/src/androidTest/java/net/orange_box/storebox/harness/changes/ChangesListenersTestCase.java import android.test.UiThreadTest; import android.test.suitebuilder.annotation.SmallTest; import net.orange_box.storebox.harness.base.PreferencesTestCase; import net.orange_box.storebox.harness.interfaces.changes.ChangeListenersInterface; import net.orange_box.storebox.harness.types.CustomClass; import net.orange_box.storebox.listeners.OnPreferenceValueChangedListener; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @UiThreadTest @SmallTest public void testIntUnregisteredVarArgs() { final AtomicInteger count = new AtomicInteger(2); final OnPreferenceValueChangedListener<Integer> one = new OnPreferenceValueChangedListener<Integer>() { @Override public void onChanged(Integer newValue) { count.decrementAndGet(); } }; final OnPreferenceValueChangedListener<Integer> two = new OnPreferenceValueChangedListener<Integer>() { @Override public void onChanged(Integer newValue) { count.decrementAndGet(); } }; uut.registerIntChangeListenerVarArgs(one, two); uut.unregisterIntChangeListenerVarArgs(one, two); uut.setInt(1); assertEquals(2, count.get()); } @UiThreadTest @SmallTest public void testCustomClassChanged() {
final AtomicReference<CustomClass> value = new AtomicReference<>();
martino2k6/StoreBox
storebox-lib/src/main/java/net/orange_box/storebox/StoreBox.java
// Path: storebox-lib/src/main/java/net/orange_box/storebox/enums/PreferencesMode.java // public enum PreferencesMode { // // /** // * Default. // * // * @see android.content.Context#MODE_PRIVATE // */ // MODE_PRIVATE(Context.MODE_PRIVATE), // // /** // * @see android.content.Context#MODE_MULTI_PROCESS // */ // MODE_MULTI_PROCESS(Context.MODE_MULTI_PROCESS), // // /** // * @see android.content.Context#MODE_WORLD_READABLE // */ // @Deprecated // MODE_WORLD_READABLE(Context.MODE_WORLD_READABLE), // // /** // * @see android.content.Context#MODE_WORLD_WRITEABLE // */ // @Deprecated // MODE_WORLD_WRITEABLE(Context.MODE_WORLD_WRITEABLE); // // private final int value; // // private PreferencesMode(int value) { // this.value = value; // } // // public int value() { // return value; // } // } // // Path: storebox-lib/src/main/java/net/orange_box/storebox/enums/PreferencesType.java // public enum PreferencesType { // // /** // * Default. // * // * @see net.orange_box.storebox.annotations.type.DefaultSharedPreferences // * @see android.preference.PreferenceManager#getDefaultSharedPreferences( // * android.content.Context) // */ // DEFAULT_SHARED, // // /** // * @see net.orange_box.storebox.annotations.type.ActivityPreferences // * @see android.app.Activity#getPreferences(int) // */ // ACTIVITY, // // /** // * @see net.orange_box.storebox.annotations.type.FilePreferences // * @see android.content.Context#getSharedPreferences(String, int) // */ // FILE // } // // Path: storebox-lib/src/main/java/net/orange_box/storebox/enums/SaveMode.java // public enum SaveMode { // // /** // * Default. // * // * @see android.content.SharedPreferences.Editor#apply() // */ // APPLY, // // /** // * @see android.content.SharedPreferences.Editor#commit() // */ // COMMIT, // // /** // * {@link android.content.SharedPreferences.Editor#apply()} or // * {@link android.content.SharedPreferences.Editor#commit()} will have // * to be called explicitly. // */ // NOME // }
import android.app.Activity; import android.content.Context; import android.text.TextUtils; import net.orange_box.storebox.annotations.option.SaveOption; import net.orange_box.storebox.annotations.type.ActivityPreferences; import net.orange_box.storebox.annotations.type.DefaultSharedPreferences; import net.orange_box.storebox.annotations.type.FilePreferences; import net.orange_box.storebox.enums.PreferencesMode; import net.orange_box.storebox.enums.PreferencesType; import net.orange_box.storebox.enums.SaveMode; import java.lang.reflect.Proxy; import java.util.Locale;
/* * Copyright 2015 Martin Bella * * 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.orange_box.storebox; /** * Creates a no-thrills instance of the supplied interface, by reading any * options provided through interface-level annotations. * <p> * If you'd like to provide options dynamically at run-time, take a look at * {@link Builder}. */ public final class StoreBox { /** * @param context - the context under which the * {@link android.content.SharedPreferences} should be opened * @param cls - the interface class which should be instantiated * @return new instance of class {@code cls} using {@code context} */ public static <T> T create(Context context, Class<T> cls) { return new Builder<>(context, cls).build(); } private StoreBox() {} /** * Can be used to provide a customised instance of the supplied interface, * by setting custom options through builder methods. * * @param <T> */ public static final class Builder<T> { private final Context context; private final Class<T> cls;
// Path: storebox-lib/src/main/java/net/orange_box/storebox/enums/PreferencesMode.java // public enum PreferencesMode { // // /** // * Default. // * // * @see android.content.Context#MODE_PRIVATE // */ // MODE_PRIVATE(Context.MODE_PRIVATE), // // /** // * @see android.content.Context#MODE_MULTI_PROCESS // */ // MODE_MULTI_PROCESS(Context.MODE_MULTI_PROCESS), // // /** // * @see android.content.Context#MODE_WORLD_READABLE // */ // @Deprecated // MODE_WORLD_READABLE(Context.MODE_WORLD_READABLE), // // /** // * @see android.content.Context#MODE_WORLD_WRITEABLE // */ // @Deprecated // MODE_WORLD_WRITEABLE(Context.MODE_WORLD_WRITEABLE); // // private final int value; // // private PreferencesMode(int value) { // this.value = value; // } // // public int value() { // return value; // } // } // // Path: storebox-lib/src/main/java/net/orange_box/storebox/enums/PreferencesType.java // public enum PreferencesType { // // /** // * Default. // * // * @see net.orange_box.storebox.annotations.type.DefaultSharedPreferences // * @see android.preference.PreferenceManager#getDefaultSharedPreferences( // * android.content.Context) // */ // DEFAULT_SHARED, // // /** // * @see net.orange_box.storebox.annotations.type.ActivityPreferences // * @see android.app.Activity#getPreferences(int) // */ // ACTIVITY, // // /** // * @see net.orange_box.storebox.annotations.type.FilePreferences // * @see android.content.Context#getSharedPreferences(String, int) // */ // FILE // } // // Path: storebox-lib/src/main/java/net/orange_box/storebox/enums/SaveMode.java // public enum SaveMode { // // /** // * Default. // * // * @see android.content.SharedPreferences.Editor#apply() // */ // APPLY, // // /** // * @see android.content.SharedPreferences.Editor#commit() // */ // COMMIT, // // /** // * {@link android.content.SharedPreferences.Editor#apply()} or // * {@link android.content.SharedPreferences.Editor#commit()} will have // * to be called explicitly. // */ // NOME // } // Path: storebox-lib/src/main/java/net/orange_box/storebox/StoreBox.java import android.app.Activity; import android.content.Context; import android.text.TextUtils; import net.orange_box.storebox.annotations.option.SaveOption; import net.orange_box.storebox.annotations.type.ActivityPreferences; import net.orange_box.storebox.annotations.type.DefaultSharedPreferences; import net.orange_box.storebox.annotations.type.FilePreferences; import net.orange_box.storebox.enums.PreferencesMode; import net.orange_box.storebox.enums.PreferencesType; import net.orange_box.storebox.enums.SaveMode; import java.lang.reflect.Proxy; import java.util.Locale; /* * Copyright 2015 Martin Bella * * 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.orange_box.storebox; /** * Creates a no-thrills instance of the supplied interface, by reading any * options provided through interface-level annotations. * <p> * If you'd like to provide options dynamically at run-time, take a look at * {@link Builder}. */ public final class StoreBox { /** * @param context - the context under which the * {@link android.content.SharedPreferences} should be opened * @param cls - the interface class which should be instantiated * @return new instance of class {@code cls} using {@code context} */ public static <T> T create(Context context, Class<T> cls) { return new Builder<>(context, cls).build(); } private StoreBox() {} /** * Can be used to provide a customised instance of the supplied interface, * by setting custom options through builder methods. * * @param <T> */ public static final class Builder<T> { private final Context context; private final Class<T> cls;
private PreferencesType preferencesType = PreferencesType.DEFAULT_SHARED;