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
faber03/AndroidMalwareEvaluatingTools
DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/ScanPreTransDao.java
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/ScanPreTrans.java // public class ScanPreTrans // { // private Integer id; // private Integer idMalware; // private Integer idAntimalware; // private String scanResultIsMalicious; // private String UpdateSignaturesId; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public Integer getIdMalware() { // return idMalware; // } // public void setIdMalware(int idMalware) { // this.idMalware = idMalware; // } // public Integer getIdAntimalware() { // return idAntimalware; // } // public void setIdAntimalware(int idAntimalware) { // this.idAntimalware = idAntimalware; // } // public String getScanResultIsMalicious() { // return scanResultIsMalicious; // } // public void setScanResultIsMalicious(String scanResult) { // this.scanResultIsMalicious = scanResult; // } // public String getUpdateSignaturesId() { // return UpdateSignaturesId; // } // public void setUpdateSignaturesId(String updateSignaturesId) { // UpdateSignaturesId = updateSignaturesId; // } // // // }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.ScanPreTrans;
package com.progetto_sicurezza.dao; public class ScanPreTransDao { /* * scanPre: tutti i campi di scanPre possono essere null tranne: * idAntiMalware,idMalware * scanResultIsMalicious in set {"T","F"} */
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/ScanPreTrans.java // public class ScanPreTrans // { // private Integer id; // private Integer idMalware; // private Integer idAntimalware; // private String scanResultIsMalicious; // private String UpdateSignaturesId; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public Integer getIdMalware() { // return idMalware; // } // public void setIdMalware(int idMalware) { // this.idMalware = idMalware; // } // public Integer getIdAntimalware() { // return idAntimalware; // } // public void setIdAntimalware(int idAntimalware) { // this.idAntimalware = idAntimalware; // } // public String getScanResultIsMalicious() { // return scanResultIsMalicious; // } // public void setScanResultIsMalicious(String scanResult) { // this.scanResultIsMalicious = scanResult; // } // public String getUpdateSignaturesId() { // return UpdateSignaturesId; // } // public void setUpdateSignaturesId(String updateSignaturesId) { // UpdateSignaturesId = updateSignaturesId; // } // // // } // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/ScanPreTransDao.java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.ScanPreTrans; package com.progetto_sicurezza.dao; public class ScanPreTransDao { /* * scanPre: tutti i campi di scanPre possono essere null tranne: * idAntiMalware,idMalware * scanResultIsMalicious in set {"T","F"} */
public int insert(ScanPreTrans scanPre) throws SQLException
faber03/AndroidMalwareEvaluatingTools
DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/ScanPreTransDao.java
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/ScanPreTrans.java // public class ScanPreTrans // { // private Integer id; // private Integer idMalware; // private Integer idAntimalware; // private String scanResultIsMalicious; // private String UpdateSignaturesId; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public Integer getIdMalware() { // return idMalware; // } // public void setIdMalware(int idMalware) { // this.idMalware = idMalware; // } // public Integer getIdAntimalware() { // return idAntimalware; // } // public void setIdAntimalware(int idAntimalware) { // this.idAntimalware = idAntimalware; // } // public String getScanResultIsMalicious() { // return scanResultIsMalicious; // } // public void setScanResultIsMalicious(String scanResult) { // this.scanResultIsMalicious = scanResult; // } // public String getUpdateSignaturesId() { // return UpdateSignaturesId; // } // public void setUpdateSignaturesId(String updateSignaturesId) { // UpdateSignaturesId = updateSignaturesId; // } // // // }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.ScanPreTrans;
package com.progetto_sicurezza.dao; public class ScanPreTransDao { /* * scanPre: tutti i campi di scanPre possono essere null tranne: * idAntiMalware,idMalware * scanResultIsMalicious in set {"T","F"} */ public int insert(ScanPreTrans scanPre) throws SQLException { // controlli: // riferimento not null // vincolo not null e di insieme valori if(scanPre == null || scanPre.getIdAntimalware() == null || scanPre.getIdAntimalware() == null || !isValidScanResult(scanPre.getScanResultIsMalicious()) ) throw new IllegalArgumentException();
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/ScanPreTrans.java // public class ScanPreTrans // { // private Integer id; // private Integer idMalware; // private Integer idAntimalware; // private String scanResultIsMalicious; // private String UpdateSignaturesId; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public Integer getIdMalware() { // return idMalware; // } // public void setIdMalware(int idMalware) { // this.idMalware = idMalware; // } // public Integer getIdAntimalware() { // return idAntimalware; // } // public void setIdAntimalware(int idAntimalware) { // this.idAntimalware = idAntimalware; // } // public String getScanResultIsMalicious() { // return scanResultIsMalicious; // } // public void setScanResultIsMalicious(String scanResult) { // this.scanResultIsMalicious = scanResult; // } // public String getUpdateSignaturesId() { // return UpdateSignaturesId; // } // public void setUpdateSignaturesId(String updateSignaturesId) { // UpdateSignaturesId = updateSignaturesId; // } // // // } // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/ScanPreTransDao.java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.ScanPreTrans; package com.progetto_sicurezza.dao; public class ScanPreTransDao { /* * scanPre: tutti i campi di scanPre possono essere null tranne: * idAntiMalware,idMalware * scanResultIsMalicious in set {"T","F"} */ public int insert(ScanPreTrans scanPre) throws SQLException { // controlli: // riferimento not null // vincolo not null e di insieme valori if(scanPre == null || scanPre.getIdAntimalware() == null || scanPre.getIdAntimalware() == null || !isValidScanResult(scanPre.getScanResultIsMalicious()) ) throw new IllegalArgumentException();
Connection dbCon = DriverManager.getConnection(DBConfiguration.DB_URL,DBConfiguration.USERNAME,DBConfiguration.PASSWORD);
faber03/AndroidMalwareEvaluatingTools
DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/ScanPostTransDao.java
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/ScanPostTrans.java // public class ScanPostTrans // { // private Integer id; // private Integer idMalware; // private Integer idAntiMalware; // private String scanResultIsMalicious; // private Boolean dissAndReass; // private Boolean repacking; // private Boolean callIndirection; // private Boolean changingPackage; // private Boolean changingClassname; // private Boolean dataEncoding; // private Boolean junkNop; // private Boolean junkNopUncJump; // private Boolean junkRandomGarbage; // private Boolean signatureRewriting; // private Boolean codeReorder; // private String amSignatureUpdateId; // // // public String getAmSignatureUpdateId() { // return amSignatureUpdateId; // } // public void setAmSignatureUpdateId(String amSignatureUpdateId) { // this.amSignatureUpdateId = amSignatureUpdateId; // } // public Boolean isCodeReorder() { // return codeReorder; // } // public void setCodeReorder(boolean codeReorder) { // this.codeReorder = codeReorder; // } // // public Integer getIdMalware() { // return idMalware; // } // public void setIdMalware(int idMalware) { // this.idMalware = idMalware; // } // public Integer getIdAntiMalware() { // return idAntiMalware; // } // public void setIdAntiMalware(int idAntiMalware) { // this.idAntiMalware = idAntiMalware; // } // public String getScanResultIsMalicious() { // return scanResultIsMalicious; // } // public void setScanResultIsMalicious(String isMaliciousPreTransf) { // this.scanResultIsMalicious = isMaliciousPreTransf; // } // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public Boolean isDissAndReass() { // return dissAndReass; // } // public void setDissAndReass(boolean dissAndReass) { // this.dissAndReass = dissAndReass; // } // public Boolean isRepacking() { // return repacking; // } // public void setRepacking(boolean repacking) { // this.repacking = repacking; // } // public Boolean isCallIndirection() { // return callIndirection; // } // public void setCallIndirection(boolean callIndirection) { // this.callIndirection = callIndirection; // } // public Boolean isChangingPackage() { // return changingPackage; // } // public void setChangingPackage(boolean changingPackage) { // this.changingPackage = changingPackage; // } // public Boolean isChangingClassname() { // return changingClassname; // } // public void setChangingClassname(boolean changingClassname) { // this.changingClassname = changingClassname; // } // public Boolean isDataEncoding() { // return dataEncoding; // } // public void setDataEncoding(boolean dataEncoding) { // this.dataEncoding = dataEncoding; // } // public Boolean isJunkNop() { // return junkNop; // } // public void setJunkNop(boolean junkNop) { // this.junkNop = junkNop; // } // public Boolean isJunkNopUncJump() { // return junkNopUncJump; // } // public void setJunkNopUncJump(boolean junkNopUncJump) { // this.junkNopUncJump = junkNopUncJump; // } // public Boolean isJunkRandomGarbage() { // return junkRandomGarbage; // } // public void setJunkRandomGarbage(boolean junkRandomGarbage) { // this.junkRandomGarbage = junkRandomGarbage; // } // public Boolean isSignatureRewriting() { // return signatureRewriting; // } // public void setSignatureRewriting(boolean updateSignature) { // this.signatureRewriting = updateSignature; // } // }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.ScanPostTrans;
package com.progetto_sicurezza.dao; public class ScanPostTransDao { /* * scanPost: tutti i campi di scanPost possono essere null tranne: * idAntiMalware,idMalware,CallIndirection,ChangingClassname, * ChangingPackage, CodeReorder ,DataEncoding , * DissAndReass,isJunkNop,JunkNopUncJump, * JunkRandomGarbage,scan.isRepacking,canResultIsMalicious * canResultIsMalicious in set {"T","F"} * */
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/ScanPostTrans.java // public class ScanPostTrans // { // private Integer id; // private Integer idMalware; // private Integer idAntiMalware; // private String scanResultIsMalicious; // private Boolean dissAndReass; // private Boolean repacking; // private Boolean callIndirection; // private Boolean changingPackage; // private Boolean changingClassname; // private Boolean dataEncoding; // private Boolean junkNop; // private Boolean junkNopUncJump; // private Boolean junkRandomGarbage; // private Boolean signatureRewriting; // private Boolean codeReorder; // private String amSignatureUpdateId; // // // public String getAmSignatureUpdateId() { // return amSignatureUpdateId; // } // public void setAmSignatureUpdateId(String amSignatureUpdateId) { // this.amSignatureUpdateId = amSignatureUpdateId; // } // public Boolean isCodeReorder() { // return codeReorder; // } // public void setCodeReorder(boolean codeReorder) { // this.codeReorder = codeReorder; // } // // public Integer getIdMalware() { // return idMalware; // } // public void setIdMalware(int idMalware) { // this.idMalware = idMalware; // } // public Integer getIdAntiMalware() { // return idAntiMalware; // } // public void setIdAntiMalware(int idAntiMalware) { // this.idAntiMalware = idAntiMalware; // } // public String getScanResultIsMalicious() { // return scanResultIsMalicious; // } // public void setScanResultIsMalicious(String isMaliciousPreTransf) { // this.scanResultIsMalicious = isMaliciousPreTransf; // } // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public Boolean isDissAndReass() { // return dissAndReass; // } // public void setDissAndReass(boolean dissAndReass) { // this.dissAndReass = dissAndReass; // } // public Boolean isRepacking() { // return repacking; // } // public void setRepacking(boolean repacking) { // this.repacking = repacking; // } // public Boolean isCallIndirection() { // return callIndirection; // } // public void setCallIndirection(boolean callIndirection) { // this.callIndirection = callIndirection; // } // public Boolean isChangingPackage() { // return changingPackage; // } // public void setChangingPackage(boolean changingPackage) { // this.changingPackage = changingPackage; // } // public Boolean isChangingClassname() { // return changingClassname; // } // public void setChangingClassname(boolean changingClassname) { // this.changingClassname = changingClassname; // } // public Boolean isDataEncoding() { // return dataEncoding; // } // public void setDataEncoding(boolean dataEncoding) { // this.dataEncoding = dataEncoding; // } // public Boolean isJunkNop() { // return junkNop; // } // public void setJunkNop(boolean junkNop) { // this.junkNop = junkNop; // } // public Boolean isJunkNopUncJump() { // return junkNopUncJump; // } // public void setJunkNopUncJump(boolean junkNopUncJump) { // this.junkNopUncJump = junkNopUncJump; // } // public Boolean isJunkRandomGarbage() { // return junkRandomGarbage; // } // public void setJunkRandomGarbage(boolean junkRandomGarbage) { // this.junkRandomGarbage = junkRandomGarbage; // } // public Boolean isSignatureRewriting() { // return signatureRewriting; // } // public void setSignatureRewriting(boolean updateSignature) { // this.signatureRewriting = updateSignature; // } // } // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/ScanPostTransDao.java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.ScanPostTrans; package com.progetto_sicurezza.dao; public class ScanPostTransDao { /* * scanPost: tutti i campi di scanPost possono essere null tranne: * idAntiMalware,idMalware,CallIndirection,ChangingClassname, * ChangingPackage, CodeReorder ,DataEncoding , * DissAndReass,isJunkNop,JunkNopUncJump, * JunkRandomGarbage,scan.isRepacking,canResultIsMalicious * canResultIsMalicious in set {"T","F"} * */
public int insert(ScanPostTrans scanPost) throws SQLException
faber03/AndroidMalwareEvaluatingTools
DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/ui/HtmlReporterPre.java
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // }
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration;
package com.progetto_sicurezza.ui; public class HtmlReporterPre { final static String CHAR_ENCODING = "UTF-8"; public static void showResultsMalwarePre() throws SQLException, IOException {
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/ui/HtmlReporterPre.java import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; package com.progetto_sicurezza.ui; public class HtmlReporterPre { final static String CHAR_ENCODING = "UTF-8"; public static void showResultsMalwarePre() throws SQLException, IOException {
Connection dbCon = DriverManager.getConnection(DBConfiguration.DB_URL,DBConfiguration.USERNAME,DBConfiguration.PASSWORD);
faber03/AndroidMalwareEvaluatingTools
DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/MalwareFamilyDao.java
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/MalwareFamily.java // public class MalwareFamily // { // private Integer id; // private String familyName; // private String familyDescription; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getFamilyName() { // return familyName; // } // public void setFamily_name(String familyName) { // this.familyName = familyName; // } // public String getFamilyDescription() { // return familyDescription; // } // public void setFamily_description(String familyDescription) { // this.familyDescription = familyDescription; // } // // // }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.MalwareFamily;
package com.progetto_sicurezza.dao; public class MalwareFamilyDao { /* * malwareF: tutti i campi di malwareF possono essere null tranne: * familyName */
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/MalwareFamily.java // public class MalwareFamily // { // private Integer id; // private String familyName; // private String familyDescription; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getFamilyName() { // return familyName; // } // public void setFamily_name(String familyName) { // this.familyName = familyName; // } // public String getFamilyDescription() { // return familyDescription; // } // public void setFamily_description(String familyDescription) { // this.familyDescription = familyDescription; // } // // // } // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/MalwareFamilyDao.java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.MalwareFamily; package com.progetto_sicurezza.dao; public class MalwareFamilyDao { /* * malwareF: tutti i campi di malwareF possono essere null tranne: * familyName */
public int insert(MalwareFamily malwareF) throws SQLException
faber03/AndroidMalwareEvaluatingTools
DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/MalwareFamilyDao.java
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/MalwareFamily.java // public class MalwareFamily // { // private Integer id; // private String familyName; // private String familyDescription; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getFamilyName() { // return familyName; // } // public void setFamily_name(String familyName) { // this.familyName = familyName; // } // public String getFamilyDescription() { // return familyDescription; // } // public void setFamily_description(String familyDescription) { // this.familyDescription = familyDescription; // } // // // }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.MalwareFamily;
package com.progetto_sicurezza.dao; public class MalwareFamilyDao { /* * malwareF: tutti i campi di malwareF possono essere null tranne: * familyName */ public int insert(MalwareFamily malwareF) throws SQLException { // controlli: // riferimento not null // vincoli sui campi not null if(malwareF == null || malwareF.getFamilyName() == null) throw new IllegalArgumentException();
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/MalwareFamily.java // public class MalwareFamily // { // private Integer id; // private String familyName; // private String familyDescription; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getFamilyName() { // return familyName; // } // public void setFamily_name(String familyName) { // this.familyName = familyName; // } // public String getFamilyDescription() { // return familyDescription; // } // public void setFamily_description(String familyDescription) { // this.familyDescription = familyDescription; // } // // // } // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/MalwareFamilyDao.java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.MalwareFamily; package com.progetto_sicurezza.dao; public class MalwareFamilyDao { /* * malwareF: tutti i campi di malwareF possono essere null tranne: * familyName */ public int insert(MalwareFamily malwareF) throws SQLException { // controlli: // riferimento not null // vincoli sui campi not null if(malwareF == null || malwareF.getFamilyName() == null) throw new IllegalArgumentException();
Connection dbCon = DriverManager.getConnection(DBConfiguration.DB_URL,DBConfiguration.USERNAME,DBConfiguration.PASSWORD);
faber03/AndroidMalwareEvaluatingTools
DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/MalwareDao.java
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/Malware.java // public class Malware // { // private Integer id; // private String malwareStrId; // private Float kbDim; // private Integer idFamily; // private String descr; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getMalwareStrId() { // return malwareStrId; // } // public void setMalwareStrId(String malwareStrId) { // this.malwareStrId = malwareStrId; // } // public Float getKbDim() // { // return kbDim; // } // public void setKbDim(float kbDim) { // this.kbDim = kbDim; // } // public Integer getIdFamily() { // return idFamily; // } // public void setIdFamily(int idFamily) { // this.idFamily = idFamily; // } // public String getDescr() { // return descr; // } // public void setDescr(String descr) { // this.descr = descr; // } // // public String toString() // { // return "Malware [id=" + id + ", malwareStrId=" + malwareStrId // + ", kbDim=" + kbDim + ", idFamily=" + idFamily + ", descr=" // + descr + "]"; // } // }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.Malware;
package com.progetto_sicurezza.dao; public class MalwareDao { /* * malware: tutti i campi di malware possono essere null tranne: * malwareStrId */
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/Malware.java // public class Malware // { // private Integer id; // private String malwareStrId; // private Float kbDim; // private Integer idFamily; // private String descr; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getMalwareStrId() { // return malwareStrId; // } // public void setMalwareStrId(String malwareStrId) { // this.malwareStrId = malwareStrId; // } // public Float getKbDim() // { // return kbDim; // } // public void setKbDim(float kbDim) { // this.kbDim = kbDim; // } // public Integer getIdFamily() { // return idFamily; // } // public void setIdFamily(int idFamily) { // this.idFamily = idFamily; // } // public String getDescr() { // return descr; // } // public void setDescr(String descr) { // this.descr = descr; // } // // public String toString() // { // return "Malware [id=" + id + ", malwareStrId=" + malwareStrId // + ", kbDim=" + kbDim + ", idFamily=" + idFamily + ", descr=" // + descr + "]"; // } // } // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/MalwareDao.java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.Malware; package com.progetto_sicurezza.dao; public class MalwareDao { /* * malware: tutti i campi di malware possono essere null tranne: * malwareStrId */
public int insert(Malware malware) throws SQLException
faber03/AndroidMalwareEvaluatingTools
DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/MalwareDao.java
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/Malware.java // public class Malware // { // private Integer id; // private String malwareStrId; // private Float kbDim; // private Integer idFamily; // private String descr; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getMalwareStrId() { // return malwareStrId; // } // public void setMalwareStrId(String malwareStrId) { // this.malwareStrId = malwareStrId; // } // public Float getKbDim() // { // return kbDim; // } // public void setKbDim(float kbDim) { // this.kbDim = kbDim; // } // public Integer getIdFamily() { // return idFamily; // } // public void setIdFamily(int idFamily) { // this.idFamily = idFamily; // } // public String getDescr() { // return descr; // } // public void setDescr(String descr) { // this.descr = descr; // } // // public String toString() // { // return "Malware [id=" + id + ", malwareStrId=" + malwareStrId // + ", kbDim=" + kbDim + ", idFamily=" + idFamily + ", descr=" // + descr + "]"; // } // }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.Malware;
package com.progetto_sicurezza.dao; public class MalwareDao { /* * malware: tutti i campi di malware possono essere null tranne: * malwareStrId */ public int insert(Malware malware) throws SQLException { // controlli: // riferimento not null // vincoli sui campi not null if(malware == null || malware.getMalwareStrId() == null) throw new IllegalArgumentException();
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/Malware.java // public class Malware // { // private Integer id; // private String malwareStrId; // private Float kbDim; // private Integer idFamily; // private String descr; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getMalwareStrId() { // return malwareStrId; // } // public void setMalwareStrId(String malwareStrId) { // this.malwareStrId = malwareStrId; // } // public Float getKbDim() // { // return kbDim; // } // public void setKbDim(float kbDim) { // this.kbDim = kbDim; // } // public Integer getIdFamily() { // return idFamily; // } // public void setIdFamily(int idFamily) { // this.idFamily = idFamily; // } // public String getDescr() { // return descr; // } // public void setDescr(String descr) { // this.descr = descr; // } // // public String toString() // { // return "Malware [id=" + id + ", malwareStrId=" + malwareStrId // + ", kbDim=" + kbDim + ", idFamily=" + idFamily + ", descr=" // + descr + "]"; // } // } // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/MalwareDao.java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.Malware; package com.progetto_sicurezza.dao; public class MalwareDao { /* * malware: tutti i campi di malware possono essere null tranne: * malwareStrId */ public int insert(Malware malware) throws SQLException { // controlli: // riferimento not null // vincoli sui campi not null if(malware == null || malware.getMalwareStrId() == null) throw new IllegalArgumentException();
Connection dbCon = DriverManager.getConnection(DBConfiguration.DB_URL,DBConfiguration.USERNAME,DBConfiguration.PASSWORD);
faber03/AndroidMalwareEvaluatingTools
DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/ui/HtmlReporterComparison.java
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // }
import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration;
package com.progetto_sicurezza.ui; public class HtmlReporterComparison { final static String CHAR_ENCODING = "UTF-8"; public static void showResultsComparisonMalware_bf(boolean disass_and_reass ,boolean repacking_signature, boolean call_indirection,boolean identifier_renaming_package, boolean identifier_renaming_classname,boolean code_reorder, boolean data_encoding, boolean junk_nop, boolean junk_nop_unc_jump, boolean junk_random_garbage) throws SQLException, IOException {
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/ui/HtmlReporterComparison.java import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; package com.progetto_sicurezza.ui; public class HtmlReporterComparison { final static String CHAR_ENCODING = "UTF-8"; public static void showResultsComparisonMalware_bf(boolean disass_and_reass ,boolean repacking_signature, boolean call_indirection,boolean identifier_renaming_package, boolean identifier_renaming_classname,boolean code_reorder, boolean data_encoding, boolean junk_nop, boolean junk_nop_unc_jump, boolean junk_random_garbage) throws SQLException, IOException {
Connection dbCon = DriverManager.getConnection(DBConfiguration.DB_URL,DBConfiguration.USERNAME,DBConfiguration.PASSWORD);
faber03/AndroidMalwareEvaluatingTools
DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/AntiMalwareDao.java
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/AntiMalware.java // public class AntiMalware // { // private Integer id; // private String nome; // private String softwareHouse; // private String version; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getNome() { // return nome; // } // public void setNome(String nome) { // this.nome = nome; // } // public String getSoftware_house() { // return softwareHouse; // } // public void setSoftware_house(String software_house) { // this.softwareHouse = software_house; // } // public String getVersion() { // return version; // } // public void setVersion(String version) { // this.version = version; // } // // @Override // public String toString() { // return "AntiMalware [id=" + id + ", nome=" + nome + ", softwareHouse=" // + softwareHouse + ", version=" + version + "]"; // } // // // }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.AntiMalware;
package com.progetto_sicurezza.dao; public class AntiMalwareDao { /* * antimalware: tutti i campi di antimalware possono essere null tranne: * nome */
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/AntiMalware.java // public class AntiMalware // { // private Integer id; // private String nome; // private String softwareHouse; // private String version; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getNome() { // return nome; // } // public void setNome(String nome) { // this.nome = nome; // } // public String getSoftware_house() { // return softwareHouse; // } // public void setSoftware_house(String software_house) { // this.softwareHouse = software_house; // } // public String getVersion() { // return version; // } // public void setVersion(String version) { // this.version = version; // } // // @Override // public String toString() { // return "AntiMalware [id=" + id + ", nome=" + nome + ", softwareHouse=" // + softwareHouse + ", version=" + version + "]"; // } // // // } // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/AntiMalwareDao.java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.AntiMalware; package com.progetto_sicurezza.dao; public class AntiMalwareDao { /* * antimalware: tutti i campi di antimalware possono essere null tranne: * nome */
public int insert(AntiMalware antimalware) throws SQLException
faber03/AndroidMalwareEvaluatingTools
DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/AntiMalwareDao.java
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/AntiMalware.java // public class AntiMalware // { // private Integer id; // private String nome; // private String softwareHouse; // private String version; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getNome() { // return nome; // } // public void setNome(String nome) { // this.nome = nome; // } // public String getSoftware_house() { // return softwareHouse; // } // public void setSoftware_house(String software_house) { // this.softwareHouse = software_house; // } // public String getVersion() { // return version; // } // public void setVersion(String version) { // this.version = version; // } // // @Override // public String toString() { // return "AntiMalware [id=" + id + ", nome=" + nome + ", softwareHouse=" // + softwareHouse + ", version=" + version + "]"; // } // // // }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.AntiMalware;
package com.progetto_sicurezza.dao; public class AntiMalwareDao { /* * antimalware: tutti i campi di antimalware possono essere null tranne: * nome */ public int insert(AntiMalware antimalware) throws SQLException { // controlli: // riferimento not null // vincoli sui campi not null if(antimalware == null || antimalware.getNome() == null) throw new IllegalArgumentException();
// Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dbconfig/DBConfiguration.java // public class DBConfiguration // { // public static final String DB_URL = "jdbc:mysql://localhost:3306/malware_data_collection"; // public static final String USERNAME ="root"; // public static final String PASSWORD = ""; // } // // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/model/AntiMalware.java // public class AntiMalware // { // private Integer id; // private String nome; // private String softwareHouse; // private String version; // // public Integer getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getNome() { // return nome; // } // public void setNome(String nome) { // this.nome = nome; // } // public String getSoftware_house() { // return softwareHouse; // } // public void setSoftware_house(String software_house) { // this.softwareHouse = software_house; // } // public String getVersion() { // return version; // } // public void setVersion(String version) { // this.version = version; // } // // @Override // public String toString() { // return "AntiMalware [id=" + id + ", nome=" + nome + ", softwareHouse=" // + softwareHouse + ", version=" + version + "]"; // } // // // } // Path: DB_and_virustotal_submission/MalwareAnalysisDBProject/src/com/progetto_sicurezza/dao/AntiMalwareDao.java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.progetto_sicurezza.dbconfig.DBConfiguration; import com.progetto_sicurezza.model.AntiMalware; package com.progetto_sicurezza.dao; public class AntiMalwareDao { /* * antimalware: tutti i campi di antimalware possono essere null tranne: * nome */ public int insert(AntiMalware antimalware) throws SQLException { // controlli: // riferimento not null // vincoli sui campi not null if(antimalware == null || antimalware.getNome() == null) throw new IllegalArgumentException();
Connection dbCon = DriverManager.getConnection(DBConfiguration.DB_URL,DBConfiguration.USERNAME,DBConfiguration.PASSWORD);
ArcBees/gwtquery-draggable-plugin
sample/src/main/java/gwtquery/plugins/draggable/client/StackSample.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class;
import com.google.gwt.core.client.EntryPoint; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable;
/* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Simple sample * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class StackSample implements EntryPoint { public void onModuleLoad() { DraggableOptions o = new DraggableOptions(); o.setStack(".ui-widget-content");
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class; // Path: sample/src/main/java/gwtquery/plugins/draggable/client/StackSample.java import com.google.gwt.core.client.EntryPoint; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable; /* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Simple sample * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class StackSample implements EntryPoint { public void onModuleLoad() { DraggableOptions o = new DraggableOptions(); o.setStack(".ui-widget-content");
$(".ui-widget-content").as(Draggable).draggable(o);
ArcBees/gwtquery-draggable-plugin
sample/src/main/java/gwtquery/plugins/draggable/client/SnapSample.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum SnapMode { // /** // * The helper will snap the inner and the outer edges of snap elements. // */ // BOTH, // // /** // * The helper will snap the inner edges of snap elements. // */ // INNER, // // /** // * The helper will snap the outer edges of snap elements. // */ // OUTER; // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class;
import com.google.gwt.core.client.EntryPoint; import gwtquery.plugins.draggable.client.DraggableOptions.SnapMode; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable;
/* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Sample for snap option. * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class SnapSample implements EntryPoint { public void onModuleLoad() { DraggableOptions o = new DraggableOptions(); o.setSnap(true);
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum SnapMode { // /** // * The helper will snap the inner and the outer edges of snap elements. // */ // BOTH, // // /** // * The helper will snap the inner edges of snap elements. // */ // INNER, // // /** // * The helper will snap the outer edges of snap elements. // */ // OUTER; // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class; // Path: sample/src/main/java/gwtquery/plugins/draggable/client/SnapSample.java import com.google.gwt.core.client.EntryPoint; import gwtquery.plugins.draggable.client.DraggableOptions.SnapMode; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable; /* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Sample for snap option. * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class SnapSample implements EntryPoint { public void onModuleLoad() { DraggableOptions o = new DraggableOptions(); o.setSnap(true);
$("#draggable").as(Draggable).draggable(o);
ArcBees/gwtquery-draggable-plugin
sample/src/main/java/gwtquery/plugins/draggable/client/SnapSample.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum SnapMode { // /** // * The helper will snap the inner and the outer edges of snap elements. // */ // BOTH, // // /** // * The helper will snap the inner edges of snap elements. // */ // INNER, // // /** // * The helper will snap the outer edges of snap elements. // */ // OUTER; // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class;
import com.google.gwt.core.client.EntryPoint; import gwtquery.plugins.draggable.client.DraggableOptions.SnapMode; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable;
/* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Sample for snap option. * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class SnapSample implements EntryPoint { public void onModuleLoad() { DraggableOptions o = new DraggableOptions(); o.setSnap(true); $("#draggable").as(Draggable).draggable(o); o = new DraggableOptions(); o.setSnap("#SnapTarget"); $("#draggable2").as(Draggable).draggable(o); o = new DraggableOptions(); o.setSnap("#SnapTarget");
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum SnapMode { // /** // * The helper will snap the inner and the outer edges of snap elements. // */ // BOTH, // // /** // * The helper will snap the inner edges of snap elements. // */ // INNER, // // /** // * The helper will snap the outer edges of snap elements. // */ // OUTER; // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class; // Path: sample/src/main/java/gwtquery/plugins/draggable/client/SnapSample.java import com.google.gwt.core.client.EntryPoint; import gwtquery.plugins.draggable.client.DraggableOptions.SnapMode; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable; /* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Sample for snap option. * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class SnapSample implements EntryPoint { public void onModuleLoad() { DraggableOptions o = new DraggableOptions(); o.setSnap(true); $("#draggable").as(Draggable).draggable(o); o = new DraggableOptions(); o.setSnap("#SnapTarget"); $("#draggable2").as(Draggable).draggable(o); o = new DraggableOptions(); o.setSnap("#SnapTarget");
o.setSnapMode(SnapMode.OUTER);
ArcBees/gwtquery-draggable-plugin
sample/src/main/java/gwtquery/plugins/draggable/client/ContainmentSample.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class;
import com.google.gwt.core.client.EntryPoint; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable;
/* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Sample for containement options * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class ContainmentSample implements EntryPoint { public void onModuleLoad() { DraggableOptions o = new DraggableOptions(); o.setContainment("#box");
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class; // Path: sample/src/main/java/gwtquery/plugins/draggable/client/ContainmentSample.java import com.google.gwt.core.client.EntryPoint; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable; /* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Sample for containement options * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class ContainmentSample implements EntryPoint { public void onModuleLoad() { DraggableOptions o = new DraggableOptions(); o.setContainment("#box");
$("#draggable").as(Draggable).draggable(o);
ArcBees/gwtquery-draggable-plugin
sample/src/main/java/gwtquery/plugins/draggable/client/DraggableSample2.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class;
import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.ui.RootPanel; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable;
/* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Sample allows testing options * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class DraggableSample2 implements EntryPoint { public void onModuleLoad() {
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class; // Path: sample/src/main/java/gwtquery/plugins/draggable/client/DraggableSample2.java import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.ui.RootPanel; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable; /* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Sample allows testing options * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class DraggableSample2 implements EntryPoint { public void onModuleLoad() {
$("#draggable").as(Draggable).draggable();
ArcBees/gwtquery-draggable-plugin
plugin/src/main/java/gwtquery/plugins/draggable/client/impl/DraggableHandlerImplIE.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum HelperType { // /** // * CLONE : a clone of the original element will be used as dragging display // */ // CLONE { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original).clone(); // } // }, // // /** // * ORIGINAL : an other element will be used as dragging display // */ // ELEMENT { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return helperFromOptions; // } // }, // // /** // * ORIGINAL : the original element will be used as dragging display // */ // ORIGINAL { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original); // } // }; // // public abstract GQuery createHelper(Element original, // GQuery helperFromOptions); // }
import com.google.gwt.dom.client.Element; import com.google.gwt.query.client.GQuery; import gwtquery.plugins.draggable.client.DraggableOptions.HelperType;
/* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client.impl; /** * Specific code for IE * * @author Julien Dramaix (julien.dramaix@gmail.com, @jdramaix) */ public class DraggableHandlerImplIE extends DraggableHandlerImpl { @Override public boolean resetParentOffsetPosition(GQuery helperOffsetParent) { return super.resetParentOffsetPosition(helperOffsetParent) || helperOffsetParent.get(0) == GQuery.document.cast(); } @Override
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum HelperType { // /** // * CLONE : a clone of the original element will be used as dragging display // */ // CLONE { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original).clone(); // } // }, // // /** // * ORIGINAL : an other element will be used as dragging display // */ // ELEMENT { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return helperFromOptions; // } // }, // // /** // * ORIGINAL : the original element will be used as dragging display // */ // ORIGINAL { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original); // } // }; // // public abstract GQuery createHelper(Element original, // GQuery helperFromOptions); // } // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/impl/DraggableHandlerImplIE.java import com.google.gwt.dom.client.Element; import com.google.gwt.query.client.GQuery; import gwtquery.plugins.draggable.client.DraggableOptions.HelperType; /* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client.impl; /** * Specific code for IE * * @author Julien Dramaix (julien.dramaix@gmail.com, @jdramaix) */ public class DraggableHandlerImplIE extends DraggableHandlerImpl { @Override public boolean resetParentOffsetPosition(GQuery helperOffsetParent) { return super.resetParentOffsetPosition(helperOffsetParent) || helperOffsetParent.get(0) == GQuery.document.cast(); } @Override
public void removeHelper(GQuery helper, HelperType helperType) {
ArcBees/gwtquery-draggable-plugin
sample/src/main/java/gwtquery/plugins/draggable/client/DraggableSample1.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public interface DragFunction { // public void f(DragContext context); // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/events/DragContext.java // public class DragContext { // // static final String VALUE_KEY = "__dragAndDropCellAssociatedValue"; // // private Element draggable; // // private List<Element> selectedDraggables; // // private Element initialDraggable; // // // /** // * Constructor // * // * @param draggable the draggable element // */ // public DragContext(Element draggable, Element initialDraggable, // List<Element> selectedDraggable) { // this.draggable = draggable; // this.selectedDraggables = selectedDraggable; // this.initialDraggable = initialDraggable; // } // // public DragContext(DragContext ctx) { // this(ctx.getDraggable(), ctx.getInitialDraggable(), ctx // .getSelectedDraggables()); // } // // /** // * @return the draggable DOM element // */ // public Element getDraggable() { // return draggable; // } // // /** // * This method allows getting the data object linked to the draggable element // * (a cell) in the context of CellWidget.It return the data object being // * rendered by the dragging cell. Return null if we are not in the context of // * an drag and drop cell widget. // * // * @param <T> the class of the data // * @return // */ // @SuppressWarnings("unchecked") // public <T> T getDraggableData() { // return (T) $(getDraggable()).data(VALUE_KEY); // } // // /** // * This method return the widget associated to the draggable DOM element if it // * exist. It returns null otherwise. // */ // public DraggableWidget<?> getDraggableWidget() { // if (getDraggable() != null) { // return DraggableWidget.get(getDraggable()); // } // return null; // } // // /** // * @return the DOM element used for dragging display // */ // public Element getHelper() { // DraggableHandler handler = DraggableHandler.getInstance(draggable); // // if (handler.getHelper() != null) { // return handler.getHelper().get(0); // } // return null; // } // // /** // * @return the {@link Offset} of the helper element. // */ // public Offset getHelperPosition() { // return DraggableHandler.getInstance(draggable).getPosition(); // } // // /** // * @return the list of selected draggables. // */ // public List<Element> getSelectedDraggables() { // return selectedDraggables; // } // // /** // * @return the draggable element that initiate the drag operation (i.e. the // * clicked element) // */ // public Element getInitialDraggable() { // return initialDraggable; // } // // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class;
import com.google.gwt.core.client.EntryPoint; import gwtquery.plugins.draggable.client.DraggableOptions.DragFunction; import gwtquery.plugins.draggable.client.events.DragContext; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable;
/* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Simple sample * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class DraggableSample1 implements EntryPoint { private int startCounter = 0; private int dragCounter = 0; private int stopCounter = 0; public void onModuleLoad() { // simpleDraggable div DraggableOptions o = createOptionsForSimpleDraggable();
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public interface DragFunction { // public void f(DragContext context); // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/events/DragContext.java // public class DragContext { // // static final String VALUE_KEY = "__dragAndDropCellAssociatedValue"; // // private Element draggable; // // private List<Element> selectedDraggables; // // private Element initialDraggable; // // // /** // * Constructor // * // * @param draggable the draggable element // */ // public DragContext(Element draggable, Element initialDraggable, // List<Element> selectedDraggable) { // this.draggable = draggable; // this.selectedDraggables = selectedDraggable; // this.initialDraggable = initialDraggable; // } // // public DragContext(DragContext ctx) { // this(ctx.getDraggable(), ctx.getInitialDraggable(), ctx // .getSelectedDraggables()); // } // // /** // * @return the draggable DOM element // */ // public Element getDraggable() { // return draggable; // } // // /** // * This method allows getting the data object linked to the draggable element // * (a cell) in the context of CellWidget.It return the data object being // * rendered by the dragging cell. Return null if we are not in the context of // * an drag and drop cell widget. // * // * @param <T> the class of the data // * @return // */ // @SuppressWarnings("unchecked") // public <T> T getDraggableData() { // return (T) $(getDraggable()).data(VALUE_KEY); // } // // /** // * This method return the widget associated to the draggable DOM element if it // * exist. It returns null otherwise. // */ // public DraggableWidget<?> getDraggableWidget() { // if (getDraggable() != null) { // return DraggableWidget.get(getDraggable()); // } // return null; // } // // /** // * @return the DOM element used for dragging display // */ // public Element getHelper() { // DraggableHandler handler = DraggableHandler.getInstance(draggable); // // if (handler.getHelper() != null) { // return handler.getHelper().get(0); // } // return null; // } // // /** // * @return the {@link Offset} of the helper element. // */ // public Offset getHelperPosition() { // return DraggableHandler.getInstance(draggable).getPosition(); // } // // /** // * @return the list of selected draggables. // */ // public List<Element> getSelectedDraggables() { // return selectedDraggables; // } // // /** // * @return the draggable element that initiate the drag operation (i.e. the // * clicked element) // */ // public Element getInitialDraggable() { // return initialDraggable; // } // // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class; // Path: sample/src/main/java/gwtquery/plugins/draggable/client/DraggableSample1.java import com.google.gwt.core.client.EntryPoint; import gwtquery.plugins.draggable.client.DraggableOptions.DragFunction; import gwtquery.plugins.draggable.client.events.DragContext; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable; /* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Simple sample * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class DraggableSample1 implements EntryPoint { private int startCounter = 0; private int dragCounter = 0; private int stopCounter = 0; public void onModuleLoad() { // simpleDraggable div DraggableOptions o = createOptionsForSimpleDraggable();
$("#simpleDraggable").as(Draggable).draggable(o);
ArcBees/gwtquery-draggable-plugin
sample/src/main/java/gwtquery/plugins/draggable/client/DraggableSample1.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public interface DragFunction { // public void f(DragContext context); // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/events/DragContext.java // public class DragContext { // // static final String VALUE_KEY = "__dragAndDropCellAssociatedValue"; // // private Element draggable; // // private List<Element> selectedDraggables; // // private Element initialDraggable; // // // /** // * Constructor // * // * @param draggable the draggable element // */ // public DragContext(Element draggable, Element initialDraggable, // List<Element> selectedDraggable) { // this.draggable = draggable; // this.selectedDraggables = selectedDraggable; // this.initialDraggable = initialDraggable; // } // // public DragContext(DragContext ctx) { // this(ctx.getDraggable(), ctx.getInitialDraggable(), ctx // .getSelectedDraggables()); // } // // /** // * @return the draggable DOM element // */ // public Element getDraggable() { // return draggable; // } // // /** // * This method allows getting the data object linked to the draggable element // * (a cell) in the context of CellWidget.It return the data object being // * rendered by the dragging cell. Return null if we are not in the context of // * an drag and drop cell widget. // * // * @param <T> the class of the data // * @return // */ // @SuppressWarnings("unchecked") // public <T> T getDraggableData() { // return (T) $(getDraggable()).data(VALUE_KEY); // } // // /** // * This method return the widget associated to the draggable DOM element if it // * exist. It returns null otherwise. // */ // public DraggableWidget<?> getDraggableWidget() { // if (getDraggable() != null) { // return DraggableWidget.get(getDraggable()); // } // return null; // } // // /** // * @return the DOM element used for dragging display // */ // public Element getHelper() { // DraggableHandler handler = DraggableHandler.getInstance(draggable); // // if (handler.getHelper() != null) { // return handler.getHelper().get(0); // } // return null; // } // // /** // * @return the {@link Offset} of the helper element. // */ // public Offset getHelperPosition() { // return DraggableHandler.getInstance(draggable).getPosition(); // } // // /** // * @return the list of selected draggables. // */ // public List<Element> getSelectedDraggables() { // return selectedDraggables; // } // // /** // * @return the draggable element that initiate the drag operation (i.e. the // * clicked element) // */ // public Element getInitialDraggable() { // return initialDraggable; // } // // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class;
import com.google.gwt.core.client.EntryPoint; import gwtquery.plugins.draggable.client.DraggableOptions.DragFunction; import gwtquery.plugins.draggable.client.events.DragContext; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable;
/* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Simple sample * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class DraggableSample1 implements EntryPoint { private int startCounter = 0; private int dragCounter = 0; private int stopCounter = 0; public void onModuleLoad() { // simpleDraggable div DraggableOptions o = createOptionsForSimpleDraggable(); $("#simpleDraggable").as(Draggable).draggable(o); } private DraggableOptions createOptionsForSimpleDraggable() { DraggableOptions o = new DraggableOptions();
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public interface DragFunction { // public void f(DragContext context); // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/events/DragContext.java // public class DragContext { // // static final String VALUE_KEY = "__dragAndDropCellAssociatedValue"; // // private Element draggable; // // private List<Element> selectedDraggables; // // private Element initialDraggable; // // // /** // * Constructor // * // * @param draggable the draggable element // */ // public DragContext(Element draggable, Element initialDraggable, // List<Element> selectedDraggable) { // this.draggable = draggable; // this.selectedDraggables = selectedDraggable; // this.initialDraggable = initialDraggable; // } // // public DragContext(DragContext ctx) { // this(ctx.getDraggable(), ctx.getInitialDraggable(), ctx // .getSelectedDraggables()); // } // // /** // * @return the draggable DOM element // */ // public Element getDraggable() { // return draggable; // } // // /** // * This method allows getting the data object linked to the draggable element // * (a cell) in the context of CellWidget.It return the data object being // * rendered by the dragging cell. Return null if we are not in the context of // * an drag and drop cell widget. // * // * @param <T> the class of the data // * @return // */ // @SuppressWarnings("unchecked") // public <T> T getDraggableData() { // return (T) $(getDraggable()).data(VALUE_KEY); // } // // /** // * This method return the widget associated to the draggable DOM element if it // * exist. It returns null otherwise. // */ // public DraggableWidget<?> getDraggableWidget() { // if (getDraggable() != null) { // return DraggableWidget.get(getDraggable()); // } // return null; // } // // /** // * @return the DOM element used for dragging display // */ // public Element getHelper() { // DraggableHandler handler = DraggableHandler.getInstance(draggable); // // if (handler.getHelper() != null) { // return handler.getHelper().get(0); // } // return null; // } // // /** // * @return the {@link Offset} of the helper element. // */ // public Offset getHelperPosition() { // return DraggableHandler.getInstance(draggable).getPosition(); // } // // /** // * @return the list of selected draggables. // */ // public List<Element> getSelectedDraggables() { // return selectedDraggables; // } // // /** // * @return the draggable element that initiate the drag operation (i.e. the // * clicked element) // */ // public Element getInitialDraggable() { // return initialDraggable; // } // // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class; // Path: sample/src/main/java/gwtquery/plugins/draggable/client/DraggableSample1.java import com.google.gwt.core.client.EntryPoint; import gwtquery.plugins.draggable.client.DraggableOptions.DragFunction; import gwtquery.plugins.draggable.client.events.DragContext; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable; /* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Simple sample * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class DraggableSample1 implements EntryPoint { private int startCounter = 0; private int dragCounter = 0; private int stopCounter = 0; public void onModuleLoad() { // simpleDraggable div DraggableOptions o = createOptionsForSimpleDraggable(); $("#simpleDraggable").as(Draggable).draggable(o); } private DraggableOptions createOptionsForSimpleDraggable() { DraggableOptions o = new DraggableOptions();
o.setOnDragStart(new DragFunction() {
ArcBees/gwtquery-draggable-plugin
sample/src/main/java/gwtquery/plugins/draggable/client/DraggableSample1.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public interface DragFunction { // public void f(DragContext context); // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/events/DragContext.java // public class DragContext { // // static final String VALUE_KEY = "__dragAndDropCellAssociatedValue"; // // private Element draggable; // // private List<Element> selectedDraggables; // // private Element initialDraggable; // // // /** // * Constructor // * // * @param draggable the draggable element // */ // public DragContext(Element draggable, Element initialDraggable, // List<Element> selectedDraggable) { // this.draggable = draggable; // this.selectedDraggables = selectedDraggable; // this.initialDraggable = initialDraggable; // } // // public DragContext(DragContext ctx) { // this(ctx.getDraggable(), ctx.getInitialDraggable(), ctx // .getSelectedDraggables()); // } // // /** // * @return the draggable DOM element // */ // public Element getDraggable() { // return draggable; // } // // /** // * This method allows getting the data object linked to the draggable element // * (a cell) in the context of CellWidget.It return the data object being // * rendered by the dragging cell. Return null if we are not in the context of // * an drag and drop cell widget. // * // * @param <T> the class of the data // * @return // */ // @SuppressWarnings("unchecked") // public <T> T getDraggableData() { // return (T) $(getDraggable()).data(VALUE_KEY); // } // // /** // * This method return the widget associated to the draggable DOM element if it // * exist. It returns null otherwise. // */ // public DraggableWidget<?> getDraggableWidget() { // if (getDraggable() != null) { // return DraggableWidget.get(getDraggable()); // } // return null; // } // // /** // * @return the DOM element used for dragging display // */ // public Element getHelper() { // DraggableHandler handler = DraggableHandler.getInstance(draggable); // // if (handler.getHelper() != null) { // return handler.getHelper().get(0); // } // return null; // } // // /** // * @return the {@link Offset} of the helper element. // */ // public Offset getHelperPosition() { // return DraggableHandler.getInstance(draggable).getPosition(); // } // // /** // * @return the list of selected draggables. // */ // public List<Element> getSelectedDraggables() { // return selectedDraggables; // } // // /** // * @return the draggable element that initiate the drag operation (i.e. the // * clicked element) // */ // public Element getInitialDraggable() { // return initialDraggable; // } // // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class;
import com.google.gwt.core.client.EntryPoint; import gwtquery.plugins.draggable.client.DraggableOptions.DragFunction; import gwtquery.plugins.draggable.client.events.DragContext; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable;
/* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Simple sample * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class DraggableSample1 implements EntryPoint { private int startCounter = 0; private int dragCounter = 0; private int stopCounter = 0; public void onModuleLoad() { // simpleDraggable div DraggableOptions o = createOptionsForSimpleDraggable(); $("#simpleDraggable").as(Draggable).draggable(o); } private DraggableOptions createOptionsForSimpleDraggable() { DraggableOptions o = new DraggableOptions(); o.setOnDragStart(new DragFunction() {
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public interface DragFunction { // public void f(DragContext context); // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/events/DragContext.java // public class DragContext { // // static final String VALUE_KEY = "__dragAndDropCellAssociatedValue"; // // private Element draggable; // // private List<Element> selectedDraggables; // // private Element initialDraggable; // // // /** // * Constructor // * // * @param draggable the draggable element // */ // public DragContext(Element draggable, Element initialDraggable, // List<Element> selectedDraggable) { // this.draggable = draggable; // this.selectedDraggables = selectedDraggable; // this.initialDraggable = initialDraggable; // } // // public DragContext(DragContext ctx) { // this(ctx.getDraggable(), ctx.getInitialDraggable(), ctx // .getSelectedDraggables()); // } // // /** // * @return the draggable DOM element // */ // public Element getDraggable() { // return draggable; // } // // /** // * This method allows getting the data object linked to the draggable element // * (a cell) in the context of CellWidget.It return the data object being // * rendered by the dragging cell. Return null if we are not in the context of // * an drag and drop cell widget. // * // * @param <T> the class of the data // * @return // */ // @SuppressWarnings("unchecked") // public <T> T getDraggableData() { // return (T) $(getDraggable()).data(VALUE_KEY); // } // // /** // * This method return the widget associated to the draggable DOM element if it // * exist. It returns null otherwise. // */ // public DraggableWidget<?> getDraggableWidget() { // if (getDraggable() != null) { // return DraggableWidget.get(getDraggable()); // } // return null; // } // // /** // * @return the DOM element used for dragging display // */ // public Element getHelper() { // DraggableHandler handler = DraggableHandler.getInstance(draggable); // // if (handler.getHelper() != null) { // return handler.getHelper().get(0); // } // return null; // } // // /** // * @return the {@link Offset} of the helper element. // */ // public Offset getHelperPosition() { // return DraggableHandler.getInstance(draggable).getPosition(); // } // // /** // * @return the list of selected draggables. // */ // public List<Element> getSelectedDraggables() { // return selectedDraggables; // } // // /** // * @return the draggable element that initiate the drag operation (i.e. the // * clicked element) // */ // public Element getInitialDraggable() { // return initialDraggable; // } // // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class; // Path: sample/src/main/java/gwtquery/plugins/draggable/client/DraggableSample1.java import com.google.gwt.core.client.EntryPoint; import gwtquery.plugins.draggable.client.DraggableOptions.DragFunction; import gwtquery.plugins.draggable.client.events.DragContext; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable; /* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Simple sample * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class DraggableSample1 implements EntryPoint { private int startCounter = 0; private int dragCounter = 0; private int stopCounter = 0; public void onModuleLoad() { // simpleDraggable div DraggableOptions o = createOptionsForSimpleDraggable(); $("#simpleDraggable").as(Draggable).draggable(o); } private DraggableOptions createOptionsForSimpleDraggable() { DraggableOptions o = new DraggableOptions(); o.setOnDragStart(new DragFunction() {
public void f(DragContext context) {
ArcBees/gwtquery-draggable-plugin
sample/src/main/java/gwtquery/plugins/draggable/client/DraggableOptionsPanel.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum AxisOption { // /** // * No axis constraint // */ // NONE, // // /** // * X_AXIS constraints the drag operation to the horizontal axis // */ // X_AXIS, // // /** // * Y_AXIS constraints the drag operation to the vertical axis // */ // Y_AXIS; // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static class CursorAt { // // private Integer bottom; // private Integer left; // private Integer right; // private Integer top; // // /** // * Specify coordinates by giving one or two parameters. If you define more // * than two argument, the bottom parameter has priority over the top // * parameter and the right parameter has priority over left parameter // * // * @param top // * @param left // * @param bottom // * @param right // */ // public CursorAt(Integer top, Integer left, Integer bottom, Integer right) { // if (bottom != null) { // this.bottom = bottom; // } else if (top != null) { // this.top = top; // } // // if (right != null) { // this.right = right; // } else if (left != null) { // this.left = left; // } // } // // public Integer getBottom() { // return bottom; // } // // public Integer getLeft() { // return left; // } // // public Integer getRight() { // return right; // } // // public Integer getTop() { // return top; // } // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum HelperType { // /** // * CLONE : a clone of the original element will be used as dragging display // */ // CLONE { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original).clone(); // } // }, // // /** // * ORIGINAL : an other element will be used as dragging display // */ // ELEMENT { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return helperFromOptions; // } // }, // // /** // * ORIGINAL : the original element will be used as dragging display // */ // ORIGINAL { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original); // } // }; // // public abstract GQuery createHelper(Element original, // GQuery helperFromOptions); // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum RevertOption { // /** // * ALWAYS : the helper will return to its start position when dragging // * stops. // */ // ALWAYS, // // /** // * NEVER : the draggable will not return to its start position when dragging // * stops. // */ // NEVER, // // /** // * ON_INVALID_DROP :revert will only occur if the draggable has not been // * dropped (useful with droppable plug-in) // */ // ON_INVALID_DROP, // // /** // * ON_VALID_DROP : revert will only occur if the draggable has been dropped // * (useful with droppable plug-in) // */ // ON_VALID_DROP; // // public boolean doRevert(boolean dropped) { // return this == ALWAYS || (this == ON_INVALID_DROP && !dropped) // || (this == ON_VALID_DROP && dropped); // } // }
import java.util.HashMap; import java.util.Map; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.query.client.GQuery; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import gwtquery.plugins.draggable.client.DraggableOptions.AxisOption; import gwtquery.plugins.draggable.client.DraggableOptions.CursorAt; import gwtquery.plugins.draggable.client.DraggableOptions.HelperType; import gwtquery.plugins.draggable.client.DraggableOptions.RevertOption; import static com.google.gwt.query.client.GQuery.$;
package gwtquery.plugins.draggable.client; public class DraggableOptionsPanel extends Composite { @UiTemplate(value = "DraggableOptionsPanel.ui.xml") interface DraggableOptionsPanelUiBinder extends UiBinder<Widget, DraggableOptionsPanel> { } private static DraggableOptionsPanelUiBinder uiBinder = GWT .create(DraggableOptionsPanelUiBinder.class); private static Map<String, Object> contaimentOptions;
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum AxisOption { // /** // * No axis constraint // */ // NONE, // // /** // * X_AXIS constraints the drag operation to the horizontal axis // */ // X_AXIS, // // /** // * Y_AXIS constraints the drag operation to the vertical axis // */ // Y_AXIS; // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static class CursorAt { // // private Integer bottom; // private Integer left; // private Integer right; // private Integer top; // // /** // * Specify coordinates by giving one or two parameters. If you define more // * than two argument, the bottom parameter has priority over the top // * parameter and the right parameter has priority over left parameter // * // * @param top // * @param left // * @param bottom // * @param right // */ // public CursorAt(Integer top, Integer left, Integer bottom, Integer right) { // if (bottom != null) { // this.bottom = bottom; // } else if (top != null) { // this.top = top; // } // // if (right != null) { // this.right = right; // } else if (left != null) { // this.left = left; // } // } // // public Integer getBottom() { // return bottom; // } // // public Integer getLeft() { // return left; // } // // public Integer getRight() { // return right; // } // // public Integer getTop() { // return top; // } // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum HelperType { // /** // * CLONE : a clone of the original element will be used as dragging display // */ // CLONE { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original).clone(); // } // }, // // /** // * ORIGINAL : an other element will be used as dragging display // */ // ELEMENT { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return helperFromOptions; // } // }, // // /** // * ORIGINAL : the original element will be used as dragging display // */ // ORIGINAL { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original); // } // }; // // public abstract GQuery createHelper(Element original, // GQuery helperFromOptions); // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum RevertOption { // /** // * ALWAYS : the helper will return to its start position when dragging // * stops. // */ // ALWAYS, // // /** // * NEVER : the draggable will not return to its start position when dragging // * stops. // */ // NEVER, // // /** // * ON_INVALID_DROP :revert will only occur if the draggable has not been // * dropped (useful with droppable plug-in) // */ // ON_INVALID_DROP, // // /** // * ON_VALID_DROP : revert will only occur if the draggable has been dropped // * (useful with droppable plug-in) // */ // ON_VALID_DROP; // // public boolean doRevert(boolean dropped) { // return this == ALWAYS || (this == ON_INVALID_DROP && !dropped) // || (this == ON_VALID_DROP && dropped); // } // } // Path: sample/src/main/java/gwtquery/plugins/draggable/client/DraggableOptionsPanel.java import java.util.HashMap; import java.util.Map; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.query.client.GQuery; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import gwtquery.plugins.draggable.client.DraggableOptions.AxisOption; import gwtquery.plugins.draggable.client.DraggableOptions.CursorAt; import gwtquery.plugins.draggable.client.DraggableOptions.HelperType; import gwtquery.plugins.draggable.client.DraggableOptions.RevertOption; import static com.google.gwt.query.client.GQuery.$; package gwtquery.plugins.draggable.client; public class DraggableOptionsPanel extends Composite { @UiTemplate(value = "DraggableOptionsPanel.ui.xml") interface DraggableOptionsPanelUiBinder extends UiBinder<Widget, DraggableOptionsPanel> { } private static DraggableOptionsPanelUiBinder uiBinder = GWT .create(DraggableOptionsPanelUiBinder.class); private static Map<String, Object> contaimentOptions;
private static Map<String, CursorAt> cursorAtOptions;
ArcBees/gwtquery-draggable-plugin
sample/src/main/java/gwtquery/plugins/draggable/client/DraggableOptionsPanel.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum AxisOption { // /** // * No axis constraint // */ // NONE, // // /** // * X_AXIS constraints the drag operation to the horizontal axis // */ // X_AXIS, // // /** // * Y_AXIS constraints the drag operation to the vertical axis // */ // Y_AXIS; // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static class CursorAt { // // private Integer bottom; // private Integer left; // private Integer right; // private Integer top; // // /** // * Specify coordinates by giving one or two parameters. If you define more // * than two argument, the bottom parameter has priority over the top // * parameter and the right parameter has priority over left parameter // * // * @param top // * @param left // * @param bottom // * @param right // */ // public CursorAt(Integer top, Integer left, Integer bottom, Integer right) { // if (bottom != null) { // this.bottom = bottom; // } else if (top != null) { // this.top = top; // } // // if (right != null) { // this.right = right; // } else if (left != null) { // this.left = left; // } // } // // public Integer getBottom() { // return bottom; // } // // public Integer getLeft() { // return left; // } // // public Integer getRight() { // return right; // } // // public Integer getTop() { // return top; // } // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum HelperType { // /** // * CLONE : a clone of the original element will be used as dragging display // */ // CLONE { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original).clone(); // } // }, // // /** // * ORIGINAL : an other element will be used as dragging display // */ // ELEMENT { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return helperFromOptions; // } // }, // // /** // * ORIGINAL : the original element will be used as dragging display // */ // ORIGINAL { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original); // } // }; // // public abstract GQuery createHelper(Element original, // GQuery helperFromOptions); // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum RevertOption { // /** // * ALWAYS : the helper will return to its start position when dragging // * stops. // */ // ALWAYS, // // /** // * NEVER : the draggable will not return to its start position when dragging // * stops. // */ // NEVER, // // /** // * ON_INVALID_DROP :revert will only occur if the draggable has not been // * dropped (useful with droppable plug-in) // */ // ON_INVALID_DROP, // // /** // * ON_VALID_DROP : revert will only occur if the draggable has been dropped // * (useful with droppable plug-in) // */ // ON_VALID_DROP; // // public boolean doRevert(boolean dropped) { // return this == ALWAYS || (this == ON_INVALID_DROP && !dropped) // || (this == ON_VALID_DROP && dropped); // } // }
import java.util.HashMap; import java.util.Map; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.query.client.GQuery; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import gwtquery.plugins.draggable.client.DraggableOptions.AxisOption; import gwtquery.plugins.draggable.client.DraggableOptions.CursorAt; import gwtquery.plugins.draggable.client.DraggableOptions.HelperType; import gwtquery.plugins.draggable.client.DraggableOptions.RevertOption; import static com.google.gwt.query.client.GQuery.$;
@UiField CheckBox handleCheckBox; @UiField TextBox opacityBox; @UiField CheckBox scrollCheckBox; @UiField TextBox scrollSensivityBox; @UiField TextBox scrollSpeedBox; @UiField ListBox revertListBox; @UiField TextBox revertDurationTextBox; public DraggableOptionsPanel(Element draggable) { this.draggable = draggable; initWidget(uiBinder.createAndBindUi(this)); Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { init(); } }); } @UiHandler(value = "axisListBox") public void onAxisChange(ChangeEvent e) {
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum AxisOption { // /** // * No axis constraint // */ // NONE, // // /** // * X_AXIS constraints the drag operation to the horizontal axis // */ // X_AXIS, // // /** // * Y_AXIS constraints the drag operation to the vertical axis // */ // Y_AXIS; // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static class CursorAt { // // private Integer bottom; // private Integer left; // private Integer right; // private Integer top; // // /** // * Specify coordinates by giving one or two parameters. If you define more // * than two argument, the bottom parameter has priority over the top // * parameter and the right parameter has priority over left parameter // * // * @param top // * @param left // * @param bottom // * @param right // */ // public CursorAt(Integer top, Integer left, Integer bottom, Integer right) { // if (bottom != null) { // this.bottom = bottom; // } else if (top != null) { // this.top = top; // } // // if (right != null) { // this.right = right; // } else if (left != null) { // this.left = left; // } // } // // public Integer getBottom() { // return bottom; // } // // public Integer getLeft() { // return left; // } // // public Integer getRight() { // return right; // } // // public Integer getTop() { // return top; // } // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum HelperType { // /** // * CLONE : a clone of the original element will be used as dragging display // */ // CLONE { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original).clone(); // } // }, // // /** // * ORIGINAL : an other element will be used as dragging display // */ // ELEMENT { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return helperFromOptions; // } // }, // // /** // * ORIGINAL : the original element will be used as dragging display // */ // ORIGINAL { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original); // } // }; // // public abstract GQuery createHelper(Element original, // GQuery helperFromOptions); // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum RevertOption { // /** // * ALWAYS : the helper will return to its start position when dragging // * stops. // */ // ALWAYS, // // /** // * NEVER : the draggable will not return to its start position when dragging // * stops. // */ // NEVER, // // /** // * ON_INVALID_DROP :revert will only occur if the draggable has not been // * dropped (useful with droppable plug-in) // */ // ON_INVALID_DROP, // // /** // * ON_VALID_DROP : revert will only occur if the draggable has been dropped // * (useful with droppable plug-in) // */ // ON_VALID_DROP; // // public boolean doRevert(boolean dropped) { // return this == ALWAYS || (this == ON_INVALID_DROP && !dropped) // || (this == ON_VALID_DROP && dropped); // } // } // Path: sample/src/main/java/gwtquery/plugins/draggable/client/DraggableOptionsPanel.java import java.util.HashMap; import java.util.Map; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.query.client.GQuery; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import gwtquery.plugins.draggable.client.DraggableOptions.AxisOption; import gwtquery.plugins.draggable.client.DraggableOptions.CursorAt; import gwtquery.plugins.draggable.client.DraggableOptions.HelperType; import gwtquery.plugins.draggable.client.DraggableOptions.RevertOption; import static com.google.gwt.query.client.GQuery.$; @UiField CheckBox handleCheckBox; @UiField TextBox opacityBox; @UiField CheckBox scrollCheckBox; @UiField TextBox scrollSensivityBox; @UiField TextBox scrollSpeedBox; @UiField ListBox revertListBox; @UiField TextBox revertDurationTextBox; public DraggableOptionsPanel(Element draggable) { this.draggable = draggable; initWidget(uiBinder.createAndBindUi(this)); Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { init(); } }); } @UiHandler(value = "axisListBox") public void onAxisChange(ChangeEvent e) {
AxisOption axis = AxisOption.valueOf(axisListBox.getValue(axisListBox
ArcBees/gwtquery-draggable-plugin
sample/src/main/java/gwtquery/plugins/draggable/client/DraggableOptionsPanel.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum AxisOption { // /** // * No axis constraint // */ // NONE, // // /** // * X_AXIS constraints the drag operation to the horizontal axis // */ // X_AXIS, // // /** // * Y_AXIS constraints the drag operation to the vertical axis // */ // Y_AXIS; // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static class CursorAt { // // private Integer bottom; // private Integer left; // private Integer right; // private Integer top; // // /** // * Specify coordinates by giving one or two parameters. If you define more // * than two argument, the bottom parameter has priority over the top // * parameter and the right parameter has priority over left parameter // * // * @param top // * @param left // * @param bottom // * @param right // */ // public CursorAt(Integer top, Integer left, Integer bottom, Integer right) { // if (bottom != null) { // this.bottom = bottom; // } else if (top != null) { // this.top = top; // } // // if (right != null) { // this.right = right; // } else if (left != null) { // this.left = left; // } // } // // public Integer getBottom() { // return bottom; // } // // public Integer getLeft() { // return left; // } // // public Integer getRight() { // return right; // } // // public Integer getTop() { // return top; // } // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum HelperType { // /** // * CLONE : a clone of the original element will be used as dragging display // */ // CLONE { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original).clone(); // } // }, // // /** // * ORIGINAL : an other element will be used as dragging display // */ // ELEMENT { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return helperFromOptions; // } // }, // // /** // * ORIGINAL : the original element will be used as dragging display // */ // ORIGINAL { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original); // } // }; // // public abstract GQuery createHelper(Element original, // GQuery helperFromOptions); // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum RevertOption { // /** // * ALWAYS : the helper will return to its start position when dragging // * stops. // */ // ALWAYS, // // /** // * NEVER : the draggable will not return to its start position when dragging // * stops. // */ // NEVER, // // /** // * ON_INVALID_DROP :revert will only occur if the draggable has not been // * dropped (useful with droppable plug-in) // */ // ON_INVALID_DROP, // // /** // * ON_VALID_DROP : revert will only occur if the draggable has been dropped // * (useful with droppable plug-in) // */ // ON_VALID_DROP; // // public boolean doRevert(boolean dropped) { // return this == ALWAYS || (this == ON_INVALID_DROP && !dropped) // || (this == ON_VALID_DROP && dropped); // } // }
import java.util.HashMap; import java.util.Map; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.query.client.GQuery; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import gwtquery.plugins.draggable.client.DraggableOptions.AxisOption; import gwtquery.plugins.draggable.client.DraggableOptions.CursorAt; import gwtquery.plugins.draggable.client.DraggableOptions.HelperType; import gwtquery.plugins.draggable.client.DraggableOptions.RevertOption; import static com.google.gwt.query.client.GQuery.$;
public void onDisabledChange(ValueChangeEvent<Boolean> e) { getOptions().setDisabled(e.getValue()); } @UiHandler(value = "distanceBox") public void onDistanceChange(ValueChangeEvent<String> e) { Integer distance; try { distance = new Integer(e.getValue()); } catch (NumberFormatException ex) { Window.alert("Please specify a correct number for distance"); return; } getOptions().setDistance(distance); } @UiHandler(value = "gridListBox") public void onGridChange(ChangeEvent e) { String grid = gridListBox.getValue(gridListBox.getSelectedIndex()); if ("None".equals(grid)) { getOptions().setGrid(null); } else { String[] dimension = grid.split(","); getOptions().setGrid( new int[]{new Integer(dimension[0]), new Integer(dimension[1])}); } } @UiHandler(value = "helperListBox") public void onHelperChange(ChangeEvent e) {
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum AxisOption { // /** // * No axis constraint // */ // NONE, // // /** // * X_AXIS constraints the drag operation to the horizontal axis // */ // X_AXIS, // // /** // * Y_AXIS constraints the drag operation to the vertical axis // */ // Y_AXIS; // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static class CursorAt { // // private Integer bottom; // private Integer left; // private Integer right; // private Integer top; // // /** // * Specify coordinates by giving one or two parameters. If you define more // * than two argument, the bottom parameter has priority over the top // * parameter and the right parameter has priority over left parameter // * // * @param top // * @param left // * @param bottom // * @param right // */ // public CursorAt(Integer top, Integer left, Integer bottom, Integer right) { // if (bottom != null) { // this.bottom = bottom; // } else if (top != null) { // this.top = top; // } // // if (right != null) { // this.right = right; // } else if (left != null) { // this.left = left; // } // } // // public Integer getBottom() { // return bottom; // } // // public Integer getLeft() { // return left; // } // // public Integer getRight() { // return right; // } // // public Integer getTop() { // return top; // } // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum HelperType { // /** // * CLONE : a clone of the original element will be used as dragging display // */ // CLONE { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original).clone(); // } // }, // // /** // * ORIGINAL : an other element will be used as dragging display // */ // ELEMENT { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return helperFromOptions; // } // }, // // /** // * ORIGINAL : the original element will be used as dragging display // */ // ORIGINAL { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original); // } // }; // // public abstract GQuery createHelper(Element original, // GQuery helperFromOptions); // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum RevertOption { // /** // * ALWAYS : the helper will return to its start position when dragging // * stops. // */ // ALWAYS, // // /** // * NEVER : the draggable will not return to its start position when dragging // * stops. // */ // NEVER, // // /** // * ON_INVALID_DROP :revert will only occur if the draggable has not been // * dropped (useful with droppable plug-in) // */ // ON_INVALID_DROP, // // /** // * ON_VALID_DROP : revert will only occur if the draggable has been dropped // * (useful with droppable plug-in) // */ // ON_VALID_DROP; // // public boolean doRevert(boolean dropped) { // return this == ALWAYS || (this == ON_INVALID_DROP && !dropped) // || (this == ON_VALID_DROP && dropped); // } // } // Path: sample/src/main/java/gwtquery/plugins/draggable/client/DraggableOptionsPanel.java import java.util.HashMap; import java.util.Map; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.query.client.GQuery; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import gwtquery.plugins.draggable.client.DraggableOptions.AxisOption; import gwtquery.plugins.draggable.client.DraggableOptions.CursorAt; import gwtquery.plugins.draggable.client.DraggableOptions.HelperType; import gwtquery.plugins.draggable.client.DraggableOptions.RevertOption; import static com.google.gwt.query.client.GQuery.$; public void onDisabledChange(ValueChangeEvent<Boolean> e) { getOptions().setDisabled(e.getValue()); } @UiHandler(value = "distanceBox") public void onDistanceChange(ValueChangeEvent<String> e) { Integer distance; try { distance = new Integer(e.getValue()); } catch (NumberFormatException ex) { Window.alert("Please specify a correct number for distance"); return; } getOptions().setDistance(distance); } @UiHandler(value = "gridListBox") public void onGridChange(ChangeEvent e) { String grid = gridListBox.getValue(gridListBox.getSelectedIndex()); if ("None".equals(grid)) { getOptions().setGrid(null); } else { String[] dimension = grid.split(","); getOptions().setGrid( new int[]{new Integer(dimension[0]), new Integer(dimension[1])}); } } @UiHandler(value = "helperListBox") public void onHelperChange(ChangeEvent e) {
HelperType type = HelperType.valueOf(helperListBox.getValue(helperListBox
ArcBees/gwtquery-draggable-plugin
sample/src/main/java/gwtquery/plugins/draggable/client/DraggableOptionsPanel.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum AxisOption { // /** // * No axis constraint // */ // NONE, // // /** // * X_AXIS constraints the drag operation to the horizontal axis // */ // X_AXIS, // // /** // * Y_AXIS constraints the drag operation to the vertical axis // */ // Y_AXIS; // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static class CursorAt { // // private Integer bottom; // private Integer left; // private Integer right; // private Integer top; // // /** // * Specify coordinates by giving one or two parameters. If you define more // * than two argument, the bottom parameter has priority over the top // * parameter and the right parameter has priority over left parameter // * // * @param top // * @param left // * @param bottom // * @param right // */ // public CursorAt(Integer top, Integer left, Integer bottom, Integer right) { // if (bottom != null) { // this.bottom = bottom; // } else if (top != null) { // this.top = top; // } // // if (right != null) { // this.right = right; // } else if (left != null) { // this.left = left; // } // } // // public Integer getBottom() { // return bottom; // } // // public Integer getLeft() { // return left; // } // // public Integer getRight() { // return right; // } // // public Integer getTop() { // return top; // } // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum HelperType { // /** // * CLONE : a clone of the original element will be used as dragging display // */ // CLONE { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original).clone(); // } // }, // // /** // * ORIGINAL : an other element will be used as dragging display // */ // ELEMENT { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return helperFromOptions; // } // }, // // /** // * ORIGINAL : the original element will be used as dragging display // */ // ORIGINAL { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original); // } // }; // // public abstract GQuery createHelper(Element original, // GQuery helperFromOptions); // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum RevertOption { // /** // * ALWAYS : the helper will return to its start position when dragging // * stops. // */ // ALWAYS, // // /** // * NEVER : the draggable will not return to its start position when dragging // * stops. // */ // NEVER, // // /** // * ON_INVALID_DROP :revert will only occur if the draggable has not been // * dropped (useful with droppable plug-in) // */ // ON_INVALID_DROP, // // /** // * ON_VALID_DROP : revert will only occur if the draggable has been dropped // * (useful with droppable plug-in) // */ // ON_VALID_DROP; // // public boolean doRevert(boolean dropped) { // return this == ALWAYS || (this == ON_INVALID_DROP && !dropped) // || (this == ON_VALID_DROP && dropped); // } // }
import java.util.HashMap; import java.util.Map; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.query.client.GQuery; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import gwtquery.plugins.draggable.client.DraggableOptions.AxisOption; import gwtquery.plugins.draggable.client.DraggableOptions.CursorAt; import gwtquery.plugins.draggable.client.DraggableOptions.HelperType; import gwtquery.plugins.draggable.client.DraggableOptions.RevertOption; import static com.google.gwt.query.client.GQuery.$;
return; } } if (opacity != null && opacity > 1) { Window.alert("Opacity must be below than 1."); return; } getOptions().setOpacity(opacity); } @UiHandler(value = "revertDurationTextBox") public void onRevertDurationChange(ValueChangeEvent<String> e) { String revertDuration = e.getValue(); Integer revertDurationInt; if (revertDuration == null || revertDuration.length() == 0) { revertDurationInt = null; } else { try { revertDurationInt = new Integer(e.getValue()); } catch (NumberFormatException ex) { Window.alert("Please specify a correct number for the revert duration"); return; } } getOptions().setRevertDuration(revertDurationInt); } @UiHandler(value = "revertListBox") public void onRevertChange(ChangeEvent e) { String revert = revertListBox.getValue(revertListBox.getSelectedIndex());
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum AxisOption { // /** // * No axis constraint // */ // NONE, // // /** // * X_AXIS constraints the drag operation to the horizontal axis // */ // X_AXIS, // // /** // * Y_AXIS constraints the drag operation to the vertical axis // */ // Y_AXIS; // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static class CursorAt { // // private Integer bottom; // private Integer left; // private Integer right; // private Integer top; // // /** // * Specify coordinates by giving one or two parameters. If you define more // * than two argument, the bottom parameter has priority over the top // * parameter and the right parameter has priority over left parameter // * // * @param top // * @param left // * @param bottom // * @param right // */ // public CursorAt(Integer top, Integer left, Integer bottom, Integer right) { // if (bottom != null) { // this.bottom = bottom; // } else if (top != null) { // this.top = top; // } // // if (right != null) { // this.right = right; // } else if (left != null) { // this.left = left; // } // } // // public Integer getBottom() { // return bottom; // } // // public Integer getLeft() { // return left; // } // // public Integer getRight() { // return right; // } // // public Integer getTop() { // return top; // } // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum HelperType { // /** // * CLONE : a clone of the original element will be used as dragging display // */ // CLONE { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original).clone(); // } // }, // // /** // * ORIGINAL : an other element will be used as dragging display // */ // ELEMENT { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return helperFromOptions; // } // }, // // /** // * ORIGINAL : the original element will be used as dragging display // */ // ORIGINAL { // @Override // public GQuery createHelper(Element original, GQuery helperFromOptions) { // return $(original); // } // }; // // public abstract GQuery createHelper(Element original, // GQuery helperFromOptions); // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum RevertOption { // /** // * ALWAYS : the helper will return to its start position when dragging // * stops. // */ // ALWAYS, // // /** // * NEVER : the draggable will not return to its start position when dragging // * stops. // */ // NEVER, // // /** // * ON_INVALID_DROP :revert will only occur if the draggable has not been // * dropped (useful with droppable plug-in) // */ // ON_INVALID_DROP, // // /** // * ON_VALID_DROP : revert will only occur if the draggable has been dropped // * (useful with droppable plug-in) // */ // ON_VALID_DROP; // // public boolean doRevert(boolean dropped) { // return this == ALWAYS || (this == ON_INVALID_DROP && !dropped) // || (this == ON_VALID_DROP && dropped); // } // } // Path: sample/src/main/java/gwtquery/plugins/draggable/client/DraggableOptionsPanel.java import java.util.HashMap; import java.util.Map; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.query.client.GQuery; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import gwtquery.plugins.draggable.client.DraggableOptions.AxisOption; import gwtquery.plugins.draggable.client.DraggableOptions.CursorAt; import gwtquery.plugins.draggable.client.DraggableOptions.HelperType; import gwtquery.plugins.draggable.client.DraggableOptions.RevertOption; import static com.google.gwt.query.client.GQuery.$; return; } } if (opacity != null && opacity > 1) { Window.alert("Opacity must be below than 1."); return; } getOptions().setOpacity(opacity); } @UiHandler(value = "revertDurationTextBox") public void onRevertDurationChange(ValueChangeEvent<String> e) { String revertDuration = e.getValue(); Integer revertDurationInt; if (revertDuration == null || revertDuration.length() == 0) { revertDurationInt = null; } else { try { revertDurationInt = new Integer(e.getValue()); } catch (NumberFormatException ex) { Window.alert("Please specify a correct number for the revert duration"); return; } } getOptions().setRevertDuration(revertDurationInt); } @UiHandler(value = "revertListBox") public void onRevertChange(ChangeEvent e) { String revert = revertListBox.getValue(revertListBox.getSelectedIndex());
getOptions().setRevert(RevertOption.valueOf(revert));
ArcBees/gwtquery-draggable-plugin
plugin/src/main/java/gwtquery/plugins/draggable/client/DragAndDropManager.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/events/DragContext.java // public class DragContext { // // static final String VALUE_KEY = "__dragAndDropCellAssociatedValue"; // // private Element draggable; // // private List<Element> selectedDraggables; // // private Element initialDraggable; // // // /** // * Constructor // * // * @param draggable the draggable element // */ // public DragContext(Element draggable, Element initialDraggable, // List<Element> selectedDraggable) { // this.draggable = draggable; // this.selectedDraggables = selectedDraggable; // this.initialDraggable = initialDraggable; // } // // public DragContext(DragContext ctx) { // this(ctx.getDraggable(), ctx.getInitialDraggable(), ctx // .getSelectedDraggables()); // } // // /** // * @return the draggable DOM element // */ // public Element getDraggable() { // return draggable; // } // // /** // * This method allows getting the data object linked to the draggable element // * (a cell) in the context of CellWidget.It return the data object being // * rendered by the dragging cell. Return null if we are not in the context of // * an drag and drop cell widget. // * // * @param <T> the class of the data // * @return // */ // @SuppressWarnings("unchecked") // public <T> T getDraggableData() { // return (T) $(getDraggable()).data(VALUE_KEY); // } // // /** // * This method return the widget associated to the draggable DOM element if it // * exist. It returns null otherwise. // */ // public DraggableWidget<?> getDraggableWidget() { // if (getDraggable() != null) { // return DraggableWidget.get(getDraggable()); // } // return null; // } // // /** // * @return the DOM element used for dragging display // */ // public Element getHelper() { // DraggableHandler handler = DraggableHandler.getInstance(draggable); // // if (handler.getHelper() != null) { // return handler.getHelper().get(0); // } // return null; // } // // /** // * @return the {@link Offset} of the helper element. // */ // public Offset getHelperPosition() { // return DraggableHandler.getInstance(draggable).getPosition(); // } // // /** // * @return the list of selected draggables. // */ // public List<Element> getSelectedDraggables() { // return selectedDraggables; // } // // /** // * @return the draggable element that initiate the drag operation (i.e. the // * clicked element) // */ // public Element getInitialDraggable() { // return initialDraggable; // } // // // }
import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Element; import com.google.gwt.query.client.plugins.events.GqEvent; import gwtquery.plugins.draggable.client.events.DragContext; import java.util.Collection;
/* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * The goal of this class is to manage the interactions between draggable and droppable objects. * This implementation specifies the interface needed by this kind of manager but do nothing. * * @author Julien Dramaix (julien.dramaix@gmail.com, @jdramaix) */ public class DragAndDropManager { private static DragAndDropManager INSTANCE = GWT .create(DragAndDropManager.class); /** * return the instance of the manager * * @return */ public static DragAndDropManager getInstance() { return INSTANCE; } /** * Link a droppable with the specified scope <code>scope</code> * * @param droppable * @param scope */ public void addDroppable(Element droppable, String scope) { } /** * Method called when the draggable is being dragged * * @param draggable * @param e */
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/events/DragContext.java // public class DragContext { // // static final String VALUE_KEY = "__dragAndDropCellAssociatedValue"; // // private Element draggable; // // private List<Element> selectedDraggables; // // private Element initialDraggable; // // // /** // * Constructor // * // * @param draggable the draggable element // */ // public DragContext(Element draggable, Element initialDraggable, // List<Element> selectedDraggable) { // this.draggable = draggable; // this.selectedDraggables = selectedDraggable; // this.initialDraggable = initialDraggable; // } // // public DragContext(DragContext ctx) { // this(ctx.getDraggable(), ctx.getInitialDraggable(), ctx // .getSelectedDraggables()); // } // // /** // * @return the draggable DOM element // */ // public Element getDraggable() { // return draggable; // } // // /** // * This method allows getting the data object linked to the draggable element // * (a cell) in the context of CellWidget.It return the data object being // * rendered by the dragging cell. Return null if we are not in the context of // * an drag and drop cell widget. // * // * @param <T> the class of the data // * @return // */ // @SuppressWarnings("unchecked") // public <T> T getDraggableData() { // return (T) $(getDraggable()).data(VALUE_KEY); // } // // /** // * This method return the widget associated to the draggable DOM element if it // * exist. It returns null otherwise. // */ // public DraggableWidget<?> getDraggableWidget() { // if (getDraggable() != null) { // return DraggableWidget.get(getDraggable()); // } // return null; // } // // /** // * @return the DOM element used for dragging display // */ // public Element getHelper() { // DraggableHandler handler = DraggableHandler.getInstance(draggable); // // if (handler.getHelper() != null) { // return handler.getHelper().get(0); // } // return null; // } // // /** // * @return the {@link Offset} of the helper element. // */ // public Offset getHelperPosition() { // return DraggableHandler.getInstance(draggable).getPosition(); // } // // /** // * @return the list of selected draggables. // */ // public List<Element> getSelectedDraggables() { // return selectedDraggables; // } // // /** // * @return the draggable element that initiate the drag operation (i.e. the // * clicked element) // */ // public Element getInitialDraggable() { // return initialDraggable; // } // // // } // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DragAndDropManager.java import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Element; import com.google.gwt.query.client.plugins.events.GqEvent; import gwtquery.plugins.draggable.client.events.DragContext; import java.util.Collection; /* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * The goal of this class is to manage the interactions between draggable and droppable objects. * This implementation specifies the interface needed by this kind of manager but do nothing. * * @author Julien Dramaix (julien.dramaix@gmail.com, @jdramaix) */ public class DragAndDropManager { private static DragAndDropManager INSTANCE = GWT .create(DragAndDropManager.class); /** * return the instance of the manager * * @return */ public static DragAndDropManager getInstance() { return INSTANCE; } /** * Link a droppable with the specified scope <code>scope</code> * * @param droppable * @param scope */ public void addDroppable(Element droppable, String scope) { } /** * Method called when the draggable is being dragged * * @param draggable * @param e */
public void drag(DragContext ctx, GqEvent e) {
ArcBees/gwtquery-draggable-plugin
sample/src/main/java/gwtquery/plugins/draggable/client/MultiDragSample.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum GroupingMode { // /** // * place the helper under the initial current helper // */ // DOWN, // /** // * place the helper to the left of the initial current helper // */ // LEFT, // /** // * No grouping // */ // NONE, // /** // * place the helper to the right of the initial current helper // */ // RIGHT, // /** // * place the helper above the initial current helper // */ // UP; // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class;
import com.google.gwt.core.client.EntryPoint; import gwtquery.plugins.draggable.client.DraggableOptions.GroupingMode; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable;
/* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Simple sample * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class MultiDragSample implements EntryPoint { public void onModuleLoad() {
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum GroupingMode { // /** // * place the helper under the initial current helper // */ // DOWN, // /** // * place the helper to the left of the initial current helper // */ // LEFT, // /** // * No grouping // */ // NONE, // /** // * place the helper to the right of the initial current helper // */ // RIGHT, // /** // * place the helper above the initial current helper // */ // UP; // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class; // Path: sample/src/main/java/gwtquery/plugins/draggable/client/MultiDragSample.java import com.google.gwt.core.client.EntryPoint; import gwtquery.plugins.draggable.client.DraggableOptions.GroupingMode; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable; /* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Simple sample * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class MultiDragSample implements EntryPoint { public void onModuleLoad() {
$(".multi-draggable").as(Draggable).draggable(createOptions(null, "basicScope", true));
ArcBees/gwtquery-draggable-plugin
sample/src/main/java/gwtquery/plugins/draggable/client/MultiDragSample.java
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum GroupingMode { // /** // * place the helper under the initial current helper // */ // DOWN, // /** // * place the helper to the left of the initial current helper // */ // LEFT, // /** // * No grouping // */ // NONE, // /** // * place the helper to the right of the initial current helper // */ // RIGHT, // /** // * place the helper above the initial current helper // */ // UP; // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class;
import com.google.gwt.core.client.EntryPoint; import gwtquery.plugins.draggable.client.DraggableOptions.GroupingMode; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable;
/* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Simple sample * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class MultiDragSample implements EntryPoint { public void onModuleLoad() { $(".multi-draggable").as(Draggable).draggable(createOptions(null, "basicScope", true)); $("#up").as(Draggable).draggable(
// Path: plugin/src/main/java/gwtquery/plugins/draggable/client/DraggableOptions.java // public static enum GroupingMode { // /** // * place the helper under the initial current helper // */ // DOWN, // /** // * place the helper to the left of the initial current helper // */ // LEFT, // /** // * No grouping // */ // NONE, // /** // * place the helper to the right of the initial current helper // */ // RIGHT, // /** // * place the helper above the initial current helper // */ // UP; // // } // // Path: plugin/src/main/java/gwtquery/plugins/draggable/client/Draggable.java // public static final Class<Draggable> Draggable = Draggable.class; // Path: sample/src/main/java/gwtquery/plugins/draggable/client/MultiDragSample.java import com.google.gwt.core.client.EntryPoint; import gwtquery.plugins.draggable.client.DraggableOptions.GroupingMode; import static com.google.gwt.query.client.GQuery.$; import static gwtquery.plugins.draggable.client.Draggable.Draggable; /* * Copyright 2010 The gwtquery plugins team. * * 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 gwtquery.plugins.draggable.client; /** * Simple sample * * @author Julien Dramaix (julien.dramaix@gmail.com) */ public class MultiDragSample implements EntryPoint { public void onModuleLoad() { $(".multi-draggable").as(Draggable).draggable(createOptions(null, "basicScope", true)); $("#up").as(Draggable).draggable(
createOptions(GroupingMode.UP, "group-position", true));
Demidong/ClockView
app/src/main/java/com/xd/demi/view/JazzyViewPager.java
// Path: app/src/main/java/com/xd/demi/utils/OutlineContainer.java // public class OutlineContainer extends FrameLayout implements Animatable // { // // private Paint mOutlinePaint; // // private boolean mIsRunning = false; // private long mStartTime; // private float mAlpha = 1.0f; // private static final long ANIMATION_DURATION = 500; // private static final long FRAME_DURATION = 1000 / 60; // private final Interpolator mInterpolator = new Interpolator() // { // public float getInterpolation(float t) // { // t -= 1.0f; // return t * t * t + 1.0f; // } // }; // // public OutlineContainer(Context context) // { // super(context); // init(); // } // // public OutlineContainer(Context context, AttributeSet attrs) // { // super(context, attrs); // init(); // } // // public OutlineContainer(Context context, AttributeSet attrs, int defStyle) // { // super(context, attrs, defStyle); // init(); // } // // private void init() // { // mOutlinePaint = new Paint(); // mOutlinePaint.setAntiAlias(true); // mOutlinePaint.setStrokeWidth(DensityUtils.dp2px(getResources(), 2)); // mOutlinePaint.setColor(getResources().getColor(R.color.holo_blue)); // mOutlinePaint.setStyle(Style.STROKE); // // int padding = DensityUtils.dp2px(getResources(), 10); // setPadding(padding, padding, padding, padding); // } // // @Override // protected void dispatchDraw(Canvas canvas) // { // super.dispatchDraw(canvas); // int offset = DensityUtils.dp2px(getResources(), 5); // if (mOutlinePaint.getColor() != JazzyViewPager.sOutlineColor) // { // mOutlinePaint.setColor(JazzyViewPager.sOutlineColor); // } // mOutlinePaint.setAlpha((int) (mAlpha * 255)); // Rect rect = new Rect(offset, offset, getMeasuredWidth() - offset, // getMeasuredHeight() - offset); // canvas.drawRect(rect, mOutlinePaint); // } // // public void setOutlineAlpha(float alpha) // { // mAlpha = alpha; // } // // @Override // public boolean isRunning() // { // return mIsRunning; // } // // @Override // public void start() // { // if (mIsRunning) // return; // mIsRunning = true; // mStartTime = AnimationUtils.currentAnimationTimeMillis(); // post(mUpdater); // } // // @Override // public void stop() // { // if (!mIsRunning) // return; // mIsRunning = false; // } // // private final Runnable mUpdater = new Runnable() // { // @Override // public void run() // { // long now = AnimationUtils.currentAnimationTimeMillis(); // long duration = now - mStartTime; // if (duration >= ANIMATION_DURATION) // { // mAlpha = 0.0f; // invalidate(); // stop(); // return; // } else // { // mAlpha = mInterpolator.getInterpolation(1 - duration // / (float) ANIMATION_DURATION); // invalidate(); // } // postDelayed(mUpdater, FRAME_DURATION); // } // }; // // }
import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Camera; import android.graphics.Color; import android.graphics.Matrix; import android.os.Build; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import com.xd.demi.R; import com.xd.demi.utils.OutlineContainer; import com.nineoldandroids.view.ViewHelper; import java.util.HashMap; import java.util.LinkedHashMap;
{ mEnabled = enabled; } public void setFadeEnabled(boolean enabled) { mFadeEnabled = enabled; } public boolean getFadeEnabled() { return mFadeEnabled; } public void setOutlineEnabled(boolean enabled) { mOutlineEnabled = enabled; wrapWithOutlines(); } public void setOutlineColor(int color) { sOutlineColor = color; } private void wrapWithOutlines() { for (int i = 0; i < getChildCount(); i++) { View v = getChildAt(i);
// Path: app/src/main/java/com/xd/demi/utils/OutlineContainer.java // public class OutlineContainer extends FrameLayout implements Animatable // { // // private Paint mOutlinePaint; // // private boolean mIsRunning = false; // private long mStartTime; // private float mAlpha = 1.0f; // private static final long ANIMATION_DURATION = 500; // private static final long FRAME_DURATION = 1000 / 60; // private final Interpolator mInterpolator = new Interpolator() // { // public float getInterpolation(float t) // { // t -= 1.0f; // return t * t * t + 1.0f; // } // }; // // public OutlineContainer(Context context) // { // super(context); // init(); // } // // public OutlineContainer(Context context, AttributeSet attrs) // { // super(context, attrs); // init(); // } // // public OutlineContainer(Context context, AttributeSet attrs, int defStyle) // { // super(context, attrs, defStyle); // init(); // } // // private void init() // { // mOutlinePaint = new Paint(); // mOutlinePaint.setAntiAlias(true); // mOutlinePaint.setStrokeWidth(DensityUtils.dp2px(getResources(), 2)); // mOutlinePaint.setColor(getResources().getColor(R.color.holo_blue)); // mOutlinePaint.setStyle(Style.STROKE); // // int padding = DensityUtils.dp2px(getResources(), 10); // setPadding(padding, padding, padding, padding); // } // // @Override // protected void dispatchDraw(Canvas canvas) // { // super.dispatchDraw(canvas); // int offset = DensityUtils.dp2px(getResources(), 5); // if (mOutlinePaint.getColor() != JazzyViewPager.sOutlineColor) // { // mOutlinePaint.setColor(JazzyViewPager.sOutlineColor); // } // mOutlinePaint.setAlpha((int) (mAlpha * 255)); // Rect rect = new Rect(offset, offset, getMeasuredWidth() - offset, // getMeasuredHeight() - offset); // canvas.drawRect(rect, mOutlinePaint); // } // // public void setOutlineAlpha(float alpha) // { // mAlpha = alpha; // } // // @Override // public boolean isRunning() // { // return mIsRunning; // } // // @Override // public void start() // { // if (mIsRunning) // return; // mIsRunning = true; // mStartTime = AnimationUtils.currentAnimationTimeMillis(); // post(mUpdater); // } // // @Override // public void stop() // { // if (!mIsRunning) // return; // mIsRunning = false; // } // // private final Runnable mUpdater = new Runnable() // { // @Override // public void run() // { // long now = AnimationUtils.currentAnimationTimeMillis(); // long duration = now - mStartTime; // if (duration >= ANIMATION_DURATION) // { // mAlpha = 0.0f; // invalidate(); // stop(); // return; // } else // { // mAlpha = mInterpolator.getInterpolation(1 - duration // / (float) ANIMATION_DURATION); // invalidate(); // } // postDelayed(mUpdater, FRAME_DURATION); // } // }; // // } // Path: app/src/main/java/com/xd/demi/view/JazzyViewPager.java import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Camera; import android.graphics.Color; import android.graphics.Matrix; import android.os.Build; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import com.xd.demi.R; import com.xd.demi.utils.OutlineContainer; import com.nineoldandroids.view.ViewHelper; import java.util.HashMap; import java.util.LinkedHashMap; { mEnabled = enabled; } public void setFadeEnabled(boolean enabled) { mFadeEnabled = enabled; } public boolean getFadeEnabled() { return mFadeEnabled; } public void setOutlineEnabled(boolean enabled) { mOutlineEnabled = enabled; wrapWithOutlines(); } public void setOutlineColor(int color) { sOutlineColor = color; } private void wrapWithOutlines() { for (int i = 0; i < getChildCount(); i++) { View v = getChildAt(i);
if (!(v instanceof OutlineContainer))
Demidong/ClockView
app/src/main/java/com/xd/demi/activity/EventActivity.java
// Path: app/src/main/java/com/xd/demi/view/EventView.java // public class EventView extends View { // private Paint mPaint = new Paint(); // private float x = 0, y = 0; // private TextView textView; // // public EventView(Context context) { // this(context, null); // } // // public EventView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public EventView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // mPaint.setColor(Color.GREEN); // mPaint.setStyle(Paint.Style.STROKE); // mPaint.setStrokeWidth(2); // } // // @Override // public boolean onTouchEvent(MotionEvent event) { // System.out.println("View onTouchEvent..." + event.getAction()); // int action = event.getAction(); // switch (action) { // case MotionEvent.ACTION_DOWN: // x = event.getX(); // y = event.getY(); // invalidate(); // break; // case MotionEvent.ACTION_MOVE: // x = event.getX(); // y = event.getY(); // invalidate(); // break; // case MotionEvent.ACTION_UP: // x = 0; // y = 0; // invalidate(); // break; // } // return true; // } // // @Override // public boolean dispatchTouchEvent(MotionEvent event) { // System.out.println("View dispatchTouchEvent..." + event.getAction()); // return super.dispatchTouchEvent(event); // } // // @Override // protected void onDraw(Canvas canvas) { // super.onDraw(canvas); // canvas.drawLine(x, 0, x, y, mPaint); // canvas.drawLine(0, y, x, y, mPaint); // if (textView != null) { // textView.setText(getTextString()); // } // } // // private String getTextString() { // return "坐标 ( " + x + "," + y + " )"; // } // // public void setTextView(TextView textView) { // this.textView = textView; // } // // // }
import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.widget.TextView; import com.xd.demi.R; import com.xd.demi.view.EventView;
package com.xd.demi.activity; /** * Created by demi on 16/12/6. */ public class EventActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_event); TextView tv = (TextView) findViewById(R.id.tv);
// Path: app/src/main/java/com/xd/demi/view/EventView.java // public class EventView extends View { // private Paint mPaint = new Paint(); // private float x = 0, y = 0; // private TextView textView; // // public EventView(Context context) { // this(context, null); // } // // public EventView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public EventView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // mPaint.setColor(Color.GREEN); // mPaint.setStyle(Paint.Style.STROKE); // mPaint.setStrokeWidth(2); // } // // @Override // public boolean onTouchEvent(MotionEvent event) { // System.out.println("View onTouchEvent..." + event.getAction()); // int action = event.getAction(); // switch (action) { // case MotionEvent.ACTION_DOWN: // x = event.getX(); // y = event.getY(); // invalidate(); // break; // case MotionEvent.ACTION_MOVE: // x = event.getX(); // y = event.getY(); // invalidate(); // break; // case MotionEvent.ACTION_UP: // x = 0; // y = 0; // invalidate(); // break; // } // return true; // } // // @Override // public boolean dispatchTouchEvent(MotionEvent event) { // System.out.println("View dispatchTouchEvent..." + event.getAction()); // return super.dispatchTouchEvent(event); // } // // @Override // protected void onDraw(Canvas canvas) { // super.onDraw(canvas); // canvas.drawLine(x, 0, x, y, mPaint); // canvas.drawLine(0, y, x, y, mPaint); // if (textView != null) { // textView.setText(getTextString()); // } // } // // private String getTextString() { // return "坐标 ( " + x + "," + y + " )"; // } // // public void setTextView(TextView textView) { // this.textView = textView; // } // // // } // Path: app/src/main/java/com/xd/demi/activity/EventActivity.java import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.widget.TextView; import com.xd.demi.R; import com.xd.demi.view.EventView; package com.xd.demi.activity; /** * Created by demi on 16/12/6. */ public class EventActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_event); TextView tv = (TextView) findViewById(R.id.tv);
EventView eventView = (EventView) findViewById(R.id.event);
Demidong/ClockView
app/src/main/java/com/xd/demi/factory/ProfitsResponseConverter.java
// Path: app/src/main/java/com/xd/demi/bean/DailyYeildsInfo.java // public class DailyYeildsInfo { // private ArrayList<Profits> HS300; // private ArrayList<Profits> PORTFOLIO; // // public ArrayList<Profits> getHS300() { // return HS300; // } // // public void setHS300(ArrayList<Profits> HS300) { // this.HS300 = HS300; // } // // public ArrayList<Profits> getPORTFOLIO() { // return PORTFOLIO; // } // // public void setPORTFOLIO(ArrayList<Profits> PORTFOLIO) { // this.PORTFOLIO = PORTFOLIO; // } // } // // Path: app/src/main/java/com/xd/demi/bean/ResponseData.java // public class ResponseData<T> { // private String ret; // private String msg; // private T info; // // public String getRet() { // return ret; // } // // public void setRet(String ret) { // this.ret = ret; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public T getInfo() { // return info; // } // // public void setInfo(T info) { // this.info = info; // } // }
import com.xd.demi.bean.DailyYeildsInfo; import com.xd.demi.bean.ResponseData; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.Type; import okhttp3.ResponseBody; import retrofit2.Converter;
package com.xd.demi.factory; /** * Created by demi on 2017/3/13. */ public class ProfitsResponseConverter<T> implements Converter<ResponseBody,T>{ Type type ; public ProfitsResponseConverter(Type type){ this.type =type ; } @Override public T convert(ResponseBody value) throws IOException { String js = value.string(); Gson gs = new Gson();
// Path: app/src/main/java/com/xd/demi/bean/DailyYeildsInfo.java // public class DailyYeildsInfo { // private ArrayList<Profits> HS300; // private ArrayList<Profits> PORTFOLIO; // // public ArrayList<Profits> getHS300() { // return HS300; // } // // public void setHS300(ArrayList<Profits> HS300) { // this.HS300 = HS300; // } // // public ArrayList<Profits> getPORTFOLIO() { // return PORTFOLIO; // } // // public void setPORTFOLIO(ArrayList<Profits> PORTFOLIO) { // this.PORTFOLIO = PORTFOLIO; // } // } // // Path: app/src/main/java/com/xd/demi/bean/ResponseData.java // public class ResponseData<T> { // private String ret; // private String msg; // private T info; // // public String getRet() { // return ret; // } // // public void setRet(String ret) { // this.ret = ret; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public T getInfo() { // return info; // } // // public void setInfo(T info) { // this.info = info; // } // } // Path: app/src/main/java/com/xd/demi/factory/ProfitsResponseConverter.java import com.xd.demi.bean.DailyYeildsInfo; import com.xd.demi.bean.ResponseData; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.Type; import okhttp3.ResponseBody; import retrofit2.Converter; package com.xd.demi.factory; /** * Created by demi on 2017/3/13. */ public class ProfitsResponseConverter<T> implements Converter<ResponseBody,T>{ Type type ; public ProfitsResponseConverter(Type type){ this.type =type ; } @Override public T convert(ResponseBody value) throws IOException { String js = value.string(); Gson gs = new Gson();
ResponseData<DailyYeildsInfo> info = gs.fromJson(js, new TypeToken<ResponseData<DailyYeildsInfo>>() {
Demidong/ClockView
app/src/main/java/com/xd/demi/factory/ProfitsResponseConverter.java
// Path: app/src/main/java/com/xd/demi/bean/DailyYeildsInfo.java // public class DailyYeildsInfo { // private ArrayList<Profits> HS300; // private ArrayList<Profits> PORTFOLIO; // // public ArrayList<Profits> getHS300() { // return HS300; // } // // public void setHS300(ArrayList<Profits> HS300) { // this.HS300 = HS300; // } // // public ArrayList<Profits> getPORTFOLIO() { // return PORTFOLIO; // } // // public void setPORTFOLIO(ArrayList<Profits> PORTFOLIO) { // this.PORTFOLIO = PORTFOLIO; // } // } // // Path: app/src/main/java/com/xd/demi/bean/ResponseData.java // public class ResponseData<T> { // private String ret; // private String msg; // private T info; // // public String getRet() { // return ret; // } // // public void setRet(String ret) { // this.ret = ret; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public T getInfo() { // return info; // } // // public void setInfo(T info) { // this.info = info; // } // }
import com.xd.demi.bean.DailyYeildsInfo; import com.xd.demi.bean.ResponseData; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.Type; import okhttp3.ResponseBody; import retrofit2.Converter;
package com.xd.demi.factory; /** * Created by demi on 2017/3/13. */ public class ProfitsResponseConverter<T> implements Converter<ResponseBody,T>{ Type type ; public ProfitsResponseConverter(Type type){ this.type =type ; } @Override public T convert(ResponseBody value) throws IOException { String js = value.string(); Gson gs = new Gson();
// Path: app/src/main/java/com/xd/demi/bean/DailyYeildsInfo.java // public class DailyYeildsInfo { // private ArrayList<Profits> HS300; // private ArrayList<Profits> PORTFOLIO; // // public ArrayList<Profits> getHS300() { // return HS300; // } // // public void setHS300(ArrayList<Profits> HS300) { // this.HS300 = HS300; // } // // public ArrayList<Profits> getPORTFOLIO() { // return PORTFOLIO; // } // // public void setPORTFOLIO(ArrayList<Profits> PORTFOLIO) { // this.PORTFOLIO = PORTFOLIO; // } // } // // Path: app/src/main/java/com/xd/demi/bean/ResponseData.java // public class ResponseData<T> { // private String ret; // private String msg; // private T info; // // public String getRet() { // return ret; // } // // public void setRet(String ret) { // this.ret = ret; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public T getInfo() { // return info; // } // // public void setInfo(T info) { // this.info = info; // } // } // Path: app/src/main/java/com/xd/demi/factory/ProfitsResponseConverter.java import com.xd.demi.bean.DailyYeildsInfo; import com.xd.demi.bean.ResponseData; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.Type; import okhttp3.ResponseBody; import retrofit2.Converter; package com.xd.demi.factory; /** * Created by demi on 2017/3/13. */ public class ProfitsResponseConverter<T> implements Converter<ResponseBody,T>{ Type type ; public ProfitsResponseConverter(Type type){ this.type =type ; } @Override public T convert(ResponseBody value) throws IOException { String js = value.string(); Gson gs = new Gson();
ResponseData<DailyYeildsInfo> info = gs.fromJson(js, new TypeToken<ResponseData<DailyYeildsInfo>>() {
Demidong/ClockView
app/src/main/java/com/xd/demi/UrlService.java
// Path: app/src/main/java/com/xd/demi/bean/DailyYeildsInfo.java // public class DailyYeildsInfo { // private ArrayList<Profits> HS300; // private ArrayList<Profits> PORTFOLIO; // // public ArrayList<Profits> getHS300() { // return HS300; // } // // public void setHS300(ArrayList<Profits> HS300) { // this.HS300 = HS300; // } // // public ArrayList<Profits> getPORTFOLIO() { // return PORTFOLIO; // } // // public void setPORTFOLIO(ArrayList<Profits> PORTFOLIO) { // this.PORTFOLIO = PORTFOLIO; // } // } // // Path: app/src/main/java/com/xd/demi/bean/ResponseData.java // public class ResponseData<T> { // private String ret; // private String msg; // private T info; // // public String getRet() { // return ret; // } // // public void setRet(String ret) { // this.ret = ret; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public T getInfo() { // return info; // } // // public void setInfo(T info) { // this.info = info; // } // }
import android.graphics.Bitmap; import com.xd.demi.bean.DailyYeildsInfo; import com.xd.demi.bean.ResponseData; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import io.reactivex.Flowable;
package com.xd.demi; /** * Created by demi on 2017/3/13. */ public interface UrlService { @GET("bd_logo1_31bdc765.png") Call<Bitmap> getImage(); @GET("{id}/daily-yields?")
// Path: app/src/main/java/com/xd/demi/bean/DailyYeildsInfo.java // public class DailyYeildsInfo { // private ArrayList<Profits> HS300; // private ArrayList<Profits> PORTFOLIO; // // public ArrayList<Profits> getHS300() { // return HS300; // } // // public void setHS300(ArrayList<Profits> HS300) { // this.HS300 = HS300; // } // // public ArrayList<Profits> getPORTFOLIO() { // return PORTFOLIO; // } // // public void setPORTFOLIO(ArrayList<Profits> PORTFOLIO) { // this.PORTFOLIO = PORTFOLIO; // } // } // // Path: app/src/main/java/com/xd/demi/bean/ResponseData.java // public class ResponseData<T> { // private String ret; // private String msg; // private T info; // // public String getRet() { // return ret; // } // // public void setRet(String ret) { // this.ret = ret; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public T getInfo() { // return info; // } // // public void setInfo(T info) { // this.info = info; // } // } // Path: app/src/main/java/com/xd/demi/UrlService.java import android.graphics.Bitmap; import com.xd.demi.bean.DailyYeildsInfo; import com.xd.demi.bean.ResponseData; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import io.reactivex.Flowable; package com.xd.demi; /** * Created by demi on 2017/3/13. */ public interface UrlService { @GET("bd_logo1_31bdc765.png") Call<Bitmap> getImage(); @GET("{id}/daily-yields?")
Call<ResponseData<DailyYeildsInfo>> getDatas(@Path("id") String id , @Query("type") String type);
Demidong/ClockView
app/src/main/java/com/xd/demi/UrlService.java
// Path: app/src/main/java/com/xd/demi/bean/DailyYeildsInfo.java // public class DailyYeildsInfo { // private ArrayList<Profits> HS300; // private ArrayList<Profits> PORTFOLIO; // // public ArrayList<Profits> getHS300() { // return HS300; // } // // public void setHS300(ArrayList<Profits> HS300) { // this.HS300 = HS300; // } // // public ArrayList<Profits> getPORTFOLIO() { // return PORTFOLIO; // } // // public void setPORTFOLIO(ArrayList<Profits> PORTFOLIO) { // this.PORTFOLIO = PORTFOLIO; // } // } // // Path: app/src/main/java/com/xd/demi/bean/ResponseData.java // public class ResponseData<T> { // private String ret; // private String msg; // private T info; // // public String getRet() { // return ret; // } // // public void setRet(String ret) { // this.ret = ret; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public T getInfo() { // return info; // } // // public void setInfo(T info) { // this.info = info; // } // }
import android.graphics.Bitmap; import com.xd.demi.bean.DailyYeildsInfo; import com.xd.demi.bean.ResponseData; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import io.reactivex.Flowable;
package com.xd.demi; /** * Created by demi on 2017/3/13. */ public interface UrlService { @GET("bd_logo1_31bdc765.png") Call<Bitmap> getImage(); @GET("{id}/daily-yields?")
// Path: app/src/main/java/com/xd/demi/bean/DailyYeildsInfo.java // public class DailyYeildsInfo { // private ArrayList<Profits> HS300; // private ArrayList<Profits> PORTFOLIO; // // public ArrayList<Profits> getHS300() { // return HS300; // } // // public void setHS300(ArrayList<Profits> HS300) { // this.HS300 = HS300; // } // // public ArrayList<Profits> getPORTFOLIO() { // return PORTFOLIO; // } // // public void setPORTFOLIO(ArrayList<Profits> PORTFOLIO) { // this.PORTFOLIO = PORTFOLIO; // } // } // // Path: app/src/main/java/com/xd/demi/bean/ResponseData.java // public class ResponseData<T> { // private String ret; // private String msg; // private T info; // // public String getRet() { // return ret; // } // // public void setRet(String ret) { // this.ret = ret; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public T getInfo() { // return info; // } // // public void setInfo(T info) { // this.info = info; // } // } // Path: app/src/main/java/com/xd/demi/UrlService.java import android.graphics.Bitmap; import com.xd.demi.bean.DailyYeildsInfo; import com.xd.demi.bean.ResponseData; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import io.reactivex.Flowable; package com.xd.demi; /** * Created by demi on 2017/3/13. */ public interface UrlService { @GET("bd_logo1_31bdc765.png") Call<Bitmap> getImage(); @GET("{id}/daily-yields?")
Call<ResponseData<DailyYeildsInfo>> getDatas(@Path("id") String id , @Query("type") String type);
Demidong/ClockView
app/src/main/java/com/xd/demi/activity/PortfoliosActivity.java
// Path: app/src/main/java/com/xd/demi/fragment/ProfitsChartFragment.java // public class ProfitsChartFragment extends Fragment { // private TabContainer tab; // private ProfitsChartView chart; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_profit_chart, container, false); // tab =view.findViewById(R.id.tab); // chart = view.findViewById(R.id.chart); // return view; // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // getDatas(); // } // // // public void getDatas() { // OkHttpClient okHttpClient = new OkHttpClient(); // Retrofit retrofit = new Retrofit.Builder() // .baseUrl("https://fq-api.zixuan.com/stock-portfolios/") // .addConverterFactory(new ProfitsConverterFactory()) // .client(okHttpClient) // .build(); // UrlService service = retrofit.create(UrlService.class); // Call<ResponseData<DailyYeildsInfo>> call = service.getDatas("520","LAST_ALL"); // call.enqueue(new Callback<ResponseData<DailyYeildsInfo>>() { // @Override // public void onResponse(Call<ResponseData<DailyYeildsInfo>> call, Response<ResponseData<DailyYeildsInfo>> response) { // // JSONObject js =new JSONObject(json); // if(response.body() == null){ // chart.setData(createDatas()); // Toast.makeText(getContext(),"服务器挂了!!!",2000).show(); // return; // } // chart.setData(response.body().getInfo()); // } // // @Override // public void onFailure(Call<ResponseData<DailyYeildsInfo>> call, Throwable t) { // t.printStackTrace(); // chart.setData(createDatas()); // } // }); // } // // private DailyYeildsInfo createDatas(){ // DailyYeildsInfo data = new DailyYeildsInfo(); // ArrayList<Profits> hs300 = new ArrayList<>(); // ArrayList<Profits> profits = new ArrayList<>(); // for (int i = 0; i <10 ; i++) { // Profits hs300d = new Profits(1529581311000L+i*100,Math.random() *30 +2.4); // Profits profitsd = new Profits(1529581311000L+i*100,Math.random() *10 +3.2); // hs300.add(hs300d); // profits.add(profitsd); // } // data.setHS300(hs300); // data.setPORTFOLIO(profits); // return data; // } // }
import android.os.Bundle; import android.support.v4.app.FragmentActivity; import com.xd.demi.R; import com.xd.demi.fragment.ProfitsChartFragment;
package com.xd.demi.activity; /** * Created by demi on 2017/5/12. * 收益走势图 */ public class PortfoliosActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_portfolios); if (savedInstanceState == null) {
// Path: app/src/main/java/com/xd/demi/fragment/ProfitsChartFragment.java // public class ProfitsChartFragment extends Fragment { // private TabContainer tab; // private ProfitsChartView chart; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_profit_chart, container, false); // tab =view.findViewById(R.id.tab); // chart = view.findViewById(R.id.chart); // return view; // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // getDatas(); // } // // // public void getDatas() { // OkHttpClient okHttpClient = new OkHttpClient(); // Retrofit retrofit = new Retrofit.Builder() // .baseUrl("https://fq-api.zixuan.com/stock-portfolios/") // .addConverterFactory(new ProfitsConverterFactory()) // .client(okHttpClient) // .build(); // UrlService service = retrofit.create(UrlService.class); // Call<ResponseData<DailyYeildsInfo>> call = service.getDatas("520","LAST_ALL"); // call.enqueue(new Callback<ResponseData<DailyYeildsInfo>>() { // @Override // public void onResponse(Call<ResponseData<DailyYeildsInfo>> call, Response<ResponseData<DailyYeildsInfo>> response) { // // JSONObject js =new JSONObject(json); // if(response.body() == null){ // chart.setData(createDatas()); // Toast.makeText(getContext(),"服务器挂了!!!",2000).show(); // return; // } // chart.setData(response.body().getInfo()); // } // // @Override // public void onFailure(Call<ResponseData<DailyYeildsInfo>> call, Throwable t) { // t.printStackTrace(); // chart.setData(createDatas()); // } // }); // } // // private DailyYeildsInfo createDatas(){ // DailyYeildsInfo data = new DailyYeildsInfo(); // ArrayList<Profits> hs300 = new ArrayList<>(); // ArrayList<Profits> profits = new ArrayList<>(); // for (int i = 0; i <10 ; i++) { // Profits hs300d = new Profits(1529581311000L+i*100,Math.random() *30 +2.4); // Profits profitsd = new Profits(1529581311000L+i*100,Math.random() *10 +3.2); // hs300.add(hs300d); // profits.add(profitsd); // } // data.setHS300(hs300); // data.setPORTFOLIO(profits); // return data; // } // } // Path: app/src/main/java/com/xd/demi/activity/PortfoliosActivity.java import android.os.Bundle; import android.support.v4.app.FragmentActivity; import com.xd.demi.R; import com.xd.demi.fragment.ProfitsChartFragment; package com.xd.demi.activity; /** * Created by demi on 2017/5/12. * 收益走势图 */ public class PortfoliosActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_portfolios); if (savedInstanceState == null) {
ProfitsChartFragment profitsFragment = new ProfitsChartFragment();
Demidong/ClockView
app/src/main/java/com/xd/demi/activity/RetrofitOKHttpActivity.java
// Path: app/src/main/java/com/xd/demi/UrlService.java // public interface UrlService { // // @GET("bd_logo1_31bdc765.png") // Call<Bitmap> getImage(); // // @GET("{id}/daily-yields?") // Call<ResponseData<DailyYeildsInfo>> getDatas(@Path("id") String id , @Query("type") String type); // // @GET("bd_logo1_31bdc765.png") // Flowable<Bitmap> getRXImage(); // // } // // Path: app/src/main/java/com/xd/demi/factory/BitmapConverterFactory.java // public class BitmapConverterFactory extends Converter.Factory{ // // public static BitmapConverterFactory create() { // return new BitmapConverterFactory(); // } // // // @Override // public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { // return new BitmapResponseConverter<>(type); // } // // // } // // Path: app/src/main/java/com/xd/demi/utils/Platform.java // public class Platform // { // private static final Platform PLATFORM = findPlatform(); // // public static Platform get() // { // L.e(PLATFORM.getClass().toString()); // return PLATFORM; // } // // private static Platform findPlatform() // { // try // { // Class.forName("android.os.Build"); // if (Build.VERSION.SDK_INT != 0) // { // return new Android(); // } // } catch (ClassNotFoundException ignored) // { // } // return new Platform(); // } // // public Executor defaultCallbackExecutor() // { // return Executors.newCachedThreadPool(); // } // // public void execute(Runnable runnable) // { // defaultCallbackExecutor().execute(runnable); // } // // // static class Android extends Platform // { // @Override // public Executor defaultCallbackExecutor() // { // return new MainThreadExecutor(); // } // // static class MainThreadExecutor implements Executor // { // private final Handler handler = new Handler(Looper.getMainLooper()); // // @Override // public void execute(Runnable r) // { // handler.post(r); // } // } // } // // // }
import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.xd.demi.R; import com.xd.demi.UrlService; import com.xd.demi.factory.BitmapConverterFactory; import com.xd.demi.utils.Platform; import org.reactivestreams.Subscription; import io.reactivex.FlowableSubscriber; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
package com.xd.demi.activity; /** * Created by demi on 2017/3/13. */ public class RetrofitOKHttpActivity extends Activity implements View.OnClickListener { ImageView image; Button button;
// Path: app/src/main/java/com/xd/demi/UrlService.java // public interface UrlService { // // @GET("bd_logo1_31bdc765.png") // Call<Bitmap> getImage(); // // @GET("{id}/daily-yields?") // Call<ResponseData<DailyYeildsInfo>> getDatas(@Path("id") String id , @Query("type") String type); // // @GET("bd_logo1_31bdc765.png") // Flowable<Bitmap> getRXImage(); // // } // // Path: app/src/main/java/com/xd/demi/factory/BitmapConverterFactory.java // public class BitmapConverterFactory extends Converter.Factory{ // // public static BitmapConverterFactory create() { // return new BitmapConverterFactory(); // } // // // @Override // public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { // return new BitmapResponseConverter<>(type); // } // // // } // // Path: app/src/main/java/com/xd/demi/utils/Platform.java // public class Platform // { // private static final Platform PLATFORM = findPlatform(); // // public static Platform get() // { // L.e(PLATFORM.getClass().toString()); // return PLATFORM; // } // // private static Platform findPlatform() // { // try // { // Class.forName("android.os.Build"); // if (Build.VERSION.SDK_INT != 0) // { // return new Android(); // } // } catch (ClassNotFoundException ignored) // { // } // return new Platform(); // } // // public Executor defaultCallbackExecutor() // { // return Executors.newCachedThreadPool(); // } // // public void execute(Runnable runnable) // { // defaultCallbackExecutor().execute(runnable); // } // // // static class Android extends Platform // { // @Override // public Executor defaultCallbackExecutor() // { // return new MainThreadExecutor(); // } // // static class MainThreadExecutor implements Executor // { // private final Handler handler = new Handler(Looper.getMainLooper()); // // @Override // public void execute(Runnable r) // { // handler.post(r); // } // } // } // // // } // Path: app/src/main/java/com/xd/demi/activity/RetrofitOKHttpActivity.java import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.xd.demi.R; import com.xd.demi.UrlService; import com.xd.demi.factory.BitmapConverterFactory; import com.xd.demi.utils.Platform; import org.reactivestreams.Subscription; import io.reactivex.FlowableSubscriber; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; package com.xd.demi.activity; /** * Created by demi on 2017/3/13. */ public class RetrofitOKHttpActivity extends Activity implements View.OnClickListener { ImageView image; Button button;
private Platform mPlatform;
Demidong/ClockView
app/src/main/java/com/xd/demi/activity/RetrofitOKHttpActivity.java
// Path: app/src/main/java/com/xd/demi/UrlService.java // public interface UrlService { // // @GET("bd_logo1_31bdc765.png") // Call<Bitmap> getImage(); // // @GET("{id}/daily-yields?") // Call<ResponseData<DailyYeildsInfo>> getDatas(@Path("id") String id , @Query("type") String type); // // @GET("bd_logo1_31bdc765.png") // Flowable<Bitmap> getRXImage(); // // } // // Path: app/src/main/java/com/xd/demi/factory/BitmapConverterFactory.java // public class BitmapConverterFactory extends Converter.Factory{ // // public static BitmapConverterFactory create() { // return new BitmapConverterFactory(); // } // // // @Override // public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { // return new BitmapResponseConverter<>(type); // } // // // } // // Path: app/src/main/java/com/xd/demi/utils/Platform.java // public class Platform // { // private static final Platform PLATFORM = findPlatform(); // // public static Platform get() // { // L.e(PLATFORM.getClass().toString()); // return PLATFORM; // } // // private static Platform findPlatform() // { // try // { // Class.forName("android.os.Build"); // if (Build.VERSION.SDK_INT != 0) // { // return new Android(); // } // } catch (ClassNotFoundException ignored) // { // } // return new Platform(); // } // // public Executor defaultCallbackExecutor() // { // return Executors.newCachedThreadPool(); // } // // public void execute(Runnable runnable) // { // defaultCallbackExecutor().execute(runnable); // } // // // static class Android extends Platform // { // @Override // public Executor defaultCallbackExecutor() // { // return new MainThreadExecutor(); // } // // static class MainThreadExecutor implements Executor // { // private final Handler handler = new Handler(Looper.getMainLooper()); // // @Override // public void execute(Runnable r) // { // handler.post(r); // } // } // } // // // }
import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.xd.demi.R; import com.xd.demi.UrlService; import com.xd.demi.factory.BitmapConverterFactory; import com.xd.demi.utils.Platform; import org.reactivestreams.Subscription; import io.reactivex.FlowableSubscriber; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
package com.xd.demi.activity; /** * Created by demi on 2017/3/13. */ public class RetrofitOKHttpActivity extends Activity implements View.OnClickListener { ImageView image; Button button; private Platform mPlatform; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_retrofit); image = (ImageView) findViewById(R.id.image); button = (Button) findViewById(R.id.button); button.setOnClickListener(this); mPlatform = Platform.get(); } @Override public void onClick(View v) { // OkHttpClient okHttpClient = new OkHttpClient(); // Request request = new Request.Builder() // .url("bd_logo1_31bdc765.png") // .build(); // Call call= okHttpClient.newCall(request); // call.enqueue(new Callback() // { // @Override // public void onFailure(Call call, IOException e) { // // } // // @Override // public void onResponse(Call call, final Response response) throws IOException { // mPlatform.execute(new Runnable() { // @Override // public void run() { // InputStream inputStream = response.body().byteStream(); // Bitmap bitmap= BitmapFactory.decodeStream(inputStream); // image.setImageBitmap(bitmap); // } // }); // // } // // }); OkHttpClient okHttpClient = new OkHttpClient(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/")
// Path: app/src/main/java/com/xd/demi/UrlService.java // public interface UrlService { // // @GET("bd_logo1_31bdc765.png") // Call<Bitmap> getImage(); // // @GET("{id}/daily-yields?") // Call<ResponseData<DailyYeildsInfo>> getDatas(@Path("id") String id , @Query("type") String type); // // @GET("bd_logo1_31bdc765.png") // Flowable<Bitmap> getRXImage(); // // } // // Path: app/src/main/java/com/xd/demi/factory/BitmapConverterFactory.java // public class BitmapConverterFactory extends Converter.Factory{ // // public static BitmapConverterFactory create() { // return new BitmapConverterFactory(); // } // // // @Override // public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { // return new BitmapResponseConverter<>(type); // } // // // } // // Path: app/src/main/java/com/xd/demi/utils/Platform.java // public class Platform // { // private static final Platform PLATFORM = findPlatform(); // // public static Platform get() // { // L.e(PLATFORM.getClass().toString()); // return PLATFORM; // } // // private static Platform findPlatform() // { // try // { // Class.forName("android.os.Build"); // if (Build.VERSION.SDK_INT != 0) // { // return new Android(); // } // } catch (ClassNotFoundException ignored) // { // } // return new Platform(); // } // // public Executor defaultCallbackExecutor() // { // return Executors.newCachedThreadPool(); // } // // public void execute(Runnable runnable) // { // defaultCallbackExecutor().execute(runnable); // } // // // static class Android extends Platform // { // @Override // public Executor defaultCallbackExecutor() // { // return new MainThreadExecutor(); // } // // static class MainThreadExecutor implements Executor // { // private final Handler handler = new Handler(Looper.getMainLooper()); // // @Override // public void execute(Runnable r) // { // handler.post(r); // } // } // } // // // } // Path: app/src/main/java/com/xd/demi/activity/RetrofitOKHttpActivity.java import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.xd.demi.R; import com.xd.demi.UrlService; import com.xd.demi.factory.BitmapConverterFactory; import com.xd.demi.utils.Platform; import org.reactivestreams.Subscription; import io.reactivex.FlowableSubscriber; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; package com.xd.demi.activity; /** * Created by demi on 2017/3/13. */ public class RetrofitOKHttpActivity extends Activity implements View.OnClickListener { ImageView image; Button button; private Platform mPlatform; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_retrofit); image = (ImageView) findViewById(R.id.image); button = (Button) findViewById(R.id.button); button.setOnClickListener(this); mPlatform = Platform.get(); } @Override public void onClick(View v) { // OkHttpClient okHttpClient = new OkHttpClient(); // Request request = new Request.Builder() // .url("bd_logo1_31bdc765.png") // .build(); // Call call= okHttpClient.newCall(request); // call.enqueue(new Callback() // { // @Override // public void onFailure(Call call, IOException e) { // // } // // @Override // public void onResponse(Call call, final Response response) throws IOException { // mPlatform.execute(new Runnable() { // @Override // public void run() { // InputStream inputStream = response.body().byteStream(); // Bitmap bitmap= BitmapFactory.decodeStream(inputStream); // image.setImageBitmap(bitmap); // } // }); // // } // // }); OkHttpClient okHttpClient = new OkHttpClient(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/")
.addConverterFactory(BitmapConverterFactory.create())
Demidong/ClockView
app/src/main/java/com/xd/demi/activity/RetrofitOKHttpActivity.java
// Path: app/src/main/java/com/xd/demi/UrlService.java // public interface UrlService { // // @GET("bd_logo1_31bdc765.png") // Call<Bitmap> getImage(); // // @GET("{id}/daily-yields?") // Call<ResponseData<DailyYeildsInfo>> getDatas(@Path("id") String id , @Query("type") String type); // // @GET("bd_logo1_31bdc765.png") // Flowable<Bitmap> getRXImage(); // // } // // Path: app/src/main/java/com/xd/demi/factory/BitmapConverterFactory.java // public class BitmapConverterFactory extends Converter.Factory{ // // public static BitmapConverterFactory create() { // return new BitmapConverterFactory(); // } // // // @Override // public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { // return new BitmapResponseConverter<>(type); // } // // // } // // Path: app/src/main/java/com/xd/demi/utils/Platform.java // public class Platform // { // private static final Platform PLATFORM = findPlatform(); // // public static Platform get() // { // L.e(PLATFORM.getClass().toString()); // return PLATFORM; // } // // private static Platform findPlatform() // { // try // { // Class.forName("android.os.Build"); // if (Build.VERSION.SDK_INT != 0) // { // return new Android(); // } // } catch (ClassNotFoundException ignored) // { // } // return new Platform(); // } // // public Executor defaultCallbackExecutor() // { // return Executors.newCachedThreadPool(); // } // // public void execute(Runnable runnable) // { // defaultCallbackExecutor().execute(runnable); // } // // // static class Android extends Platform // { // @Override // public Executor defaultCallbackExecutor() // { // return new MainThreadExecutor(); // } // // static class MainThreadExecutor implements Executor // { // private final Handler handler = new Handler(Looper.getMainLooper()); // // @Override // public void execute(Runnable r) // { // handler.post(r); // } // } // } // // // }
import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.xd.demi.R; import com.xd.demi.UrlService; import com.xd.demi.factory.BitmapConverterFactory; import com.xd.demi.utils.Platform; import org.reactivestreams.Subscription; import io.reactivex.FlowableSubscriber; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
package com.xd.demi.activity; /** * Created by demi on 2017/3/13. */ public class RetrofitOKHttpActivity extends Activity implements View.OnClickListener { ImageView image; Button button; private Platform mPlatform; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_retrofit); image = (ImageView) findViewById(R.id.image); button = (Button) findViewById(R.id.button); button.setOnClickListener(this); mPlatform = Platform.get(); } @Override public void onClick(View v) { // OkHttpClient okHttpClient = new OkHttpClient(); // Request request = new Request.Builder() // .url("bd_logo1_31bdc765.png") // .build(); // Call call= okHttpClient.newCall(request); // call.enqueue(new Callback() // { // @Override // public void onFailure(Call call, IOException e) { // // } // // @Override // public void onResponse(Call call, final Response response) throws IOException { // mPlatform.execute(new Runnable() { // @Override // public void run() { // InputStream inputStream = response.body().byteStream(); // Bitmap bitmap= BitmapFactory.decodeStream(inputStream); // image.setImageBitmap(bitmap); // } // }); // // } // // }); OkHttpClient okHttpClient = new OkHttpClient(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/") .addConverterFactory(BitmapConverterFactory.create()) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build();
// Path: app/src/main/java/com/xd/demi/UrlService.java // public interface UrlService { // // @GET("bd_logo1_31bdc765.png") // Call<Bitmap> getImage(); // // @GET("{id}/daily-yields?") // Call<ResponseData<DailyYeildsInfo>> getDatas(@Path("id") String id , @Query("type") String type); // // @GET("bd_logo1_31bdc765.png") // Flowable<Bitmap> getRXImage(); // // } // // Path: app/src/main/java/com/xd/demi/factory/BitmapConverterFactory.java // public class BitmapConverterFactory extends Converter.Factory{ // // public static BitmapConverterFactory create() { // return new BitmapConverterFactory(); // } // // // @Override // public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { // return new BitmapResponseConverter<>(type); // } // // // } // // Path: app/src/main/java/com/xd/demi/utils/Platform.java // public class Platform // { // private static final Platform PLATFORM = findPlatform(); // // public static Platform get() // { // L.e(PLATFORM.getClass().toString()); // return PLATFORM; // } // // private static Platform findPlatform() // { // try // { // Class.forName("android.os.Build"); // if (Build.VERSION.SDK_INT != 0) // { // return new Android(); // } // } catch (ClassNotFoundException ignored) // { // } // return new Platform(); // } // // public Executor defaultCallbackExecutor() // { // return Executors.newCachedThreadPool(); // } // // public void execute(Runnable runnable) // { // defaultCallbackExecutor().execute(runnable); // } // // // static class Android extends Platform // { // @Override // public Executor defaultCallbackExecutor() // { // return new MainThreadExecutor(); // } // // static class MainThreadExecutor implements Executor // { // private final Handler handler = new Handler(Looper.getMainLooper()); // // @Override // public void execute(Runnable r) // { // handler.post(r); // } // } // } // // // } // Path: app/src/main/java/com/xd/demi/activity/RetrofitOKHttpActivity.java import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.xd.demi.R; import com.xd.demi.UrlService; import com.xd.demi.factory.BitmapConverterFactory; import com.xd.demi.utils.Platform; import org.reactivestreams.Subscription; import io.reactivex.FlowableSubscriber; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; package com.xd.demi.activity; /** * Created by demi on 2017/3/13. */ public class RetrofitOKHttpActivity extends Activity implements View.OnClickListener { ImageView image; Button button; private Platform mPlatform; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_retrofit); image = (ImageView) findViewById(R.id.image); button = (Button) findViewById(R.id.button); button.setOnClickListener(this); mPlatform = Platform.get(); } @Override public void onClick(View v) { // OkHttpClient okHttpClient = new OkHttpClient(); // Request request = new Request.Builder() // .url("bd_logo1_31bdc765.png") // .build(); // Call call= okHttpClient.newCall(request); // call.enqueue(new Callback() // { // @Override // public void onFailure(Call call, IOException e) { // // } // // @Override // public void onResponse(Call call, final Response response) throws IOException { // mPlatform.execute(new Runnable() { // @Override // public void run() { // InputStream inputStream = response.body().byteStream(); // Bitmap bitmap= BitmapFactory.decodeStream(inputStream); // image.setImageBitmap(bitmap); // } // }); // // } // // }); OkHttpClient okHttpClient = new OkHttpClient(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/") .addConverterFactory(BitmapConverterFactory.create()) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build();
UrlService service = retrofit.create(UrlService.class);
Demidong/ClockView
app/src/main/java/com/xd/demi/view/NineSquareView.java
// Path: app/src/main/java/com/xd/demi/bean/Point.java // public class Point implements Serializable{ // private float x ; // private float y ; // // public float getX() { // return x; // } // // public void setX(float x) { // this.x = x; // } // // public float getY() { // return y; // } // // public void setY(float y) { // this.y = y; // } // // public Point(float x, float y) { // this.x = x; // this.y = y; // } // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.xd.demi.bean.Point; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set;
package com.xd.demi.view; /** * Created by demi on 2017/3/14. */ public class NineSquareView extends View { private Paint pointPaint; //画点的画笔 private Paint linePaint; // 画线的画笔 private Path path; //路径 private static int SQUAREWIDRH = 300; //默认正方形的边长 private float mSquarewidth = SQUAREWIDRH; //每个正方形的边长 9个 private float x, y; //手指在滑动的时候那个点的坐标 private float startX, startY; //手指首次接触View的那个点的坐标
// Path: app/src/main/java/com/xd/demi/bean/Point.java // public class Point implements Serializable{ // private float x ; // private float y ; // // public float getX() { // return x; // } // // public void setX(float x) { // this.x = x; // } // // public float getY() { // return y; // } // // public void setY(float y) { // this.y = y; // } // // public Point(float x, float y) { // this.x = x; // this.y = y; // } // } // Path: app/src/main/java/com/xd/demi/view/NineSquareView.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.xd.demi.bean.Point; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; package com.xd.demi.view; /** * Created by demi on 2017/3/14. */ public class NineSquareView extends View { private Paint pointPaint; //画点的画笔 private Paint linePaint; // 画线的画笔 private Path path; //路径 private static int SQUAREWIDRH = 300; //默认正方形的边长 private float mSquarewidth = SQUAREWIDRH; //每个正方形的边长 9个 private float x, y; //手指在滑动的时候那个点的坐标 private float startX, startY; //手指首次接触View的那个点的坐标
private LinkedHashMap<String,Point> points = new LinkedHashMap<>(); //存放手指连接的点
Demidong/ClockView
app/src/main/java/com/xd/demi/adapter/DividerItemDecoration.java
// Path: app/src/main/java/com/xd/demi/utils/DensityUtils.java // public class DensityUtils // { // private DensityUtils() // { // /* cannot be instantiated */ // throw new UnsupportedOperationException("cannot be instantiated"); // } // // /** // * dp转px // * // * @param context // * @param dpVal // * @return // */ // public static int dp2px(Context context, float dpVal) // { // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, // dpVal, context.getResources().getDisplayMetrics()); // } // /** // * dp转px // * // * @param res // * @param dpVal // * @return // */ // public static int dp2px(Resources res, float dpVal) // { // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, // dpVal, res.getDisplayMetrics()); // } // // /** // * sp转px // * // * @param context // * @param spVal // * @return // */ // public static int sp2px(Context context, float spVal) // { // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, // spVal, context.getResources().getDisplayMetrics()); // } // // /** // * px转dp // * // * @param context // * @param pxVal // * @return // */ // public static float px2dp(Context context, float pxVal) // { // final float scale = context.getResources().getDisplayMetrics().density; // return (pxVal / scale); // } // // /** // * px转sp // * // * @param context // * @param pxVal // * @return // */ // public static float px2sp(Context context, float pxVal) // { // return (pxVal / context.getResources().getDisplayMetrics().scaledDensity); // } // // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.support.v4.content.ContextCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.xd.demi.R; import com.xd.demi.utils.DensityUtils;
package com.xd.demi.adapter; /** * Created by demi on 2017/4/25. */ public class DividerItemDecoration extends RecyclerView.ItemDecoration { /* * RecyclerView的布局方向,默认先赋值 * 为纵向布局 * RecyclerView 布局可横向,也可纵向 * 横向和纵向对应的分割想画法不一样 * */ private int mOrientation = LinearLayoutManager.VERTICAL; /** * item之间分割线的size,默认为1 */ private float mItemSize = 1.0f; /** * 绘制item分割线的画笔,和设置其属性 * 来绘制个性分割线 */ private Paint mPaint; /** * 构造方法传入布局方向,不可不传 * * @param context * @param orientation */ public DividerItemDecoration(Context context, int orientation, float mItemSize, int colorId) { this.mOrientation = orientation; if (orientation != LinearLayoutManager.VERTICAL && orientation != LinearLayoutManager.HORIZONTAL) { throw new IllegalArgumentException("请传入正确的参数"); }
// Path: app/src/main/java/com/xd/demi/utils/DensityUtils.java // public class DensityUtils // { // private DensityUtils() // { // /* cannot be instantiated */ // throw new UnsupportedOperationException("cannot be instantiated"); // } // // /** // * dp转px // * // * @param context // * @param dpVal // * @return // */ // public static int dp2px(Context context, float dpVal) // { // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, // dpVal, context.getResources().getDisplayMetrics()); // } // /** // * dp转px // * // * @param res // * @param dpVal // * @return // */ // public static int dp2px(Resources res, float dpVal) // { // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, // dpVal, res.getDisplayMetrics()); // } // // /** // * sp转px // * // * @param context // * @param spVal // * @return // */ // public static int sp2px(Context context, float spVal) // { // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, // spVal, context.getResources().getDisplayMetrics()); // } // // /** // * px转dp // * // * @param context // * @param pxVal // * @return // */ // public static float px2dp(Context context, float pxVal) // { // final float scale = context.getResources().getDisplayMetrics().density; // return (pxVal / scale); // } // // /** // * px转sp // * // * @param context // * @param pxVal // * @return // */ // public static float px2sp(Context context, float pxVal) // { // return (pxVal / context.getResources().getDisplayMetrics().scaledDensity); // } // // } // Path: app/src/main/java/com/xd/demi/adapter/DividerItemDecoration.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.support.v4.content.ContextCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.xd.demi.R; import com.xd.demi.utils.DensityUtils; package com.xd.demi.adapter; /** * Created by demi on 2017/4/25. */ public class DividerItemDecoration extends RecyclerView.ItemDecoration { /* * RecyclerView的布局方向,默认先赋值 * 为纵向布局 * RecyclerView 布局可横向,也可纵向 * 横向和纵向对应的分割想画法不一样 * */ private int mOrientation = LinearLayoutManager.VERTICAL; /** * item之间分割线的size,默认为1 */ private float mItemSize = 1.0f; /** * 绘制item分割线的画笔,和设置其属性 * 来绘制个性分割线 */ private Paint mPaint; /** * 构造方法传入布局方向,不可不传 * * @param context * @param orientation */ public DividerItemDecoration(Context context, int orientation, float mItemSize, int colorId) { this.mOrientation = orientation; if (orientation != LinearLayoutManager.VERTICAL && orientation != LinearLayoutManager.HORIZONTAL) { throw new IllegalArgumentException("请传入正确的参数"); }
this.mItemSize = DensityUtils.dp2px(context,mItemSize);
Demidong/ClockView
app/src/main/java/com/xd/demi/view/PercentView.java
// Path: app/src/main/java/com/xd/demi/utils/ViewSizeChangeAnimation.java // public class ViewSizeChangeAnimation extends Animation { // int initialWidth; // int targetWidth; // View view; // // public ViewSizeChangeAnimation(View view, int targetWidth) { // this.view = view; // this.targetWidth = targetWidth; // } // // @Override // protected void applyTransformation(float interpolatedTime, Transformation t) { // view.getLayoutParams().width = initialWidth + (int) ((targetWidth - initialWidth) * interpolatedTime); // view.requestLayout(); // } // // // @Override // public void initialize(int width, int height, int parentWidth, int parentHeight) { // this.initialWidth = width; // super.initialize(width, height, parentWidth, parentHeight); // } // // @Override // public boolean willChangeBounds() { // return true; // } // }
import android.animation.ObjectAnimator; import android.animation.PropertyValuesHolder; import android.animation.ValueAnimator; import android.content.Context; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.xd.demi.R; import com.xd.demi.utils.ViewSizeChangeAnimation;
clearRightGunDong(); clearCenterGunDong(); left_iv.setVisibility(View.VISIBLE); right_iv.setVisibility(View.GONE); center_iv_left.setVisibility(View.GONE); center_iv_right.setVisibility(View.GONE); } else if (flagMax == RIGHT_HEAD) { startRightGunDong(); clearLeftGunDong(); clearCenterGunDong(); left_iv.setVisibility(View.GONE); right_iv.setVisibility(View.VISIBLE); center_iv_left.setVisibility(View.GONE); center_iv_right.setVisibility(View.GONE); } else { startCenterGunDong(); clearLeftGunDong(); clearRightGunDong(); right_iv.setVisibility(View.GONE); left_iv.setVisibility(View.GONE); center_iv_left.setVisibility(View.VISIBLE); center_iv_right.setVisibility(View.VISIBLE); } } public void setPercentMoveAnimator() { LinearLayout.LayoutParams lp = new LayoutParams(0, LayoutParams.MATCH_PARENT, leftHead); LinearLayout.LayoutParams cp = new LayoutParams(0, LayoutParams.MATCH_PARENT, centerHead); LinearLayout.LayoutParams rp = new LayoutParams(0, LayoutParams.MATCH_PARENT, rightHead);
// Path: app/src/main/java/com/xd/demi/utils/ViewSizeChangeAnimation.java // public class ViewSizeChangeAnimation extends Animation { // int initialWidth; // int targetWidth; // View view; // // public ViewSizeChangeAnimation(View view, int targetWidth) { // this.view = view; // this.targetWidth = targetWidth; // } // // @Override // protected void applyTransformation(float interpolatedTime, Transformation t) { // view.getLayoutParams().width = initialWidth + (int) ((targetWidth - initialWidth) * interpolatedTime); // view.requestLayout(); // } // // // @Override // public void initialize(int width, int height, int parentWidth, int parentHeight) { // this.initialWidth = width; // super.initialize(width, height, parentWidth, parentHeight); // } // // @Override // public boolean willChangeBounds() { // return true; // } // } // Path: app/src/main/java/com/xd/demi/view/PercentView.java import android.animation.ObjectAnimator; import android.animation.PropertyValuesHolder; import android.animation.ValueAnimator; import android.content.Context; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.xd.demi.R; import com.xd.demi.utils.ViewSizeChangeAnimation; clearRightGunDong(); clearCenterGunDong(); left_iv.setVisibility(View.VISIBLE); right_iv.setVisibility(View.GONE); center_iv_left.setVisibility(View.GONE); center_iv_right.setVisibility(View.GONE); } else if (flagMax == RIGHT_HEAD) { startRightGunDong(); clearLeftGunDong(); clearCenterGunDong(); left_iv.setVisibility(View.GONE); right_iv.setVisibility(View.VISIBLE); center_iv_left.setVisibility(View.GONE); center_iv_right.setVisibility(View.GONE); } else { startCenterGunDong(); clearLeftGunDong(); clearRightGunDong(); right_iv.setVisibility(View.GONE); left_iv.setVisibility(View.GONE); center_iv_left.setVisibility(View.VISIBLE); center_iv_right.setVisibility(View.VISIBLE); } } public void setPercentMoveAnimator() { LinearLayout.LayoutParams lp = new LayoutParams(0, LayoutParams.MATCH_PARENT, leftHead); LinearLayout.LayoutParams cp = new LayoutParams(0, LayoutParams.MATCH_PARENT, centerHead); LinearLayout.LayoutParams rp = new LayoutParams(0, LayoutParams.MATCH_PARENT, rightHead);
ViewSizeChangeAnimation animationL = new ViewSizeChangeAnimation(left_fr, (int) (lp.weight / 100 * getWidth()));
Demidong/ClockView
app/src/main/java/com/xd/demi/view/ShopCarLayout.java
// Path: app/src/main/java/com/xd/demi/utils/DensityUtils.java // public class DensityUtils // { // private DensityUtils() // { // /* cannot be instantiated */ // throw new UnsupportedOperationException("cannot be instantiated"); // } // // /** // * dp转px // * // * @param context // * @param dpVal // * @return // */ // public static int dp2px(Context context, float dpVal) // { // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, // dpVal, context.getResources().getDisplayMetrics()); // } // /** // * dp转px // * // * @param res // * @param dpVal // * @return // */ // public static int dp2px(Resources res, float dpVal) // { // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, // dpVal, res.getDisplayMetrics()); // } // // /** // * sp转px // * // * @param context // * @param spVal // * @return // */ // public static int sp2px(Context context, float spVal) // { // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, // spVal, context.getResources().getDisplayMetrics()); // } // // /** // * px转dp // * // * @param context // * @param pxVal // * @return // */ // public static float px2dp(Context context, float pxVal) // { // final float scale = context.getResources().getDisplayMetrics().density; // return (pxVal / scale); // } // // /** // * px转sp // * // * @param context // * @param pxVal // * @return // */ // public static float px2sp(Context context, float pxVal) // { // return (pxVal / context.getResources().getDisplayMetrics().scaledDensity); // } // // }
import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.RotateAnimation; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; import android.widget.FrameLayout; import com.xd.demi.utils.DensityUtils; import de.hdodenhof.circleimageview.CircleImageView;
if(!isClean){ setAnim(drawable,start_location,finish_view); }else{ try{ removeAllViews(); isClean = false; setAnim(drawable,start_location,finish_view); }catch(Exception e){ e.printStackTrace(); } finally{ isClean = true; } } } /** * @deprecated 将要执行动画的view 添加到动画层 * @param vg * 动画运行的层 这里是frameLayout * @param view * 要运行动画的View * @param location * 动画的起始位置 * @return */ private View addViewToAnimLayout(ViewGroup vg, View view, int[] location){ int x = location[0]; int y = location[1]; vg.addView(view); LayoutParams lp = new LayoutParams(
// Path: app/src/main/java/com/xd/demi/utils/DensityUtils.java // public class DensityUtils // { // private DensityUtils() // { // /* cannot be instantiated */ // throw new UnsupportedOperationException("cannot be instantiated"); // } // // /** // * dp转px // * // * @param context // * @param dpVal // * @return // */ // public static int dp2px(Context context, float dpVal) // { // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, // dpVal, context.getResources().getDisplayMetrics()); // } // /** // * dp转px // * // * @param res // * @param dpVal // * @return // */ // public static int dp2px(Resources res, float dpVal) // { // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, // dpVal, res.getDisplayMetrics()); // } // // /** // * sp转px // * // * @param context // * @param spVal // * @return // */ // public static int sp2px(Context context, float spVal) // { // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, // spVal, context.getResources().getDisplayMetrics()); // } // // /** // * px转dp // * // * @param context // * @param pxVal // * @return // */ // public static float px2dp(Context context, float pxVal) // { // final float scale = context.getResources().getDisplayMetrics().density; // return (pxVal / scale); // } // // /** // * px转sp // * // * @param context // * @param pxVal // * @return // */ // public static float px2sp(Context context, float pxVal) // { // return (pxVal / context.getResources().getDisplayMetrics().scaledDensity); // } // // } // Path: app/src/main/java/com/xd/demi/view/ShopCarLayout.java import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.RotateAnimation; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; import android.widget.FrameLayout; import com.xd.demi.utils.DensityUtils; import de.hdodenhof.circleimageview.CircleImageView; if(!isClean){ setAnim(drawable,start_location,finish_view); }else{ try{ removeAllViews(); isClean = false; setAnim(drawable,start_location,finish_view); }catch(Exception e){ e.printStackTrace(); } finally{ isClean = true; } } } /** * @deprecated 将要执行动画的view 添加到动画层 * @param vg * 动画运行的层 这里是frameLayout * @param view * 要运行动画的View * @param location * 动画的起始位置 * @return */ private View addViewToAnimLayout(ViewGroup vg, View view, int[] location){ int x = location[0]; int y = location[1]; vg.addView(view); LayoutParams lp = new LayoutParams(
DensityUtils.dp2px(context,30), DensityUtils.dp2px(context,30));
Demidong/ClockView
app/src/main/java/com/xd/demi/activity/ShopCarActivity.java
// Path: app/src/main/java/com/xd/demi/view/ShopCarLayout.java // public class ShopCarLayout extends FrameLayout { // //动画时间 // private int animationDuration = 1000; // //正在执行的动画数量 // private int number = 0; // //是否完成清理 // private boolean isClean = false; // private Context context ; // public ShopCarLayout(Context context) { // super(context); // this.context =context ; // ViewGroup rootView = (ViewGroup) ((Activity)context).getWindow().getDecorView(); // LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); // setLayoutParams(lp); // setBackgroundResource(android.R.color.transparent); // rootView.addView(this); // } // /** // * 动画效果设置 // * @param drawable // * 将要加入购物车的商品 // * @param start_location // * 起始位置 // */ // private void setAnim(Drawable drawable, int[] start_location,View finish_view){ // // // Animation mScaleAnimation = new ScaleAnimation(1.5f,0.0f,1.5f,0.0f,Animation.RELATIVE_TO_SELF,0.1f,Animation.RELATIVE_TO_SELF,0.1f); // mScaleAnimation.setDuration(animationDuration); // mScaleAnimation.setFillAfter(true); // // // final CircleImageView iview = new CircleImageView(context); // iview.setImageDrawable(drawable); // final View view = addViewToAnimLayout(this,iview,start_location); // view.setAlpha(0.6f); // // int[] end_location = new int[2]; // finish_view.getLocationInWindow(end_location); // int endX = end_location[0]-start_location[0]+finish_view.getWidth()/2; // int endY = end_location[1]-start_location[1]+finish_view.getHeight()/2; // // Animation mTranslateAnimation = new TranslateAnimation(0,endX,0,endY); // Animation mRotateAnimation = new RotateAnimation(0, 180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); // mRotateAnimation.setDuration(animationDuration); // mTranslateAnimation.setDuration(animationDuration); // AnimationSet mAnimationSet = new AnimationSet(true); // // mAnimationSet.setFillAfter(true); // mAnimationSet.addAnimation(mRotateAnimation); // mAnimationSet.addAnimation(mScaleAnimation); // mAnimationSet.addAnimation(mTranslateAnimation); // // mAnimationSet.setAnimationListener(new Animation.AnimationListener(){ // // @Override // public void onAnimationStart(Animation animation) { // // TODO Auto-generated method stub // number++; // } // // @Override // public void onAnimationEnd(Animation animation) { // // TODO Auto-generated method stub // // number--; // if(number==0){ // isClean = true; // removeAllViews(); // isClean =false; // } // // } // // @Override // public void onAnimationRepeat(Animation animation) { // // TODO Auto-generated method stub // // } // // }); // iview.startAnimation(mAnimationSet); // // } // // // public void doAnim(Drawable drawable, int[] start_location,View finish_view){ // if(!isClean){ // setAnim(drawable,start_location,finish_view); // }else{ // try{ // removeAllViews(); // isClean = false; // setAnim(drawable,start_location,finish_view); // }catch(Exception e){ // e.printStackTrace(); // } // finally{ // isClean = true; // } // } // } // /** // * @deprecated 将要执行动画的view 添加到动画层 // * @param vg // * 动画运行的层 这里是frameLayout // * @param view // * 要运行动画的View // * @param location // * 动画的起始位置 // * @return // */ // private View addViewToAnimLayout(ViewGroup vg, View view, int[] location){ // int x = location[0]; // int y = location[1]; // vg.addView(view); // LayoutParams lp = new LayoutParams( // DensityUtils.dp2px(context,30), DensityUtils.dp2px(context,30)); // lp.leftMargin = x; // lp.topMargin = y; // view.setPadding(5, 5, 5, 5); // view.setLayoutParams(lp); // // return view; // } // }
import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.xd.demi.R; import com.xd.demi.view.ShopCarLayout;
package com.xd.demi.activity; /** * Created by demi on 16/12/16. */ public class ShopCarActivity extends Activity { TextView tv_myDr; ImageView iv1; ImageView iv2; ImageView iv3; ImageView iv4;
// Path: app/src/main/java/com/xd/demi/view/ShopCarLayout.java // public class ShopCarLayout extends FrameLayout { // //动画时间 // private int animationDuration = 1000; // //正在执行的动画数量 // private int number = 0; // //是否完成清理 // private boolean isClean = false; // private Context context ; // public ShopCarLayout(Context context) { // super(context); // this.context =context ; // ViewGroup rootView = (ViewGroup) ((Activity)context).getWindow().getDecorView(); // LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); // setLayoutParams(lp); // setBackgroundResource(android.R.color.transparent); // rootView.addView(this); // } // /** // * 动画效果设置 // * @param drawable // * 将要加入购物车的商品 // * @param start_location // * 起始位置 // */ // private void setAnim(Drawable drawable, int[] start_location,View finish_view){ // // // Animation mScaleAnimation = new ScaleAnimation(1.5f,0.0f,1.5f,0.0f,Animation.RELATIVE_TO_SELF,0.1f,Animation.RELATIVE_TO_SELF,0.1f); // mScaleAnimation.setDuration(animationDuration); // mScaleAnimation.setFillAfter(true); // // // final CircleImageView iview = new CircleImageView(context); // iview.setImageDrawable(drawable); // final View view = addViewToAnimLayout(this,iview,start_location); // view.setAlpha(0.6f); // // int[] end_location = new int[2]; // finish_view.getLocationInWindow(end_location); // int endX = end_location[0]-start_location[0]+finish_view.getWidth()/2; // int endY = end_location[1]-start_location[1]+finish_view.getHeight()/2; // // Animation mTranslateAnimation = new TranslateAnimation(0,endX,0,endY); // Animation mRotateAnimation = new RotateAnimation(0, 180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); // mRotateAnimation.setDuration(animationDuration); // mTranslateAnimation.setDuration(animationDuration); // AnimationSet mAnimationSet = new AnimationSet(true); // // mAnimationSet.setFillAfter(true); // mAnimationSet.addAnimation(mRotateAnimation); // mAnimationSet.addAnimation(mScaleAnimation); // mAnimationSet.addAnimation(mTranslateAnimation); // // mAnimationSet.setAnimationListener(new Animation.AnimationListener(){ // // @Override // public void onAnimationStart(Animation animation) { // // TODO Auto-generated method stub // number++; // } // // @Override // public void onAnimationEnd(Animation animation) { // // TODO Auto-generated method stub // // number--; // if(number==0){ // isClean = true; // removeAllViews(); // isClean =false; // } // // } // // @Override // public void onAnimationRepeat(Animation animation) { // // TODO Auto-generated method stub // // } // // }); // iview.startAnimation(mAnimationSet); // // } // // // public void doAnim(Drawable drawable, int[] start_location,View finish_view){ // if(!isClean){ // setAnim(drawable,start_location,finish_view); // }else{ // try{ // removeAllViews(); // isClean = false; // setAnim(drawable,start_location,finish_view); // }catch(Exception e){ // e.printStackTrace(); // } // finally{ // isClean = true; // } // } // } // /** // * @deprecated 将要执行动画的view 添加到动画层 // * @param vg // * 动画运行的层 这里是frameLayout // * @param view // * 要运行动画的View // * @param location // * 动画的起始位置 // * @return // */ // private View addViewToAnimLayout(ViewGroup vg, View view, int[] location){ // int x = location[0]; // int y = location[1]; // vg.addView(view); // LayoutParams lp = new LayoutParams( // DensityUtils.dp2px(context,30), DensityUtils.dp2px(context,30)); // lp.leftMargin = x; // lp.topMargin = y; // view.setPadding(5, 5, 5, 5); // view.setLayoutParams(lp); // // return view; // } // } // Path: app/src/main/java/com/xd/demi/activity/ShopCarActivity.java import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.xd.demi.R; import com.xd.demi.view.ShopCarLayout; package com.xd.demi.activity; /** * Created by demi on 16/12/16. */ public class ShopCarActivity extends Activity { TextView tv_myDr; ImageView iv1; ImageView iv2; ImageView iv3; ImageView iv4;
private ShopCarLayout shopCarLayout;
Demidong/ClockView
app/src/main/java/com/xd/demi/view/NinePointView.java
// Path: app/src/main/java/com/xd/demi/bean/Point.java // public class Point implements Serializable{ // private float x ; // private float y ; // // public float getX() { // return x; // } // // public void setX(float x) { // this.x = x; // } // // public float getY() { // return y; // } // // public void setY(float y) { // this.y = y; // } // // public Point(float x, float y) { // this.x = x; // this.y = y; // } // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import com.xd.demi.bean.Point; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set;
package com.xd.demi.view; /** * Created by demi on 2017/3/14. */ public class NinePointView extends View { private Paint pointPaint;
// Path: app/src/main/java/com/xd/demi/bean/Point.java // public class Point implements Serializable{ // private float x ; // private float y ; // // public float getX() { // return x; // } // // public void setX(float x) { // this.x = x; // } // // public float getY() { // return y; // } // // public void setY(float y) { // this.y = y; // } // // public Point(float x, float y) { // this.x = x; // this.y = y; // } // } // Path: app/src/main/java/com/xd/demi/view/NinePointView.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import com.xd.demi.bean.Point; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; package com.xd.demi.view; /** * Created by demi on 2017/3/14. */ public class NinePointView extends View { private Paint pointPaint;
private LinkedHashMap<String,Point> points = new LinkedHashMap<>();
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/label/SearchLabelsPage.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java // public abstract class SearchPage implements Page { // // protected String url; // // private String query; // // public SearchPage(String url) { // this.url = url; // } // // public String getSubtitle() throws IOException { // return "Общо " + getItems().length + " резултата"; // } // // public int getItemsCount() throws IOException { // return getItems().length; // } // // public Item[] getItems(int index, int length) throws IOException { // int len = Math.min(length, getItems().length - index); // Item[] result = new Item[len]; // System.arraycopy(getItems(), index, result, 0, len); // return result; // } // // public Item getItem(int index) throws IOException { // return getItems()[index]; // } // // protected String getQuery() throws IOException { // if (query == null) { // String urlQuery = new URL(url).getQuery(); // // remove all params after the first one // int ampIndex = urlQuery.indexOf('&'); // if (ampIndex != -1) { // urlQuery = urlQuery.substring(0, ampIndex); // } // // extract the value of the first param // int eqIndex = urlQuery.indexOf('='); // if (eqIndex != -1) { // query = urlQuery.substring(eqIndex + 1); // } // } // return query; // } // // }
import name.raev.kaloyan.kindle.chitanka.model.Item; import name.raev.kaloyan.kindle.chitanka.model.search.SearchPage; import java.io.IOException; import org.json.simple.parser.ParseException;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.label; public class SearchLabelsPage extends SearchPage { private Label[] labels;
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java // public abstract class SearchPage implements Page { // // protected String url; // // private String query; // // public SearchPage(String url) { // this.url = url; // } // // public String getSubtitle() throws IOException { // return "Общо " + getItems().length + " резултата"; // } // // public int getItemsCount() throws IOException { // return getItems().length; // } // // public Item[] getItems(int index, int length) throws IOException { // int len = Math.min(length, getItems().length - index); // Item[] result = new Item[len]; // System.arraycopy(getItems(), index, result, 0, len); // return result; // } // // public Item getItem(int index) throws IOException { // return getItems()[index]; // } // // protected String getQuery() throws IOException { // if (query == null) { // String urlQuery = new URL(url).getQuery(); // // remove all params after the first one // int ampIndex = urlQuery.indexOf('&'); // if (ampIndex != -1) { // urlQuery = urlQuery.substring(0, ampIndex); // } // // extract the value of the first param // int eqIndex = urlQuery.indexOf('='); // if (eqIndex != -1) { // query = urlQuery.substring(eqIndex + 1); // } // } // return query; // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/label/SearchLabelsPage.java import name.raev.kaloyan.kindle.chitanka.model.Item; import name.raev.kaloyan.kindle.chitanka.model.search.SearchPage; import java.io.IOException; import org.json.simple.parser.ParseException; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.label; public class SearchLabelsPage extends SearchPage { private Label[] labels;
private Item[] items;
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/category/SearchCategories.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/BaseContentHandler.java // public class BaseContentHandler implements ContentHandler { // // protected Stack objects = new Stack(); // // public void startJSON() throws ParseException, IOException { // } // // public void endJSON() throws ParseException, IOException { // } // // public boolean startArray() throws ParseException, IOException { // return true; // } // // public boolean endArray() throws ParseException, IOException { // return true; // } // // public boolean startObject() throws ParseException, IOException { // return true; // } // // public boolean endObject() throws ParseException, IOException { // return true; // } // // public boolean startObjectEntry(String key) throws ParseException, IOException { // objects.push(key); // return true; // } // // public boolean endObjectEntry() throws ParseException, IOException { // objects.pop(); // return true; // } // // public boolean primitive(Object value) throws ParseException, IOException { // return true; // } // // protected String getParentKey() { // return objects.isEmpty() ? null : (String) objects.peek(); // } // // protected String getParentKey(int depth) { // return (objects.size() < depth) ? null : (String) objects.elementAt(objects.size() - 2); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java // public abstract class SearchParser { // // protected abstract ContentHandler getContentHandler(); // // protected void parse(String url) throws IOException, ParseException { // Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url))); // // new JSONParser().parse(reader, getContentHandler()); // } // // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.model.search.BaseContentHandler; import name.raev.kaloyan.kindle.chitanka.model.search.SearchParser;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.category; public class SearchCategories extends SearchParser { private static final String CATEGORIES_KEY = "categories"; private List categories = new ArrayList(); public SearchCategories(String url) throws IOException, ParseException { parse(url); } public Category[] getCategories() { return (Category[]) categories.toArray(new Category[categories.size()]); } protected ContentHandler getContentHandler() {
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/BaseContentHandler.java // public class BaseContentHandler implements ContentHandler { // // protected Stack objects = new Stack(); // // public void startJSON() throws ParseException, IOException { // } // // public void endJSON() throws ParseException, IOException { // } // // public boolean startArray() throws ParseException, IOException { // return true; // } // // public boolean endArray() throws ParseException, IOException { // return true; // } // // public boolean startObject() throws ParseException, IOException { // return true; // } // // public boolean endObject() throws ParseException, IOException { // return true; // } // // public boolean startObjectEntry(String key) throws ParseException, IOException { // objects.push(key); // return true; // } // // public boolean endObjectEntry() throws ParseException, IOException { // objects.pop(); // return true; // } // // public boolean primitive(Object value) throws ParseException, IOException { // return true; // } // // protected String getParentKey() { // return objects.isEmpty() ? null : (String) objects.peek(); // } // // protected String getParentKey(int depth) { // return (objects.size() < depth) ? null : (String) objects.elementAt(objects.size() - 2); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java // public abstract class SearchParser { // // protected abstract ContentHandler getContentHandler(); // // protected void parse(String url) throws IOException, ParseException { // Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url))); // // new JSONParser().parse(reader, getContentHandler()); // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/category/SearchCategories.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.model.search.BaseContentHandler; import name.raev.kaloyan.kindle.chitanka.model.search.SearchParser; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.category; public class SearchCategories extends SearchParser { private static final String CATEGORIES_KEY = "categories"; private List categories = new ArrayList(); public SearchCategories(String url) throws IOException, ParseException { parse(url); } public Category[] getCategories() { return (Category[]) categories.toArray(new Category[categories.size()]); } protected ContentHandler getContentHandler() {
return new BaseContentHandler() {
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/utils/Network.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/ConnectivityManager.java // public class ConnectivityManager { // // public static final String BASE_URL = "http://chitanka.info"; // // private static ConnectivityManager instance; // // private Stack history = new Stack(); // // public static ConnectivityManager getInstance() { // if (instance == null) { // instance = new ConnectivityManager(); // } // return instance; // } // // public void display(final String url) { // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // display(url); // } // // public void connected() throws InterruptedException { // Screen screen = ScreenManager.createScreen(url); // try { // screen.display(); // } catch (IOException e) { // handleNetworkError(); // display(url); // } // // ScreenManager.setCurrentScreen(screen); // } // }, true); // } // // public void downloadBook(final String href) { // ProgressIndicator.start("Книгата се изтегля"); // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // downloadBook(href); // } // // public void connected() throws InterruptedException { // try { // BookDownloader.downloadMobiFromEpubUrl(href); // BookDownloader.rescanDocuments(); // } catch (IOException e) { // handleNetworkError(); // downloadBook(href); // return; // } finally { // ProgressIndicator.stop(); // } // // // show info message // String title = "Книгата е изтеглена"; // String message = "Ще намерите книгата в началото на главния екран на Kindle. Натиснете бутона Home, за да преминете към главния екран."; // DialogManager.displayDialog(message, title); // } // }, true); // // } // // public boolean canGoBack() { // return history.size() > 1; // } // // public void goBack() { // if (canGoBack()) { // // remove the current page from history // history.pop(); // // display the previous page from history // display((String) history.peek()); // } // } // // public void navigateTo(String link) { // String url = Network.getUrlFromLinkAsString(link); // // push to history // history.push(url); // // navigate to the selected page // display(url); // } // // public void handleNetworkError() throws InterruptedException { // ProgressIndicator.stop(); // String title = "Неуспешно свързване"; // String message = "Приложението не може да се свърже с мрежата. Уверете се, че сте в обхвата на безжична мрежа.\n\nЗатворете това съобщение, за да опитате отново."; // DialogManager.displayDialog(message, title); // } // // }
import name.raev.kaloyan.kindle.chitanka.ConnectivityManager; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Properties; import java.util.zip.GZIPInputStream;
*/ public static void readToFile(URL url, File file) throws IOException { readToFile(getInputStream(url), file); } private static void readToFile(InputStream in, File file) throws IOException { OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { byte[] b = new byte[4096]; int bytesRead; while ((bytesRead = in.read(b)) != -1) { out.write(b, 0, bytesRead); } } finally { in.close(); out.flush(); out.close(); } } /** * Returns a URL object from the given hyperlink. * * @param url * a hyperlink as <code>String</code> object * @return a <code>URL</code> object * @throws MalformedURLException * if the URL cannot be created successfully */ public static URL getUrlFromLink(String link) throws MalformedURLException {
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/ConnectivityManager.java // public class ConnectivityManager { // // public static final String BASE_URL = "http://chitanka.info"; // // private static ConnectivityManager instance; // // private Stack history = new Stack(); // // public static ConnectivityManager getInstance() { // if (instance == null) { // instance = new ConnectivityManager(); // } // return instance; // } // // public void display(final String url) { // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // display(url); // } // // public void connected() throws InterruptedException { // Screen screen = ScreenManager.createScreen(url); // try { // screen.display(); // } catch (IOException e) { // handleNetworkError(); // display(url); // } // // ScreenManager.setCurrentScreen(screen); // } // }, true); // } // // public void downloadBook(final String href) { // ProgressIndicator.start("Книгата се изтегля"); // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // downloadBook(href); // } // // public void connected() throws InterruptedException { // try { // BookDownloader.downloadMobiFromEpubUrl(href); // BookDownloader.rescanDocuments(); // } catch (IOException e) { // handleNetworkError(); // downloadBook(href); // return; // } finally { // ProgressIndicator.stop(); // } // // // show info message // String title = "Книгата е изтеглена"; // String message = "Ще намерите книгата в началото на главния екран на Kindle. Натиснете бутона Home, за да преминете към главния екран."; // DialogManager.displayDialog(message, title); // } // }, true); // // } // // public boolean canGoBack() { // return history.size() > 1; // } // // public void goBack() { // if (canGoBack()) { // // remove the current page from history // history.pop(); // // display the previous page from history // display((String) history.peek()); // } // } // // public void navigateTo(String link) { // String url = Network.getUrlFromLinkAsString(link); // // push to history // history.push(url); // // navigate to the selected page // display(url); // } // // public void handleNetworkError() throws InterruptedException { // ProgressIndicator.stop(); // String title = "Неуспешно свързване"; // String message = "Приложението не може да се свърже с мрежата. Уверете се, че сте в обхвата на безжична мрежа.\n\nЗатворете това съобщение, за да опитате отново."; // DialogManager.displayDialog(message, title); // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/utils/Network.java import name.raev.kaloyan.kindle.chitanka.ConnectivityManager; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Properties; import java.util.zip.GZIPInputStream; */ public static void readToFile(URL url, File file) throws IOException { readToFile(getInputStream(url), file); } private static void readToFile(InputStream in, File file) throws IOException { OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { byte[] b = new byte[4096]; int bytesRead; while ((bytesRead = in.read(b)) != -1) { out.write(b, 0, bytesRead); } } finally { in.close(); out.flush(); out.close(); } } /** * Returns a URL object from the given hyperlink. * * @param url * a hyperlink as <code>String</code> object * @return a <code>URL</code> object * @throws MalformedURLException * if the URL cannot be created successfully */ public static URL getUrlFromLink(String link) throws MalformedURLException {
return new URL(new URL(ConnectivityManager.BASE_URL), link);
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/ChitankaKindlet.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/screen/ScreenManager.java // public class ScreenManager { // // private static Screen currentScreen; // // public static Screen createScreen(String url) { // try { // URL u = new URL(url); // String path = u.getPath(); // // if ("/catalog.opds".equals(path)) { // return new HomeScreen(new OpdsPage(url)); // } else if ("/authors.opds".equals(path) // || "/translators.opds".equals(path) // || "/books.opds".equals(path) || "/texts.opds".equals(path)) { // return new ShortListScreen(new OpdsPage(url)); // } else if ("/authors/first-name.opds".equals(path) // || "/authors/last-name.opds".equals(path) // || "/translators/first-name.opds".equals(path) // || "/translators/last-name.opds".equals(path) // || "/books/alpha.opds".equals(path) // || "/texts/alpha.opds".equals(path) // || "/series.opds".equals(path) // || "/sequences.opds".equals(path)) { // return new AlphaScreen(new OpdsPage(url)); // } else if ("/books/category.opds".equals(path) // || "/texts/label.opds".equals(path) // || "/texts/type.opds".equals(path) // || path.indexOf("/country/") != -1 // || path.indexOf("/first-name/") != -1 // || path.indexOf("/last-name/") != -1 // || path.indexOf("/series/alpha/") != -1 // || path.indexOf("/sequences/alpha/") != -1) { // return new LongListScreen(new OpdsPage(url)); // } else if (path.indexOf("/search.json") != -1) { // String query = u.getQuery(); // if (query.endsWith("&filter=texts")) { // return new BookListScreen(new SearchTextsPage(url)); // } else if (query.endsWith("&filter=persons")) { // return new LongListScreen(new SearchPersonsPage(url)); // } else if (query.endsWith("&filter=categories")) { // return new LongListScreen(new SearchCategoriesPage(url)); // } else if (query.endsWith("&filter=sequences")) { // return new LongListScreen(new SearchSequencesPage(url)); // } else if (query.endsWith("&filter=series")) { // return new LongListScreen(new SearchSeriesPage(url)); // } else if (query.endsWith("&filter=labels")) { // return new LongListScreen(new SearchLabelsPage(url)); // } else { // return new ShortListScreen(new SearchOverviewPage(url)); // } // } // } catch (MalformedURLException e) { // // return the default screen // } // // // default screen // return new BookListScreen(new OpdsPage(url)); // } // // public static void setCurrentScreen(Screen screen) { // currentScreen = screen; // } // // public static Screen getCurrentScreen() { // return currentScreen; // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/screen/SplashScreen.java // public class SplashScreen extends Screen { // // public SplashScreen() { // super(new NullPage()); // } // // protected int getPageSize() { // return 1; // } // // protected void createContent(Container container) throws IOException { // GridBagConstraints c = new GridBagConstraints(); // c.gridx = 0; // c.gridwidth = GridBagConstraints.REMAINDER; // c.gridy = GridBagConstraints.RELATIVE; // c.weightx = 1.0; // c.weighty = 1.0; // // KLabel label = new KLabel("Зарежда се…"); // container.add(label, c); // } // // protected void updateContent(Container container) { // // nothing to update // } // // }
import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.event.KeyEvent; import java.io.IOException; import com.amazon.kindle.kindlet.AbstractKindlet; import com.amazon.kindle.kindlet.KindletContext; import com.amazon.kindle.kindlet.event.KindleKeyCodes; import name.raev.kaloyan.kindle.chitanka.screen.ScreenManager; import name.raev.kaloyan.kindle.chitanka.screen.SplashScreen;
if (mgr.canGoBack()) { key.consume(); mgr.goBack(); return true; } break; case KindleKeyCodes.VK_LEFT_HAND_SIDE_TURN_PAGE: case KindleKeyCodes.VK_RIGHT_HAND_SIDE_TURN_PAGE: key.consume(); ScreenManager.getCurrentScreen().nextPage(); return true; case KindleKeyCodes.VK_TURN_PAGE_BACK: key.consume(); ScreenManager.getCurrentScreen().previousPage(); return true; case VK_KEYBOARD: ScreenManager.getCurrentScreen().focusOnSearch(); return true; } return false; } }); } public void start() { try {
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/screen/ScreenManager.java // public class ScreenManager { // // private static Screen currentScreen; // // public static Screen createScreen(String url) { // try { // URL u = new URL(url); // String path = u.getPath(); // // if ("/catalog.opds".equals(path)) { // return new HomeScreen(new OpdsPage(url)); // } else if ("/authors.opds".equals(path) // || "/translators.opds".equals(path) // || "/books.opds".equals(path) || "/texts.opds".equals(path)) { // return new ShortListScreen(new OpdsPage(url)); // } else if ("/authors/first-name.opds".equals(path) // || "/authors/last-name.opds".equals(path) // || "/translators/first-name.opds".equals(path) // || "/translators/last-name.opds".equals(path) // || "/books/alpha.opds".equals(path) // || "/texts/alpha.opds".equals(path) // || "/series.opds".equals(path) // || "/sequences.opds".equals(path)) { // return new AlphaScreen(new OpdsPage(url)); // } else if ("/books/category.opds".equals(path) // || "/texts/label.opds".equals(path) // || "/texts/type.opds".equals(path) // || path.indexOf("/country/") != -1 // || path.indexOf("/first-name/") != -1 // || path.indexOf("/last-name/") != -1 // || path.indexOf("/series/alpha/") != -1 // || path.indexOf("/sequences/alpha/") != -1) { // return new LongListScreen(new OpdsPage(url)); // } else if (path.indexOf("/search.json") != -1) { // String query = u.getQuery(); // if (query.endsWith("&filter=texts")) { // return new BookListScreen(new SearchTextsPage(url)); // } else if (query.endsWith("&filter=persons")) { // return new LongListScreen(new SearchPersonsPage(url)); // } else if (query.endsWith("&filter=categories")) { // return new LongListScreen(new SearchCategoriesPage(url)); // } else if (query.endsWith("&filter=sequences")) { // return new LongListScreen(new SearchSequencesPage(url)); // } else if (query.endsWith("&filter=series")) { // return new LongListScreen(new SearchSeriesPage(url)); // } else if (query.endsWith("&filter=labels")) { // return new LongListScreen(new SearchLabelsPage(url)); // } else { // return new ShortListScreen(new SearchOverviewPage(url)); // } // } // } catch (MalformedURLException e) { // // return the default screen // } // // // default screen // return new BookListScreen(new OpdsPage(url)); // } // // public static void setCurrentScreen(Screen screen) { // currentScreen = screen; // } // // public static Screen getCurrentScreen() { // return currentScreen; // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/screen/SplashScreen.java // public class SplashScreen extends Screen { // // public SplashScreen() { // super(new NullPage()); // } // // protected int getPageSize() { // return 1; // } // // protected void createContent(Container container) throws IOException { // GridBagConstraints c = new GridBagConstraints(); // c.gridx = 0; // c.gridwidth = GridBagConstraints.REMAINDER; // c.gridy = GridBagConstraints.RELATIVE; // c.weightx = 1.0; // c.weighty = 1.0; // // KLabel label = new KLabel("Зарежда се…"); // container.add(label, c); // } // // protected void updateContent(Container container) { // // nothing to update // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/ChitankaKindlet.java import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.event.KeyEvent; import java.io.IOException; import com.amazon.kindle.kindlet.AbstractKindlet; import com.amazon.kindle.kindlet.KindletContext; import com.amazon.kindle.kindlet.event.KindleKeyCodes; import name.raev.kaloyan.kindle.chitanka.screen.ScreenManager; import name.raev.kaloyan.kindle.chitanka.screen.SplashScreen; if (mgr.canGoBack()) { key.consume(); mgr.goBack(); return true; } break; case KindleKeyCodes.VK_LEFT_HAND_SIDE_TURN_PAGE: case KindleKeyCodes.VK_RIGHT_HAND_SIDE_TURN_PAGE: key.consume(); ScreenManager.getCurrentScreen().nextPage(); return true; case KindleKeyCodes.VK_TURN_PAGE_BACK: key.consume(); ScreenManager.getCurrentScreen().previousPage(); return true; case VK_KEYBOARD: ScreenManager.getCurrentScreen().focusOnSearch(); return true; } return false; } }); } public void start() { try {
new SplashScreen().display();
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/person/SearchPersonsPage.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java // public abstract class SearchPage implements Page { // // protected String url; // // private String query; // // public SearchPage(String url) { // this.url = url; // } // // public String getSubtitle() throws IOException { // return "Общо " + getItems().length + " резултата"; // } // // public int getItemsCount() throws IOException { // return getItems().length; // } // // public Item[] getItems(int index, int length) throws IOException { // int len = Math.min(length, getItems().length - index); // Item[] result = new Item[len]; // System.arraycopy(getItems(), index, result, 0, len); // return result; // } // // public Item getItem(int index) throws IOException { // return getItems()[index]; // } // // protected String getQuery() throws IOException { // if (query == null) { // String urlQuery = new URL(url).getQuery(); // // remove all params after the first one // int ampIndex = urlQuery.indexOf('&'); // if (ampIndex != -1) { // urlQuery = urlQuery.substring(0, ampIndex); // } // // extract the value of the first param // int eqIndex = urlQuery.indexOf('='); // if (eqIndex != -1) { // query = urlQuery.substring(eqIndex + 1); // } // } // return query; // } // // }
import name.raev.kaloyan.kindle.chitanka.model.Item; import name.raev.kaloyan.kindle.chitanka.model.search.SearchPage; import java.io.IOException; import org.json.simple.parser.ParseException;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.person; public class SearchPersonsPage extends SearchPage { private Person[] persons;
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java // public abstract class SearchPage implements Page { // // protected String url; // // private String query; // // public SearchPage(String url) { // this.url = url; // } // // public String getSubtitle() throws IOException { // return "Общо " + getItems().length + " резултата"; // } // // public int getItemsCount() throws IOException { // return getItems().length; // } // // public Item[] getItems(int index, int length) throws IOException { // int len = Math.min(length, getItems().length - index); // Item[] result = new Item[len]; // System.arraycopy(getItems(), index, result, 0, len); // return result; // } // // public Item getItem(int index) throws IOException { // return getItems()[index]; // } // // protected String getQuery() throws IOException { // if (query == null) { // String urlQuery = new URL(url).getQuery(); // // remove all params after the first one // int ampIndex = urlQuery.indexOf('&'); // if (ampIndex != -1) { // urlQuery = urlQuery.substring(0, ampIndex); // } // // extract the value of the first param // int eqIndex = urlQuery.indexOf('='); // if (eqIndex != -1) { // query = urlQuery.substring(eqIndex + 1); // } // } // return query; // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/person/SearchPersonsPage.java import name.raev.kaloyan.kindle.chitanka.model.Item; import name.raev.kaloyan.kindle.chitanka.model.search.SearchPage; import java.io.IOException; import org.json.simple.parser.ParseException; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.person; public class SearchPersonsPage extends SearchPage { private Person[] persons;
private Item[] items;
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/overview/SearchOverview.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/BaseContentHandler.java // public class BaseContentHandler implements ContentHandler { // // protected Stack objects = new Stack(); // // public void startJSON() throws ParseException, IOException { // } // // public void endJSON() throws ParseException, IOException { // } // // public boolean startArray() throws ParseException, IOException { // return true; // } // // public boolean endArray() throws ParseException, IOException { // return true; // } // // public boolean startObject() throws ParseException, IOException { // return true; // } // // public boolean endObject() throws ParseException, IOException { // return true; // } // // public boolean startObjectEntry(String key) throws ParseException, IOException { // objects.push(key); // return true; // } // // public boolean endObjectEntry() throws ParseException, IOException { // objects.pop(); // return true; // } // // public boolean primitive(Object value) throws ParseException, IOException { // return true; // } // // protected String getParentKey() { // return objects.isEmpty() ? null : (String) objects.peek(); // } // // protected String getParentKey(int depth) { // return (objects.size() < depth) ? null : (String) objects.elementAt(objects.size() - 2); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java // public abstract class SearchParser { // // protected abstract ContentHandler getContentHandler(); // // protected void parse(String url) throws IOException, ParseException { // Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url))); // // new JSONParser().parse(reader, getContentHandler()); // } // // }
import java.io.IOException; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.model.search.BaseContentHandler; import name.raev.kaloyan.kindle.chitanka.model.search.SearchParser;
public int getPersons() { return persons; } public int getTexts() { return texts; } public int getBooks() { return books; } public int getSeries() { return series; } public int getSequences() { return sequences; } public int getLabels() { return labels; } public int getCategories() { return categories; } protected ContentHandler getContentHandler() {
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/BaseContentHandler.java // public class BaseContentHandler implements ContentHandler { // // protected Stack objects = new Stack(); // // public void startJSON() throws ParseException, IOException { // } // // public void endJSON() throws ParseException, IOException { // } // // public boolean startArray() throws ParseException, IOException { // return true; // } // // public boolean endArray() throws ParseException, IOException { // return true; // } // // public boolean startObject() throws ParseException, IOException { // return true; // } // // public boolean endObject() throws ParseException, IOException { // return true; // } // // public boolean startObjectEntry(String key) throws ParseException, IOException { // objects.push(key); // return true; // } // // public boolean endObjectEntry() throws ParseException, IOException { // objects.pop(); // return true; // } // // public boolean primitive(Object value) throws ParseException, IOException { // return true; // } // // protected String getParentKey() { // return objects.isEmpty() ? null : (String) objects.peek(); // } // // protected String getParentKey(int depth) { // return (objects.size() < depth) ? null : (String) objects.elementAt(objects.size() - 2); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java // public abstract class SearchParser { // // protected abstract ContentHandler getContentHandler(); // // protected void parse(String url) throws IOException, ParseException { // Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url))); // // new JSONParser().parse(reader, getContentHandler()); // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/overview/SearchOverview.java import java.io.IOException; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.model.search.BaseContentHandler; import name.raev.kaloyan.kindle.chitanka.model.search.SearchParser; public int getPersons() { return persons; } public int getTexts() { return texts; } public int getBooks() { return books; } public int getSeries() { return series; } public int getSequences() { return sequences; } public int getLabels() { return labels; } public int getCategories() { return categories; } protected ContentHandler getContentHandler() {
return new BaseContentHandler() {
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Page.java // public interface Page { // // public String getTitle() throws IOException; // // public String getSubtitle() throws IOException; // // public int getItemsCount() throws IOException; // // public Item[] getItems() throws IOException; // // public Item[] getItems(int index, int length) throws IOException; // // public Item getItem(int index) throws IOException; // // }
import name.raev.kaloyan.kindle.chitanka.model.Page; import java.io.IOException; import java.net.URL; import name.raev.kaloyan.kindle.chitanka.model.Item;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search; public abstract class SearchPage implements Page { protected String url; private String query; public SearchPage(String url) { this.url = url; } public String getSubtitle() throws IOException { return "Общо " + getItems().length + " резултата"; } public int getItemsCount() throws IOException { return getItems().length; }
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Page.java // public interface Page { // // public String getTitle() throws IOException; // // public String getSubtitle() throws IOException; // // public int getItemsCount() throws IOException; // // public Item[] getItems() throws IOException; // // public Item[] getItems(int index, int length) throws IOException; // // public Item getItem(int index) throws IOException; // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java import name.raev.kaloyan.kindle.chitanka.model.Page; import java.io.IOException; import java.net.URL; import name.raev.kaloyan.kindle.chitanka.model.Item; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search; public abstract class SearchPage implements Page { protected String url; private String query; public SearchPage(String url) { this.url = url; } public String getSubtitle() throws IOException { return "Общо " + getItems().length + " резултата"; } public int getItemsCount() throws IOException { return getItems().length; }
public Item[] getItems(int index, int length) throws IOException {
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/text/SearchTexts.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/BaseContentHandler.java // public class BaseContentHandler implements ContentHandler { // // protected Stack objects = new Stack(); // // public void startJSON() throws ParseException, IOException { // } // // public void endJSON() throws ParseException, IOException { // } // // public boolean startArray() throws ParseException, IOException { // return true; // } // // public boolean endArray() throws ParseException, IOException { // return true; // } // // public boolean startObject() throws ParseException, IOException { // return true; // } // // public boolean endObject() throws ParseException, IOException { // return true; // } // // public boolean startObjectEntry(String key) throws ParseException, IOException { // objects.push(key); // return true; // } // // public boolean endObjectEntry() throws ParseException, IOException { // objects.pop(); // return true; // } // // public boolean primitive(Object value) throws ParseException, IOException { // return true; // } // // protected String getParentKey() { // return objects.isEmpty() ? null : (String) objects.peek(); // } // // protected String getParentKey(int depth) { // return (objects.size() < depth) ? null : (String) objects.elementAt(objects.size() - 2); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java // public abstract class SearchParser { // // protected abstract ContentHandler getContentHandler(); // // protected void parse(String url) throws IOException, ParseException { // Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url))); // // new JSONParser().parse(reader, getContentHandler()); // } // // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.model.search.BaseContentHandler; import name.raev.kaloyan.kindle.chitanka.model.search.SearchParser;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.text; public class SearchTexts extends SearchParser { private static final String TEXTS_KEY = "texts"; private List texts = new ArrayList(); public SearchTexts(String url) throws IOException, ParseException { parse(url); } public Text[] getTexts() { return (Text[]) texts.toArray(new Text[texts.size()]); } protected ContentHandler getContentHandler() {
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/BaseContentHandler.java // public class BaseContentHandler implements ContentHandler { // // protected Stack objects = new Stack(); // // public void startJSON() throws ParseException, IOException { // } // // public void endJSON() throws ParseException, IOException { // } // // public boolean startArray() throws ParseException, IOException { // return true; // } // // public boolean endArray() throws ParseException, IOException { // return true; // } // // public boolean startObject() throws ParseException, IOException { // return true; // } // // public boolean endObject() throws ParseException, IOException { // return true; // } // // public boolean startObjectEntry(String key) throws ParseException, IOException { // objects.push(key); // return true; // } // // public boolean endObjectEntry() throws ParseException, IOException { // objects.pop(); // return true; // } // // public boolean primitive(Object value) throws ParseException, IOException { // return true; // } // // protected String getParentKey() { // return objects.isEmpty() ? null : (String) objects.peek(); // } // // protected String getParentKey(int depth) { // return (objects.size() < depth) ? null : (String) objects.elementAt(objects.size() - 2); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java // public abstract class SearchParser { // // protected abstract ContentHandler getContentHandler(); // // protected void parse(String url) throws IOException, ParseException { // Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url))); // // new JSONParser().parse(reader, getContentHandler()); // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/text/SearchTexts.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.model.search.BaseContentHandler; import name.raev.kaloyan.kindle.chitanka.model.search.SearchParser; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.text; public class SearchTexts extends SearchParser { private static final String TEXTS_KEY = "texts"; private List texts = new ArrayList(); public SearchTexts(String url) throws IOException, ParseException { parse(url); } public Text[] getTexts() { return (Text[]) texts.toArray(new Text[texts.size()]); } protected ContentHandler getContentHandler() {
return new BaseContentHandler() {
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/person/SearchPersons.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/BaseContentHandler.java // public class BaseContentHandler implements ContentHandler { // // protected Stack objects = new Stack(); // // public void startJSON() throws ParseException, IOException { // } // // public void endJSON() throws ParseException, IOException { // } // // public boolean startArray() throws ParseException, IOException { // return true; // } // // public boolean endArray() throws ParseException, IOException { // return true; // } // // public boolean startObject() throws ParseException, IOException { // return true; // } // // public boolean endObject() throws ParseException, IOException { // return true; // } // // public boolean startObjectEntry(String key) throws ParseException, IOException { // objects.push(key); // return true; // } // // public boolean endObjectEntry() throws ParseException, IOException { // objects.pop(); // return true; // } // // public boolean primitive(Object value) throws ParseException, IOException { // return true; // } // // protected String getParentKey() { // return objects.isEmpty() ? null : (String) objects.peek(); // } // // protected String getParentKey(int depth) { // return (objects.size() < depth) ? null : (String) objects.elementAt(objects.size() - 2); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java // public abstract class SearchParser { // // protected abstract ContentHandler getContentHandler(); // // protected void parse(String url) throws IOException, ParseException { // Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url))); // // new JSONParser().parse(reader, getContentHandler()); // } // // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.model.search.BaseContentHandler; import name.raev.kaloyan.kindle.chitanka.model.search.SearchParser;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.person; public class SearchPersons extends SearchParser { private static final String PERSONS_KEY = "persons"; private List persons = new ArrayList(); public SearchPersons(String url) throws IOException, ParseException { parse(url); } public Person[] getPersons() { return (Person[]) persons.toArray(new Person[persons.size()]); } protected ContentHandler getContentHandler() {
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/BaseContentHandler.java // public class BaseContentHandler implements ContentHandler { // // protected Stack objects = new Stack(); // // public void startJSON() throws ParseException, IOException { // } // // public void endJSON() throws ParseException, IOException { // } // // public boolean startArray() throws ParseException, IOException { // return true; // } // // public boolean endArray() throws ParseException, IOException { // return true; // } // // public boolean startObject() throws ParseException, IOException { // return true; // } // // public boolean endObject() throws ParseException, IOException { // return true; // } // // public boolean startObjectEntry(String key) throws ParseException, IOException { // objects.push(key); // return true; // } // // public boolean endObjectEntry() throws ParseException, IOException { // objects.pop(); // return true; // } // // public boolean primitive(Object value) throws ParseException, IOException { // return true; // } // // protected String getParentKey() { // return objects.isEmpty() ? null : (String) objects.peek(); // } // // protected String getParentKey(int depth) { // return (objects.size() < depth) ? null : (String) objects.elementAt(objects.size() - 2); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java // public abstract class SearchParser { // // protected abstract ContentHandler getContentHandler(); // // protected void parse(String url) throws IOException, ParseException { // Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url))); // // new JSONParser().parse(reader, getContentHandler()); // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/person/SearchPersons.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.model.search.BaseContentHandler; import name.raev.kaloyan.kindle.chitanka.model.search.SearchParser; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.person; public class SearchPersons extends SearchParser { private static final String PERSONS_KEY = "persons"; private List persons = new ArrayList(); public SearchPersons(String url) throws IOException, ParseException { parse(url); } public Person[] getPersons() { return (Person[]) persons.toArray(new Person[persons.size()]); } protected ContentHandler getContentHandler() {
return new BaseContentHandler() {
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/utils/Network.java // public class Network { // // /** // * Returns an input stream for the given URL. // * // * @param url // * the URL as <code>String</code> object // * @return an <code>InputStream</code> object // * @throws IOException // * if a malformed URL is given or a networking problem occurs // */ // public static InputStream getInputStream(String url) throws IOException { // return getInputStream(new URL(url)); // } // // /** // * Returns an input stream for the given URL. // * // * @param url // * the URL // * @return an <code>InputStream</code> object // * @throws IOException // * if a malformed URL is given or a networking problem occurs // */ // public static InputStream getInputStream(URL url) throws IOException { // if (KindleModel.getModel().hasUnrestricted3G()) { // // prepare a 3G-capable connection // System.setProperty("http.proxyHost", "fints-g7g.amazon.com"); // System.setProperty("http.proxyPort", "80"); // URLConnection conn = url.openConnection(); // conn.setRequestProperty("x-fsn", getXFSN()); // conn.setRequestProperty("User-Agent", // "Mozilla/5.0 (Linux; U; en-US) AppleWebKit/528.5+ (KHTML, like Gecko, Safari/528.5+) Version/4.0 Kindle/3.0 (screen 600x800; rotate)"); // conn.setRequestProperty("Accept", // "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); // conn.setRequestProperty("Accept-Encoding", "gzip"); // conn.setRequestProperty("x-kn-appId", "BBookletV3"); // InputStream in = conn.getInputStream(); // return (url.getPath().indexOf("opds") == -1) ? in : new GZIPInputStream(in); // } else { // // no 3G - open the stream directly to the URL // return url.openStream(); // } // } // // private static String getXFSN() throws IOException { // File cookie = new File( // "/var/local/java/prefs/cookies/Cookie__x-fsn_WITH_DOMAIN__$$cookie.store.domains.cookie"); // if (cookie.exists()) { // Properties props = new Properties(); // props.load(new FileInputStream(cookie)); // return props.getProperty("x-fsn"); // } // return null; // } // // /** // * Reads the content of the resource with the given URL to a file. // * // * @param url // * the URL of the resource to read // * @param file // * the file to save the content to // * @throws IOException // * if a malformed URL is given or a networking or file system // * problem occurs // */ // public static void readToFile(URL url, File file) throws IOException { // readToFile(getInputStream(url), file); // } // // private static void readToFile(InputStream in, File file) throws IOException { // OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); // try { // byte[] b = new byte[4096]; // int bytesRead; // while ((bytesRead = in.read(b)) != -1) { // out.write(b, 0, bytesRead); // } // } finally { // in.close(); // out.flush(); // out.close(); // } // } // // /** // * Returns a URL object from the given hyperlink. // * // * @param url // * a hyperlink as <code>String</code> object // * @return a <code>URL</code> object // * @throws MalformedURLException // * if the URL cannot be created successfully // */ // public static URL getUrlFromLink(String link) throws MalformedURLException { // return new URL(new URL(ConnectivityManager.BASE_URL), link); // } // // /** // * Returns a URL as String object from the given hyperlink. // * // * @param url // * a hyperlink as <code>String</code> object // * @return a URL as <code>String</code> object, or <code>null</code> if the // * URL cannot be created successfully // */ // public static String getUrlFromLinkAsString(String link) { // try { // return getUrlFromLink(link).toString(); // } catch (MalformedURLException e) { // e.printStackTrace(); // return null; // } // } // // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.utils.Network;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search; public abstract class SearchParser { protected abstract ContentHandler getContentHandler(); protected void parse(String url) throws IOException, ParseException {
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/utils/Network.java // public class Network { // // /** // * Returns an input stream for the given URL. // * // * @param url // * the URL as <code>String</code> object // * @return an <code>InputStream</code> object // * @throws IOException // * if a malformed URL is given or a networking problem occurs // */ // public static InputStream getInputStream(String url) throws IOException { // return getInputStream(new URL(url)); // } // // /** // * Returns an input stream for the given URL. // * // * @param url // * the URL // * @return an <code>InputStream</code> object // * @throws IOException // * if a malformed URL is given or a networking problem occurs // */ // public static InputStream getInputStream(URL url) throws IOException { // if (KindleModel.getModel().hasUnrestricted3G()) { // // prepare a 3G-capable connection // System.setProperty("http.proxyHost", "fints-g7g.amazon.com"); // System.setProperty("http.proxyPort", "80"); // URLConnection conn = url.openConnection(); // conn.setRequestProperty("x-fsn", getXFSN()); // conn.setRequestProperty("User-Agent", // "Mozilla/5.0 (Linux; U; en-US) AppleWebKit/528.5+ (KHTML, like Gecko, Safari/528.5+) Version/4.0 Kindle/3.0 (screen 600x800; rotate)"); // conn.setRequestProperty("Accept", // "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); // conn.setRequestProperty("Accept-Encoding", "gzip"); // conn.setRequestProperty("x-kn-appId", "BBookletV3"); // InputStream in = conn.getInputStream(); // return (url.getPath().indexOf("opds") == -1) ? in : new GZIPInputStream(in); // } else { // // no 3G - open the stream directly to the URL // return url.openStream(); // } // } // // private static String getXFSN() throws IOException { // File cookie = new File( // "/var/local/java/prefs/cookies/Cookie__x-fsn_WITH_DOMAIN__$$cookie.store.domains.cookie"); // if (cookie.exists()) { // Properties props = new Properties(); // props.load(new FileInputStream(cookie)); // return props.getProperty("x-fsn"); // } // return null; // } // // /** // * Reads the content of the resource with the given URL to a file. // * // * @param url // * the URL of the resource to read // * @param file // * the file to save the content to // * @throws IOException // * if a malformed URL is given or a networking or file system // * problem occurs // */ // public static void readToFile(URL url, File file) throws IOException { // readToFile(getInputStream(url), file); // } // // private static void readToFile(InputStream in, File file) throws IOException { // OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); // try { // byte[] b = new byte[4096]; // int bytesRead; // while ((bytesRead = in.read(b)) != -1) { // out.write(b, 0, bytesRead); // } // } finally { // in.close(); // out.flush(); // out.close(); // } // } // // /** // * Returns a URL object from the given hyperlink. // * // * @param url // * a hyperlink as <code>String</code> object // * @return a <code>URL</code> object // * @throws MalformedURLException // * if the URL cannot be created successfully // */ // public static URL getUrlFromLink(String link) throws MalformedURLException { // return new URL(new URL(ConnectivityManager.BASE_URL), link); // } // // /** // * Returns a URL as String object from the given hyperlink. // * // * @param url // * a hyperlink as <code>String</code> object // * @return a URL as <code>String</code> object, or <code>null</code> if the // * URL cannot be created successfully // */ // public static String getUrlFromLinkAsString(String link) { // try { // return getUrlFromLink(link).toString(); // } catch (MalformedURLException e) { // e.printStackTrace(); // return null; // } // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.utils.Network; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search; public abstract class SearchParser { protected abstract ContentHandler getContentHandler(); protected void parse(String url) throws IOException, ParseException {
Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url)));
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/sequence/SearchSequences.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/BaseContentHandler.java // public class BaseContentHandler implements ContentHandler { // // protected Stack objects = new Stack(); // // public void startJSON() throws ParseException, IOException { // } // // public void endJSON() throws ParseException, IOException { // } // // public boolean startArray() throws ParseException, IOException { // return true; // } // // public boolean endArray() throws ParseException, IOException { // return true; // } // // public boolean startObject() throws ParseException, IOException { // return true; // } // // public boolean endObject() throws ParseException, IOException { // return true; // } // // public boolean startObjectEntry(String key) throws ParseException, IOException { // objects.push(key); // return true; // } // // public boolean endObjectEntry() throws ParseException, IOException { // objects.pop(); // return true; // } // // public boolean primitive(Object value) throws ParseException, IOException { // return true; // } // // protected String getParentKey() { // return objects.isEmpty() ? null : (String) objects.peek(); // } // // protected String getParentKey(int depth) { // return (objects.size() < depth) ? null : (String) objects.elementAt(objects.size() - 2); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java // public abstract class SearchParser { // // protected abstract ContentHandler getContentHandler(); // // protected void parse(String url) throws IOException, ParseException { // Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url))); // // new JSONParser().parse(reader, getContentHandler()); // } // // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.model.search.BaseContentHandler; import name.raev.kaloyan.kindle.chitanka.model.search.SearchParser;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.sequence; public class SearchSequences extends SearchParser { private static final String SEQUENCES_KEY = "sequences"; private List sequences = new ArrayList(); public SearchSequences(String url) throws IOException, ParseException { parse(url); } public Sequence[] getSequences() { return (Sequence[]) sequences.toArray(new Sequence[sequences.size()]); } protected ContentHandler getContentHandler() {
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/BaseContentHandler.java // public class BaseContentHandler implements ContentHandler { // // protected Stack objects = new Stack(); // // public void startJSON() throws ParseException, IOException { // } // // public void endJSON() throws ParseException, IOException { // } // // public boolean startArray() throws ParseException, IOException { // return true; // } // // public boolean endArray() throws ParseException, IOException { // return true; // } // // public boolean startObject() throws ParseException, IOException { // return true; // } // // public boolean endObject() throws ParseException, IOException { // return true; // } // // public boolean startObjectEntry(String key) throws ParseException, IOException { // objects.push(key); // return true; // } // // public boolean endObjectEntry() throws ParseException, IOException { // objects.pop(); // return true; // } // // public boolean primitive(Object value) throws ParseException, IOException { // return true; // } // // protected String getParentKey() { // return objects.isEmpty() ? null : (String) objects.peek(); // } // // protected String getParentKey(int depth) { // return (objects.size() < depth) ? null : (String) objects.elementAt(objects.size() - 2); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java // public abstract class SearchParser { // // protected abstract ContentHandler getContentHandler(); // // protected void parse(String url) throws IOException, ParseException { // Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url))); // // new JSONParser().parse(reader, getContentHandler()); // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/sequence/SearchSequences.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.model.search.BaseContentHandler; import name.raev.kaloyan.kindle.chitanka.model.search.SearchParser; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.sequence; public class SearchSequences extends SearchParser { private static final String SEQUENCES_KEY = "sequences"; private List sequences = new ArrayList(); public SearchSequences(String url) throws IOException, ParseException { parse(url); } public Sequence[] getSequences() { return (Sequence[]) sequences.toArray(new Sequence[sequences.size()]); } protected ContentHandler getContentHandler() {
return new BaseContentHandler() {
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/label/SearchLabels.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/BaseContentHandler.java // public class BaseContentHandler implements ContentHandler { // // protected Stack objects = new Stack(); // // public void startJSON() throws ParseException, IOException { // } // // public void endJSON() throws ParseException, IOException { // } // // public boolean startArray() throws ParseException, IOException { // return true; // } // // public boolean endArray() throws ParseException, IOException { // return true; // } // // public boolean startObject() throws ParseException, IOException { // return true; // } // // public boolean endObject() throws ParseException, IOException { // return true; // } // // public boolean startObjectEntry(String key) throws ParseException, IOException { // objects.push(key); // return true; // } // // public boolean endObjectEntry() throws ParseException, IOException { // objects.pop(); // return true; // } // // public boolean primitive(Object value) throws ParseException, IOException { // return true; // } // // protected String getParentKey() { // return objects.isEmpty() ? null : (String) objects.peek(); // } // // protected String getParentKey(int depth) { // return (objects.size() < depth) ? null : (String) objects.elementAt(objects.size() - 2); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java // public abstract class SearchParser { // // protected abstract ContentHandler getContentHandler(); // // protected void parse(String url) throws IOException, ParseException { // Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url))); // // new JSONParser().parse(reader, getContentHandler()); // } // // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.model.search.BaseContentHandler; import name.raev.kaloyan.kindle.chitanka.model.search.SearchParser;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.label; public class SearchLabels extends SearchParser { private static final String LABELS_KEY = "labels"; private List labels = new ArrayList(); public SearchLabels(String url) throws IOException, ParseException { parse(url); } public Label[] getLabels() { return (Label[]) labels.toArray(new Label[labels.size()]); } protected ContentHandler getContentHandler() {
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/BaseContentHandler.java // public class BaseContentHandler implements ContentHandler { // // protected Stack objects = new Stack(); // // public void startJSON() throws ParseException, IOException { // } // // public void endJSON() throws ParseException, IOException { // } // // public boolean startArray() throws ParseException, IOException { // return true; // } // // public boolean endArray() throws ParseException, IOException { // return true; // } // // public boolean startObject() throws ParseException, IOException { // return true; // } // // public boolean endObject() throws ParseException, IOException { // return true; // } // // public boolean startObjectEntry(String key) throws ParseException, IOException { // objects.push(key); // return true; // } // // public boolean endObjectEntry() throws ParseException, IOException { // objects.pop(); // return true; // } // // public boolean primitive(Object value) throws ParseException, IOException { // return true; // } // // protected String getParentKey() { // return objects.isEmpty() ? null : (String) objects.peek(); // } // // protected String getParentKey(int depth) { // return (objects.size() < depth) ? null : (String) objects.elementAt(objects.size() - 2); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java // public abstract class SearchParser { // // protected abstract ContentHandler getContentHandler(); // // protected void parse(String url) throws IOException, ParseException { // Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url))); // // new JSONParser().parse(reader, getContentHandler()); // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/label/SearchLabels.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.model.search.BaseContentHandler; import name.raev.kaloyan.kindle.chitanka.model.search.SearchParser; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.label; public class SearchLabels extends SearchParser { private static final String LABELS_KEY = "labels"; private List labels = new ArrayList(); public SearchLabels(String url) throws IOException, ParseException { parse(url); } public Label[] getLabels() { return (Label[]) labels.toArray(new Label[labels.size()]); } protected ContentHandler getContentHandler() {
return new BaseContentHandler() {
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/sequence/SearchSequencesPage.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java // public abstract class SearchPage implements Page { // // protected String url; // // private String query; // // public SearchPage(String url) { // this.url = url; // } // // public String getSubtitle() throws IOException { // return "Общо " + getItems().length + " резултата"; // } // // public int getItemsCount() throws IOException { // return getItems().length; // } // // public Item[] getItems(int index, int length) throws IOException { // int len = Math.min(length, getItems().length - index); // Item[] result = new Item[len]; // System.arraycopy(getItems(), index, result, 0, len); // return result; // } // // public Item getItem(int index) throws IOException { // return getItems()[index]; // } // // protected String getQuery() throws IOException { // if (query == null) { // String urlQuery = new URL(url).getQuery(); // // remove all params after the first one // int ampIndex = urlQuery.indexOf('&'); // if (ampIndex != -1) { // urlQuery = urlQuery.substring(0, ampIndex); // } // // extract the value of the first param // int eqIndex = urlQuery.indexOf('='); // if (eqIndex != -1) { // query = urlQuery.substring(eqIndex + 1); // } // } // return query; // } // // }
import name.raev.kaloyan.kindle.chitanka.model.Item; import name.raev.kaloyan.kindle.chitanka.model.search.SearchPage; import java.io.IOException; import org.json.simple.parser.ParseException;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.sequence; public class SearchSequencesPage extends SearchPage { private Sequence[] sequences;
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java // public abstract class SearchPage implements Page { // // protected String url; // // private String query; // // public SearchPage(String url) { // this.url = url; // } // // public String getSubtitle() throws IOException { // return "Общо " + getItems().length + " резултата"; // } // // public int getItemsCount() throws IOException { // return getItems().length; // } // // public Item[] getItems(int index, int length) throws IOException { // int len = Math.min(length, getItems().length - index); // Item[] result = new Item[len]; // System.arraycopy(getItems(), index, result, 0, len); // return result; // } // // public Item getItem(int index) throws IOException { // return getItems()[index]; // } // // protected String getQuery() throws IOException { // if (query == null) { // String urlQuery = new URL(url).getQuery(); // // remove all params after the first one // int ampIndex = urlQuery.indexOf('&'); // if (ampIndex != -1) { // urlQuery = urlQuery.substring(0, ampIndex); // } // // extract the value of the first param // int eqIndex = urlQuery.indexOf('='); // if (eqIndex != -1) { // query = urlQuery.substring(eqIndex + 1); // } // } // return query; // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/sequence/SearchSequencesPage.java import name.raev.kaloyan.kindle.chitanka.model.Item; import name.raev.kaloyan.kindle.chitanka.model.search.SearchPage; import java.io.IOException; import org.json.simple.parser.ParseException; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.sequence; public class SearchSequencesPage extends SearchPage { private Sequence[] sequences;
private Item[] items;
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/screen/SplashScreen.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/NullPage.java // public class NullPage implements Page { // // public String getTitle() throws IOException { // return null; // } // // public String getSubtitle() throws IOException { // return null; // } // // public int getItemsCount() throws IOException { // return 0; // } // // public Item[] getItems() throws IOException { // return new Item[0]; // } // // public Item[] getItems(int index, int length) throws IOException { // return new Item[0]; // } // // public Item getItem(int index) { // return null; // } // // }
import java.awt.Container; import java.awt.GridBagConstraints; import java.io.IOException; import com.amazon.kindle.kindlet.ui.KLabel; import name.raev.kaloyan.kindle.chitanka.model.NullPage;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.screen; public class SplashScreen extends Screen { public SplashScreen() {
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/NullPage.java // public class NullPage implements Page { // // public String getTitle() throws IOException { // return null; // } // // public String getSubtitle() throws IOException { // return null; // } // // public int getItemsCount() throws IOException { // return 0; // } // // public Item[] getItems() throws IOException { // return new Item[0]; // } // // public Item[] getItems(int index, int length) throws IOException { // return new Item[0]; // } // // public Item getItem(int index) { // return null; // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/screen/SplashScreen.java import java.awt.Container; import java.awt.GridBagConstraints; import java.io.IOException; import com.amazon.kindle.kindlet.ui.KLabel; import name.raev.kaloyan.kindle.chitanka.model.NullPage; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.screen; public class SplashScreen extends Screen { public SplashScreen() {
super(new NullPage());
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/text/SearchTextsPage.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java // public abstract class SearchPage implements Page { // // protected String url; // // private String query; // // public SearchPage(String url) { // this.url = url; // } // // public String getSubtitle() throws IOException { // return "Общо " + getItems().length + " резултата"; // } // // public int getItemsCount() throws IOException { // return getItems().length; // } // // public Item[] getItems(int index, int length) throws IOException { // int len = Math.min(length, getItems().length - index); // Item[] result = new Item[len]; // System.arraycopy(getItems(), index, result, 0, len); // return result; // } // // public Item getItem(int index) throws IOException { // return getItems()[index]; // } // // protected String getQuery() throws IOException { // if (query == null) { // String urlQuery = new URL(url).getQuery(); // // remove all params after the first one // int ampIndex = urlQuery.indexOf('&'); // if (ampIndex != -1) { // urlQuery = urlQuery.substring(0, ampIndex); // } // // extract the value of the first param // int eqIndex = urlQuery.indexOf('='); // if (eqIndex != -1) { // query = urlQuery.substring(eqIndex + 1); // } // } // return query; // } // // }
import name.raev.kaloyan.kindle.chitanka.model.Item; import name.raev.kaloyan.kindle.chitanka.model.search.SearchPage; import java.io.IOException; import org.json.simple.parser.ParseException;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.text; public class SearchTextsPage extends SearchPage { private Text[] texts;
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java // public abstract class SearchPage implements Page { // // protected String url; // // private String query; // // public SearchPage(String url) { // this.url = url; // } // // public String getSubtitle() throws IOException { // return "Общо " + getItems().length + " резултата"; // } // // public int getItemsCount() throws IOException { // return getItems().length; // } // // public Item[] getItems(int index, int length) throws IOException { // int len = Math.min(length, getItems().length - index); // Item[] result = new Item[len]; // System.arraycopy(getItems(), index, result, 0, len); // return result; // } // // public Item getItem(int index) throws IOException { // return getItems()[index]; // } // // protected String getQuery() throws IOException { // if (query == null) { // String urlQuery = new URL(url).getQuery(); // // remove all params after the first one // int ampIndex = urlQuery.indexOf('&'); // if (ampIndex != -1) { // urlQuery = urlQuery.substring(0, ampIndex); // } // // extract the value of the first param // int eqIndex = urlQuery.indexOf('='); // if (eqIndex != -1) { // query = urlQuery.substring(eqIndex + 1); // } // } // return query; // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/text/SearchTextsPage.java import name.raev.kaloyan.kindle.chitanka.model.Item; import name.raev.kaloyan.kindle.chitanka.model.search.SearchPage; import java.io.IOException; import org.json.simple.parser.ParseException; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.text; public class SearchTextsPage extends SearchPage { private Text[] texts;
private Item[] items;
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/overview/SearchOverviewPage.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java // public abstract class SearchPage implements Page { // // protected String url; // // private String query; // // public SearchPage(String url) { // this.url = url; // } // // public String getSubtitle() throws IOException { // return "Общо " + getItems().length + " резултата"; // } // // public int getItemsCount() throws IOException { // return getItems().length; // } // // public Item[] getItems(int index, int length) throws IOException { // int len = Math.min(length, getItems().length - index); // Item[] result = new Item[len]; // System.arraycopy(getItems(), index, result, 0, len); // return result; // } // // public Item getItem(int index) throws IOException { // return getItems()[index]; // } // // protected String getQuery() throws IOException { // if (query == null) { // String urlQuery = new URL(url).getQuery(); // // remove all params after the first one // int ampIndex = urlQuery.indexOf('&'); // if (ampIndex != -1) { // urlQuery = urlQuery.substring(0, ampIndex); // } // // extract the value of the first param // int eqIndex = urlQuery.indexOf('='); // if (eqIndex != -1) { // query = urlQuery.substring(eqIndex + 1); // } // } // return query; // } // // }
import name.raev.kaloyan.kindle.chitanka.model.Item; import name.raev.kaloyan.kindle.chitanka.model.search.SearchPage; import java.io.IOException; import org.json.simple.parser.ParseException;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.overview; public class SearchOverviewPage extends SearchPage { private SearchOverview overview;
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java // public abstract class SearchPage implements Page { // // protected String url; // // private String query; // // public SearchPage(String url) { // this.url = url; // } // // public String getSubtitle() throws IOException { // return "Общо " + getItems().length + " резултата"; // } // // public int getItemsCount() throws IOException { // return getItems().length; // } // // public Item[] getItems(int index, int length) throws IOException { // int len = Math.min(length, getItems().length - index); // Item[] result = new Item[len]; // System.arraycopy(getItems(), index, result, 0, len); // return result; // } // // public Item getItem(int index) throws IOException { // return getItems()[index]; // } // // protected String getQuery() throws IOException { // if (query == null) { // String urlQuery = new URL(url).getQuery(); // // remove all params after the first one // int ampIndex = urlQuery.indexOf('&'); // if (ampIndex != -1) { // urlQuery = urlQuery.substring(0, ampIndex); // } // // extract the value of the first param // int eqIndex = urlQuery.indexOf('='); // if (eqIndex != -1) { // query = urlQuery.substring(eqIndex + 1); // } // } // return query; // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/overview/SearchOverviewPage.java import name.raev.kaloyan.kindle.chitanka.model.Item; import name.raev.kaloyan.kindle.chitanka.model.search.SearchPage; import java.io.IOException; import org.json.simple.parser.ParseException; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.overview; public class SearchOverviewPage extends SearchPage { private SearchOverview overview;
private Item[] items;
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/screen/LinkActionListener.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/ConnectivityManager.java // public class ConnectivityManager { // // public static final String BASE_URL = "http://chitanka.info"; // // private static ConnectivityManager instance; // // private Stack history = new Stack(); // // public static ConnectivityManager getInstance() { // if (instance == null) { // instance = new ConnectivityManager(); // } // return instance; // } // // public void display(final String url) { // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // display(url); // } // // public void connected() throws InterruptedException { // Screen screen = ScreenManager.createScreen(url); // try { // screen.display(); // } catch (IOException e) { // handleNetworkError(); // display(url); // } // // ScreenManager.setCurrentScreen(screen); // } // }, true); // } // // public void downloadBook(final String href) { // ProgressIndicator.start("Книгата се изтегля"); // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // downloadBook(href); // } // // public void connected() throws InterruptedException { // try { // BookDownloader.downloadMobiFromEpubUrl(href); // BookDownloader.rescanDocuments(); // } catch (IOException e) { // handleNetworkError(); // downloadBook(href); // return; // } finally { // ProgressIndicator.stop(); // } // // // show info message // String title = "Книгата е изтеглена"; // String message = "Ще намерите книгата в началото на главния екран на Kindle. Натиснете бутона Home, за да преминете към главния екран."; // DialogManager.displayDialog(message, title); // } // }, true); // // } // // public boolean canGoBack() { // return history.size() > 1; // } // // public void goBack() { // if (canGoBack()) { // // remove the current page from history // history.pop(); // // display the previous page from history // display((String) history.peek()); // } // } // // public void navigateTo(String link) { // String url = Network.getUrlFromLinkAsString(link); // // push to history // history.push(url); // // navigate to the selected page // display(url); // } // // public void handleNetworkError() throws InterruptedException { // ProgressIndicator.stop(); // String title = "Неуспешно свързване"; // String message = "Приложението не може да се свърже с мрежата. Уверете се, че сте в обхвата на безжична мрежа.\n\nЗатворете това съобщение, за да опитате отново."; // DialogManager.displayDialog(message, title); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // }
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import name.raev.kaloyan.kindle.chitanka.ConnectivityManager; import name.raev.kaloyan.kindle.chitanka.model.Item;
/** * Copyright 2014-2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.screen; public class LinkActionListener implements ActionListener { private Screen screen; private int index; public LinkActionListener(Screen screen, int index) { this.screen = screen; this.index = index; } public void actionPerformed(ActionEvent e) { try {
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/ConnectivityManager.java // public class ConnectivityManager { // // public static final String BASE_URL = "http://chitanka.info"; // // private static ConnectivityManager instance; // // private Stack history = new Stack(); // // public static ConnectivityManager getInstance() { // if (instance == null) { // instance = new ConnectivityManager(); // } // return instance; // } // // public void display(final String url) { // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // display(url); // } // // public void connected() throws InterruptedException { // Screen screen = ScreenManager.createScreen(url); // try { // screen.display(); // } catch (IOException e) { // handleNetworkError(); // display(url); // } // // ScreenManager.setCurrentScreen(screen); // } // }, true); // } // // public void downloadBook(final String href) { // ProgressIndicator.start("Книгата се изтегля"); // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // downloadBook(href); // } // // public void connected() throws InterruptedException { // try { // BookDownloader.downloadMobiFromEpubUrl(href); // BookDownloader.rescanDocuments(); // } catch (IOException e) { // handleNetworkError(); // downloadBook(href); // return; // } finally { // ProgressIndicator.stop(); // } // // // show info message // String title = "Книгата е изтеглена"; // String message = "Ще намерите книгата в началото на главния екран на Kindle. Натиснете бутона Home, за да преминете към главния екран."; // DialogManager.displayDialog(message, title); // } // }, true); // // } // // public boolean canGoBack() { // return history.size() > 1; // } // // public void goBack() { // if (canGoBack()) { // // remove the current page from history // history.pop(); // // display the previous page from history // display((String) history.peek()); // } // } // // public void navigateTo(String link) { // String url = Network.getUrlFromLinkAsString(link); // // push to history // history.push(url); // // navigate to the selected page // display(url); // } // // public void handleNetworkError() throws InterruptedException { // ProgressIndicator.stop(); // String title = "Неуспешно свързване"; // String message = "Приложението не може да се свърже с мрежата. Уверете се, че сте в обхвата на безжична мрежа.\n\nЗатворете това съобщение, за да опитате отново."; // DialogManager.displayDialog(message, title); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/screen/LinkActionListener.java import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import name.raev.kaloyan.kindle.chitanka.ConnectivityManager; import name.raev.kaloyan.kindle.chitanka.model.Item; /** * Copyright 2014-2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.screen; public class LinkActionListener implements ActionListener { private Screen screen; private int index; public LinkActionListener(Screen screen, int index) { this.screen = screen; this.index = index; } public void actionPerformed(ActionEvent e) { try {
Item item = screen.page.getItem(screen.pageIndex + index);
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/screen/LinkActionListener.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/ConnectivityManager.java // public class ConnectivityManager { // // public static final String BASE_URL = "http://chitanka.info"; // // private static ConnectivityManager instance; // // private Stack history = new Stack(); // // public static ConnectivityManager getInstance() { // if (instance == null) { // instance = new ConnectivityManager(); // } // return instance; // } // // public void display(final String url) { // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // display(url); // } // // public void connected() throws InterruptedException { // Screen screen = ScreenManager.createScreen(url); // try { // screen.display(); // } catch (IOException e) { // handleNetworkError(); // display(url); // } // // ScreenManager.setCurrentScreen(screen); // } // }, true); // } // // public void downloadBook(final String href) { // ProgressIndicator.start("Книгата се изтегля"); // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // downloadBook(href); // } // // public void connected() throws InterruptedException { // try { // BookDownloader.downloadMobiFromEpubUrl(href); // BookDownloader.rescanDocuments(); // } catch (IOException e) { // handleNetworkError(); // downloadBook(href); // return; // } finally { // ProgressIndicator.stop(); // } // // // show info message // String title = "Книгата е изтеглена"; // String message = "Ще намерите книгата в началото на главния екран на Kindle. Натиснете бутона Home, за да преминете към главния екран."; // DialogManager.displayDialog(message, title); // } // }, true); // // } // // public boolean canGoBack() { // return history.size() > 1; // } // // public void goBack() { // if (canGoBack()) { // // remove the current page from history // history.pop(); // // display the previous page from history // display((String) history.peek()); // } // } // // public void navigateTo(String link) { // String url = Network.getUrlFromLinkAsString(link); // // push to history // history.push(url); // // navigate to the selected page // display(url); // } // // public void handleNetworkError() throws InterruptedException { // ProgressIndicator.stop(); // String title = "Неуспешно свързване"; // String message = "Приложението не може да се свърже с мрежата. Уверете се, че сте в обхвата на безжична мрежа.\n\nЗатворете това съобщение, за да опитате отново."; // DialogManager.displayDialog(message, title); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // }
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import name.raev.kaloyan.kindle.chitanka.ConnectivityManager; import name.raev.kaloyan.kindle.chitanka.model.Item;
/** * Copyright 2014-2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.screen; public class LinkActionListener implements ActionListener { private Screen screen; private int index; public LinkActionListener(Screen screen, int index) { this.screen = screen; this.index = index; } public void actionPerformed(ActionEvent e) { try { Item item = screen.page.getItem(screen.pageIndex + index); String link = item.getNavigationLink(); if (link != null) {
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/ConnectivityManager.java // public class ConnectivityManager { // // public static final String BASE_URL = "http://chitanka.info"; // // private static ConnectivityManager instance; // // private Stack history = new Stack(); // // public static ConnectivityManager getInstance() { // if (instance == null) { // instance = new ConnectivityManager(); // } // return instance; // } // // public void display(final String url) { // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // display(url); // } // // public void connected() throws InterruptedException { // Screen screen = ScreenManager.createScreen(url); // try { // screen.display(); // } catch (IOException e) { // handleNetworkError(); // display(url); // } // // ScreenManager.setCurrentScreen(screen); // } // }, true); // } // // public void downloadBook(final String href) { // ProgressIndicator.start("Книгата се изтегля"); // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // downloadBook(href); // } // // public void connected() throws InterruptedException { // try { // BookDownloader.downloadMobiFromEpubUrl(href); // BookDownloader.rescanDocuments(); // } catch (IOException e) { // handleNetworkError(); // downloadBook(href); // return; // } finally { // ProgressIndicator.stop(); // } // // // show info message // String title = "Книгата е изтеглена"; // String message = "Ще намерите книгата в началото на главния екран на Kindle. Натиснете бутона Home, за да преминете към главния екран."; // DialogManager.displayDialog(message, title); // } // }, true); // // } // // public boolean canGoBack() { // return history.size() > 1; // } // // public void goBack() { // if (canGoBack()) { // // remove the current page from history // history.pop(); // // display the previous page from history // display((String) history.peek()); // } // } // // public void navigateTo(String link) { // String url = Network.getUrlFromLinkAsString(link); // // push to history // history.push(url); // // navigate to the selected page // display(url); // } // // public void handleNetworkError() throws InterruptedException { // ProgressIndicator.stop(); // String title = "Неуспешно свързване"; // String message = "Приложението не може да се свърже с мрежата. Уверете се, че сте в обхвата на безжична мрежа.\n\nЗатворете това съобщение, за да опитате отново."; // DialogManager.displayDialog(message, title); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/screen/LinkActionListener.java import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import name.raev.kaloyan.kindle.chitanka.ConnectivityManager; import name.raev.kaloyan.kindle.chitanka.model.Item; /** * Copyright 2014-2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.screen; public class LinkActionListener implements ActionListener { private Screen screen; private int index; public LinkActionListener(Screen screen, int index) { this.screen = screen; this.index = index; } public void actionPerformed(ActionEvent e) { try { Item item = screen.page.getItem(screen.pageIndex + index); String link = item.getNavigationLink(); if (link != null) {
ConnectivityManager.getInstance().navigateTo(link);
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/category/SearchCategoriesPage.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java // public abstract class SearchPage implements Page { // // protected String url; // // private String query; // // public SearchPage(String url) { // this.url = url; // } // // public String getSubtitle() throws IOException { // return "Общо " + getItems().length + " резултата"; // } // // public int getItemsCount() throws IOException { // return getItems().length; // } // // public Item[] getItems(int index, int length) throws IOException { // int len = Math.min(length, getItems().length - index); // Item[] result = new Item[len]; // System.arraycopy(getItems(), index, result, 0, len); // return result; // } // // public Item getItem(int index) throws IOException { // return getItems()[index]; // } // // protected String getQuery() throws IOException { // if (query == null) { // String urlQuery = new URL(url).getQuery(); // // remove all params after the first one // int ampIndex = urlQuery.indexOf('&'); // if (ampIndex != -1) { // urlQuery = urlQuery.substring(0, ampIndex); // } // // extract the value of the first param // int eqIndex = urlQuery.indexOf('='); // if (eqIndex != -1) { // query = urlQuery.substring(eqIndex + 1); // } // } // return query; // } // // }
import name.raev.kaloyan.kindle.chitanka.model.Item; import name.raev.kaloyan.kindle.chitanka.model.search.SearchPage; import java.io.IOException; import org.json.simple.parser.ParseException;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.category; public class SearchCategoriesPage extends SearchPage { private Category[] categories;
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java // public abstract class SearchPage implements Page { // // protected String url; // // private String query; // // public SearchPage(String url) { // this.url = url; // } // // public String getSubtitle() throws IOException { // return "Общо " + getItems().length + " резултата"; // } // // public int getItemsCount() throws IOException { // return getItems().length; // } // // public Item[] getItems(int index, int length) throws IOException { // int len = Math.min(length, getItems().length - index); // Item[] result = new Item[len]; // System.arraycopy(getItems(), index, result, 0, len); // return result; // } // // public Item getItem(int index) throws IOException { // return getItems()[index]; // } // // protected String getQuery() throws IOException { // if (query == null) { // String urlQuery = new URL(url).getQuery(); // // remove all params after the first one // int ampIndex = urlQuery.indexOf('&'); // if (ampIndex != -1) { // urlQuery = urlQuery.substring(0, ampIndex); // } // // extract the value of the first param // int eqIndex = urlQuery.indexOf('='); // if (eqIndex != -1) { // query = urlQuery.substring(eqIndex + 1); // } // } // return query; // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/category/SearchCategoriesPage.java import name.raev.kaloyan.kindle.chitanka.model.Item; import name.raev.kaloyan.kindle.chitanka.model.search.SearchPage; import java.io.IOException; import org.json.simple.parser.ParseException; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.category; public class SearchCategoriesPage extends SearchPage { private Category[] categories;
private Item[] items;
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/utils/ImageLoader.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/ContextManager.java // public class ContextManager { // // private static KindletContext ctx; // // public static KindletContext getContext() { // return ctx; // } // // public static void setContext(KindletContext context) { // ctx = context; // } // // }
import java.awt.Image; import java.awt.Toolkit; import java.io.File; import java.io.IOException; import java.net.URL; import name.raev.kaloyan.kindle.chitanka.ContextManager;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.utils; /** * Utilities for loading images. */ public class ImageLoader { /** * Loads an image resource from the application's JAR/AZW2 file. * * @param fileName * the file name of the image to load * @return an AWT <code>Image</code> object */ public static Image loadBuiltinImage(String fileName) { URL url = ImageLoader.class.getClassLoader().getResource(fileName); return Toolkit.getDefaultToolkit().getImage(url); } /** * Loads an Image resource from a URL. * * @param url * the URL to load the image from * @return an AWT <code>Image</code> object * @throws IOException * if a malformed URL is given or a networking problem occurs */ public static Image getImage(URL url) throws IOException { if (KindleModel.getModel().hasUnrestricted3G()) { // download the image via 3G-capable connection
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/ContextManager.java // public class ContextManager { // // private static KindletContext ctx; // // public static KindletContext getContext() { // return ctx; // } // // public static void setContext(KindletContext context) { // ctx = context; // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/utils/ImageLoader.java import java.awt.Image; import java.awt.Toolkit; import java.io.File; import java.io.IOException; import java.net.URL; import name.raev.kaloyan.kindle.chitanka.ContextManager; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.utils; /** * Utilities for loading images. */ public class ImageLoader { /** * Loads an image resource from the application's JAR/AZW2 file. * * @param fileName * the file name of the image to load * @return an AWT <code>Image</code> object */ public static Image loadBuiltinImage(String fileName) { URL url = ImageLoader.class.getClassLoader().getResource(fileName); return Toolkit.getDefaultToolkit().getImage(url); } /** * Loads an Image resource from a URL. * * @param url * the URL to load the image from * @return an AWT <code>Image</code> object * @throws IOException * if a malformed URL is given or a networking problem occurs */ public static Image getImage(URL url) throws IOException { if (KindleModel.getModel().hasUnrestricted3G()) { // download the image via 3G-capable connection
File homeDir = ContextManager.getContext().getHomeDirectory();
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/serie/SearchSeriesPage.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java // public abstract class SearchPage implements Page { // // protected String url; // // private String query; // // public SearchPage(String url) { // this.url = url; // } // // public String getSubtitle() throws IOException { // return "Общо " + getItems().length + " резултата"; // } // // public int getItemsCount() throws IOException { // return getItems().length; // } // // public Item[] getItems(int index, int length) throws IOException { // int len = Math.min(length, getItems().length - index); // Item[] result = new Item[len]; // System.arraycopy(getItems(), index, result, 0, len); // return result; // } // // public Item getItem(int index) throws IOException { // return getItems()[index]; // } // // protected String getQuery() throws IOException { // if (query == null) { // String urlQuery = new URL(url).getQuery(); // // remove all params after the first one // int ampIndex = urlQuery.indexOf('&'); // if (ampIndex != -1) { // urlQuery = urlQuery.substring(0, ampIndex); // } // // extract the value of the first param // int eqIndex = urlQuery.indexOf('='); // if (eqIndex != -1) { // query = urlQuery.substring(eqIndex + 1); // } // } // return query; // } // // }
import name.raev.kaloyan.kindle.chitanka.model.Item; import name.raev.kaloyan.kindle.chitanka.model.search.SearchPage; import java.io.IOException; import org.json.simple.parser.ParseException;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.serie; public class SearchSeriesPage extends SearchPage { private Serie[] series;
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/Item.java // public interface Item { // // public String getTitle(); // // public String getNavigationLink(); // // public String getDownloadLink(); // // public Image getImage(); // // public boolean isEnabled(); // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchPage.java // public abstract class SearchPage implements Page { // // protected String url; // // private String query; // // public SearchPage(String url) { // this.url = url; // } // // public String getSubtitle() throws IOException { // return "Общо " + getItems().length + " резултата"; // } // // public int getItemsCount() throws IOException { // return getItems().length; // } // // public Item[] getItems(int index, int length) throws IOException { // int len = Math.min(length, getItems().length - index); // Item[] result = new Item[len]; // System.arraycopy(getItems(), index, result, 0, len); // return result; // } // // public Item getItem(int index) throws IOException { // return getItems()[index]; // } // // protected String getQuery() throws IOException { // if (query == null) { // String urlQuery = new URL(url).getQuery(); // // remove all params after the first one // int ampIndex = urlQuery.indexOf('&'); // if (ampIndex != -1) { // urlQuery = urlQuery.substring(0, ampIndex); // } // // extract the value of the first param // int eqIndex = urlQuery.indexOf('='); // if (eqIndex != -1) { // query = urlQuery.substring(eqIndex + 1); // } // } // return query; // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/serie/SearchSeriesPage.java import name.raev.kaloyan.kindle.chitanka.model.Item; import name.raev.kaloyan.kindle.chitanka.model.search.SearchPage; import java.io.IOException; import org.json.simple.parser.ParseException; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.serie; public class SearchSeriesPage extends SearchPage { private Serie[] series;
private Item[] items;
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/widget/KSearchField.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/ConnectivityManager.java // public class ConnectivityManager { // // public static final String BASE_URL = "http://chitanka.info"; // // private static ConnectivityManager instance; // // private Stack history = new Stack(); // // public static ConnectivityManager getInstance() { // if (instance == null) { // instance = new ConnectivityManager(); // } // return instance; // } // // public void display(final String url) { // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // display(url); // } // // public void connected() throws InterruptedException { // Screen screen = ScreenManager.createScreen(url); // try { // screen.display(); // } catch (IOException e) { // handleNetworkError(); // display(url); // } // // ScreenManager.setCurrentScreen(screen); // } // }, true); // } // // public void downloadBook(final String href) { // ProgressIndicator.start("Книгата се изтегля"); // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // downloadBook(href); // } // // public void connected() throws InterruptedException { // try { // BookDownloader.downloadMobiFromEpubUrl(href); // BookDownloader.rescanDocuments(); // } catch (IOException e) { // handleNetworkError(); // downloadBook(href); // return; // } finally { // ProgressIndicator.stop(); // } // // // show info message // String title = "Книгата е изтеглена"; // String message = "Ще намерите книгата в началото на главния екран на Kindle. Натиснете бутона Home, за да преминете към главния екран."; // DialogManager.displayDialog(message, title); // } // }, true); // // } // // public boolean canGoBack() { // return history.size() > 1; // } // // public void goBack() { // if (canGoBack()) { // // remove the current page from history // history.pop(); // // display the previous page from history // display((String) history.peek()); // } // } // // public void navigateTo(String link) { // String url = Network.getUrlFromLinkAsString(link); // // push to history // history.push(url); // // navigate to the selected page // display(url); // } // // public void handleNetworkError() throws InterruptedException { // ProgressIndicator.stop(); // String title = "Неуспешно свързване"; // String message = "Приложението не може да се свърже с мрежата. Уверете се, че сте в обхвата на безжична мрежа.\n\nЗатворете това съобщение, за да опитате отново."; // DialogManager.displayDialog(message, title); // } // // }
import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import com.amazon.kindle.kindlet.ui.KButton; import com.amazon.kindle.kindlet.ui.KOptionPane; import com.amazon.kindle.kindlet.ui.KOptionPane.MessageDialogListener; import com.amazon.kindle.kindlet.ui.KTextField; import name.raev.kaloyan.kindle.chitanka.ConnectivityManager;
public KSearchField(String initialText) { text = new KTextField(initialText, 18); text.setHint("Въведете поне 3 символа"); text.setMargin(new Insets(0, 20, 0, 20)); add(text); text.addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { if (e.getKeyChar() == '\n') { doSearch(); } } }); button = new KButton(" в библиотеката"); add(button); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSearch(); } }); } public void requestFocus() { text.requestFocus(); } private void doSearch() { if (text.getText().trim().length() >= 3) { String url = SEARCH_LINK_PREFIX + text.getText().trim();
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/ConnectivityManager.java // public class ConnectivityManager { // // public static final String BASE_URL = "http://chitanka.info"; // // private static ConnectivityManager instance; // // private Stack history = new Stack(); // // public static ConnectivityManager getInstance() { // if (instance == null) { // instance = new ConnectivityManager(); // } // return instance; // } // // public void display(final String url) { // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // display(url); // } // // public void connected() throws InterruptedException { // Screen screen = ScreenManager.createScreen(url); // try { // screen.display(); // } catch (IOException e) { // handleNetworkError(); // display(url); // } // // ScreenManager.setCurrentScreen(screen); // } // }, true); // } // // public void downloadBook(final String href) { // ProgressIndicator.start("Книгата се изтегля"); // Connectivity connectivity = ContextManager.getContext().getConnectivity(); // connectivity.submitSingleAttemptConnectivityRequest(new ConnectivityHandler() { // public void disabled(NetworkDisabledDetails details) throws InterruptedException { // handleNetworkError(); // downloadBook(href); // } // // public void connected() throws InterruptedException { // try { // BookDownloader.downloadMobiFromEpubUrl(href); // BookDownloader.rescanDocuments(); // } catch (IOException e) { // handleNetworkError(); // downloadBook(href); // return; // } finally { // ProgressIndicator.stop(); // } // // // show info message // String title = "Книгата е изтеглена"; // String message = "Ще намерите книгата в началото на главния екран на Kindle. Натиснете бутона Home, за да преминете към главния екран."; // DialogManager.displayDialog(message, title); // } // }, true); // // } // // public boolean canGoBack() { // return history.size() > 1; // } // // public void goBack() { // if (canGoBack()) { // // remove the current page from history // history.pop(); // // display the previous page from history // display((String) history.peek()); // } // } // // public void navigateTo(String link) { // String url = Network.getUrlFromLinkAsString(link); // // push to history // history.push(url); // // navigate to the selected page // display(url); // } // // public void handleNetworkError() throws InterruptedException { // ProgressIndicator.stop(); // String title = "Неуспешно свързване"; // String message = "Приложението не може да се свърже с мрежата. Уверете се, че сте в обхвата на безжична мрежа.\n\nЗатворете това съобщение, за да опитате отново."; // DialogManager.displayDialog(message, title); // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/widget/KSearchField.java import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import com.amazon.kindle.kindlet.ui.KButton; import com.amazon.kindle.kindlet.ui.KOptionPane; import com.amazon.kindle.kindlet.ui.KOptionPane.MessageDialogListener; import com.amazon.kindle.kindlet.ui.KTextField; import name.raev.kaloyan.kindle.chitanka.ConnectivityManager; public KSearchField(String initialText) { text = new KTextField(initialText, 18); text.setHint("Въведете поне 3 символа"); text.setMargin(new Insets(0, 20, 0, 20)); add(text); text.addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { if (e.getKeyChar() == '\n') { doSearch(); } } }); button = new KButton(" в библиотеката"); add(button); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSearch(); } }); } public void requestFocus() { text.requestFocus(); } private void doSearch() { if (text.getText().trim().length() >= 3) { String url = SEARCH_LINK_PREFIX + text.getText().trim();
ConnectivityManager.getInstance().navigateTo(url);
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/serie/SearchSeries.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/BaseContentHandler.java // public class BaseContentHandler implements ContentHandler { // // protected Stack objects = new Stack(); // // public void startJSON() throws ParseException, IOException { // } // // public void endJSON() throws ParseException, IOException { // } // // public boolean startArray() throws ParseException, IOException { // return true; // } // // public boolean endArray() throws ParseException, IOException { // return true; // } // // public boolean startObject() throws ParseException, IOException { // return true; // } // // public boolean endObject() throws ParseException, IOException { // return true; // } // // public boolean startObjectEntry(String key) throws ParseException, IOException { // objects.push(key); // return true; // } // // public boolean endObjectEntry() throws ParseException, IOException { // objects.pop(); // return true; // } // // public boolean primitive(Object value) throws ParseException, IOException { // return true; // } // // protected String getParentKey() { // return objects.isEmpty() ? null : (String) objects.peek(); // } // // protected String getParentKey(int depth) { // return (objects.size() < depth) ? null : (String) objects.elementAt(objects.size() - 2); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java // public abstract class SearchParser { // // protected abstract ContentHandler getContentHandler(); // // protected void parse(String url) throws IOException, ParseException { // Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url))); // // new JSONParser().parse(reader, getContentHandler()); // } // // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.model.search.BaseContentHandler; import name.raev.kaloyan.kindle.chitanka.model.search.SearchParser;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.serie; public class SearchSeries extends SearchParser { private static final String SERIES_KEY = "series"; private List series = new ArrayList(); public SearchSeries(String url) throws IOException, ParseException { parse(url); } public Serie[] getSeries() { return (Serie[]) series.toArray(new Serie[series.size()]); } protected ContentHandler getContentHandler() {
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/BaseContentHandler.java // public class BaseContentHandler implements ContentHandler { // // protected Stack objects = new Stack(); // // public void startJSON() throws ParseException, IOException { // } // // public void endJSON() throws ParseException, IOException { // } // // public boolean startArray() throws ParseException, IOException { // return true; // } // // public boolean endArray() throws ParseException, IOException { // return true; // } // // public boolean startObject() throws ParseException, IOException { // return true; // } // // public boolean endObject() throws ParseException, IOException { // return true; // } // // public boolean startObjectEntry(String key) throws ParseException, IOException { // objects.push(key); // return true; // } // // public boolean endObjectEntry() throws ParseException, IOException { // objects.pop(); // return true; // } // // public boolean primitive(Object value) throws ParseException, IOException { // return true; // } // // protected String getParentKey() { // return objects.isEmpty() ? null : (String) objects.peek(); // } // // protected String getParentKey(int depth) { // return (objects.size() < depth) ? null : (String) objects.elementAt(objects.size() - 2); // } // // } // // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/SearchParser.java // public abstract class SearchParser { // // protected abstract ContentHandler getContentHandler(); // // protected void parse(String url) throws IOException, ParseException { // Reader reader = new BufferedReader(new InputStreamReader(Network.getInputStream(url))); // // new JSONParser().parse(reader, getContentHandler()); // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/serie/SearchSeries.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.ParseException; import name.raev.kaloyan.kindle.chitanka.model.search.BaseContentHandler; import name.raev.kaloyan.kindle.chitanka.model.search.SearchParser; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.serie; public class SearchSeries extends SearchParser { private static final String SERIES_KEY = "series"; private List series = new ArrayList(); public SearchSeries(String url) throws IOException, ParseException { parse(url); } public Serie[] getSeries() { return (Serie[]) series.toArray(new Serie[series.size()]); } protected ContentHandler getContentHandler() {
return new BaseContentHandler() {
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/utils/ProgressIndicator.java
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/ContextManager.java // public class ContextManager { // // private static KindletContext ctx; // // public static KindletContext getContext() { // return ctx; // } // // public static void setContext(KindletContext context) { // ctx = context; // } // // }
import com.amazon.kindle.kindlet.ui.KProgress; import name.raev.kaloyan.kindle.chitanka.ContextManager;
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.utils; /** * Utility with convenient methods for starting and stopping the progress * indicator. */ public class ProgressIndicator { /** * Starts the progress indicator with no status message. */ public static void start() { start(null); } /** * Starts the progress indicator with a status message. * * @param status * the status message to display */ public static void start(String status) {
// Path: src/main/java/name/raev/kaloyan/kindle/chitanka/ContextManager.java // public class ContextManager { // // private static KindletContext ctx; // // public static KindletContext getContext() { // return ctx; // } // // public static void setContext(KindletContext context) { // ctx = context; // } // // } // Path: src/main/java/name/raev/kaloyan/kindle/chitanka/utils/ProgressIndicator.java import com.amazon.kindle.kindlet.ui.KProgress; import name.raev.kaloyan.kindle.chitanka.ContextManager; /** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle 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. * * chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.utils; /** * Utility with convenient methods for starting and stopping the progress * indicator. */ public class ProgressIndicator { /** * Starts the progress indicator with no status message. */ public static void start() { start(null); } /** * Starts the progress indicator with a status message. * * @param status * the status message to display */ public static void start(String status) {
KProgress progress = ContextManager.getContext().getProgressIndicator();
SWE-4103-Group-3/Project
src/main/java/com/unb/tracker/UserDetailsServiceImpl.java
// Path: src/main/java/com/unb/tracker/model/User.java // @Entity // This tells Hibernate to make a table out of this class // public class User { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String username; // // private String email; // // private String password; // // @Transient // private String passwordConfirm; // // private boolean hasExtendedPrivileges; // // @OneToMany(mappedBy = "student", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Seat> seats; // for students // // @OneToMany(mappedBy = "instructor", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Course> courses; // for instructors // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Transient // public String getPasswordConfirm() { // return passwordConfirm; // } // // @Transient // public void setPasswordConfirm(String passwordConfirm) { // this.passwordConfirm = passwordConfirm; // } // // public boolean getHasExtendedPrivileges() { // return hasExtendedPrivileges; // } // // public void setHasExtendedPrivileges(boolean hasExtendedPrivileges) { // this.hasExtendedPrivileges = hasExtendedPrivileges; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public void setCourses(List<Course> courses) { // this.courses = courses; // } // // /** // * This method returns the courses created by the user if they're an instructor or the courses they're currently registered in if they're a student // * @return their courses // */ // public Iterable<Course> getCourses() { // if(this.getHasExtendedPrivileges()) { // return this.courses; // } else { // if(seats == null) { // return null; // } // // List<Course> courses = new ArrayList<>(); // for(Seat s : seats) { // courses.add(s.getCourse()); // } // return courses; // } // } // // public void removeSeat(Seat s) { // seats.remove(s); // } // } // // Path: src/main/java/com/unb/tracker/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // public User findByUsername(String username); // }
import com.unb.tracker.model.User; import com.unb.tracker.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.HashSet; import java.util.Set;
package com.unb.tracker; @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired
// Path: src/main/java/com/unb/tracker/model/User.java // @Entity // This tells Hibernate to make a table out of this class // public class User { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String username; // // private String email; // // private String password; // // @Transient // private String passwordConfirm; // // private boolean hasExtendedPrivileges; // // @OneToMany(mappedBy = "student", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Seat> seats; // for students // // @OneToMany(mappedBy = "instructor", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Course> courses; // for instructors // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Transient // public String getPasswordConfirm() { // return passwordConfirm; // } // // @Transient // public void setPasswordConfirm(String passwordConfirm) { // this.passwordConfirm = passwordConfirm; // } // // public boolean getHasExtendedPrivileges() { // return hasExtendedPrivileges; // } // // public void setHasExtendedPrivileges(boolean hasExtendedPrivileges) { // this.hasExtendedPrivileges = hasExtendedPrivileges; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public void setCourses(List<Course> courses) { // this.courses = courses; // } // // /** // * This method returns the courses created by the user if they're an instructor or the courses they're currently registered in if they're a student // * @return their courses // */ // public Iterable<Course> getCourses() { // if(this.getHasExtendedPrivileges()) { // return this.courses; // } else { // if(seats == null) { // return null; // } // // List<Course> courses = new ArrayList<>(); // for(Seat s : seats) { // courses.add(s.getCourse()); // } // return courses; // } // } // // public void removeSeat(Seat s) { // seats.remove(s); // } // } // // Path: src/main/java/com/unb/tracker/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // public User findByUsername(String username); // } // Path: src/main/java/com/unb/tracker/UserDetailsServiceImpl.java import com.unb.tracker.model.User; import com.unb.tracker.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.HashSet; import java.util.Set; package com.unb.tracker; @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired
private UserRepository userRepository;
SWE-4103-Group-3/Project
src/main/java/com/unb/tracker/UserDetailsServiceImpl.java
// Path: src/main/java/com/unb/tracker/model/User.java // @Entity // This tells Hibernate to make a table out of this class // public class User { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String username; // // private String email; // // private String password; // // @Transient // private String passwordConfirm; // // private boolean hasExtendedPrivileges; // // @OneToMany(mappedBy = "student", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Seat> seats; // for students // // @OneToMany(mappedBy = "instructor", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Course> courses; // for instructors // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Transient // public String getPasswordConfirm() { // return passwordConfirm; // } // // @Transient // public void setPasswordConfirm(String passwordConfirm) { // this.passwordConfirm = passwordConfirm; // } // // public boolean getHasExtendedPrivileges() { // return hasExtendedPrivileges; // } // // public void setHasExtendedPrivileges(boolean hasExtendedPrivileges) { // this.hasExtendedPrivileges = hasExtendedPrivileges; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public void setCourses(List<Course> courses) { // this.courses = courses; // } // // /** // * This method returns the courses created by the user if they're an instructor or the courses they're currently registered in if they're a student // * @return their courses // */ // public Iterable<Course> getCourses() { // if(this.getHasExtendedPrivileges()) { // return this.courses; // } else { // if(seats == null) { // return null; // } // // List<Course> courses = new ArrayList<>(); // for(Seat s : seats) { // courses.add(s.getCourse()); // } // return courses; // } // } // // public void removeSeat(Seat s) { // seats.remove(s); // } // } // // Path: src/main/java/com/unb/tracker/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // public User findByUsername(String username); // }
import com.unb.tracker.model.User; import com.unb.tracker.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.HashSet; import java.util.Set;
package com.unb.tracker; @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Path: src/main/java/com/unb/tracker/model/User.java // @Entity // This tells Hibernate to make a table out of this class // public class User { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String username; // // private String email; // // private String password; // // @Transient // private String passwordConfirm; // // private boolean hasExtendedPrivileges; // // @OneToMany(mappedBy = "student", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Seat> seats; // for students // // @OneToMany(mappedBy = "instructor", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Course> courses; // for instructors // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Transient // public String getPasswordConfirm() { // return passwordConfirm; // } // // @Transient // public void setPasswordConfirm(String passwordConfirm) { // this.passwordConfirm = passwordConfirm; // } // // public boolean getHasExtendedPrivileges() { // return hasExtendedPrivileges; // } // // public void setHasExtendedPrivileges(boolean hasExtendedPrivileges) { // this.hasExtendedPrivileges = hasExtendedPrivileges; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public void setCourses(List<Course> courses) { // this.courses = courses; // } // // /** // * This method returns the courses created by the user if they're an instructor or the courses they're currently registered in if they're a student // * @return their courses // */ // public Iterable<Course> getCourses() { // if(this.getHasExtendedPrivileges()) { // return this.courses; // } else { // if(seats == null) { // return null; // } // // List<Course> courses = new ArrayList<>(); // for(Seat s : seats) { // courses.add(s.getCourse()); // } // return courses; // } // } // // public void removeSeat(Seat s) { // seats.remove(s); // } // } // // Path: src/main/java/com/unb/tracker/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // public User findByUsername(String username); // } // Path: src/main/java/com/unb/tracker/UserDetailsServiceImpl.java import com.unb.tracker.model.User; import com.unb.tracker.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.HashSet; import java.util.Set; package com.unb.tracker; @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
SWE-4103-Group-3/Project
src/main/java/com/unb/tracker/service/UserServiceImpl.java
// Path: src/main/java/com/unb/tracker/model/User.java // @Entity // This tells Hibernate to make a table out of this class // public class User { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String username; // // private String email; // // private String password; // // @Transient // private String passwordConfirm; // // private boolean hasExtendedPrivileges; // // @OneToMany(mappedBy = "student", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Seat> seats; // for students // // @OneToMany(mappedBy = "instructor", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Course> courses; // for instructors // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Transient // public String getPasswordConfirm() { // return passwordConfirm; // } // // @Transient // public void setPasswordConfirm(String passwordConfirm) { // this.passwordConfirm = passwordConfirm; // } // // public boolean getHasExtendedPrivileges() { // return hasExtendedPrivileges; // } // // public void setHasExtendedPrivileges(boolean hasExtendedPrivileges) { // this.hasExtendedPrivileges = hasExtendedPrivileges; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public void setCourses(List<Course> courses) { // this.courses = courses; // } // // /** // * This method returns the courses created by the user if they're an instructor or the courses they're currently registered in if they're a student // * @return their courses // */ // public Iterable<Course> getCourses() { // if(this.getHasExtendedPrivileges()) { // return this.courses; // } else { // if(seats == null) { // return null; // } // // List<Course> courses = new ArrayList<>(); // for(Seat s : seats) { // courses.add(s.getCourse()); // } // return courses; // } // } // // public void removeSeat(Seat s) { // seats.remove(s); // } // } // // Path: src/main/java/com/unb/tracker/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // public User findByUsername(String username); // }
import com.unb.tracker.model.User; import com.unb.tracker.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service;
package com.unb.tracker.service; @Service public class UserServiceImpl implements UserService { @Autowired
// Path: src/main/java/com/unb/tracker/model/User.java // @Entity // This tells Hibernate to make a table out of this class // public class User { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String username; // // private String email; // // private String password; // // @Transient // private String passwordConfirm; // // private boolean hasExtendedPrivileges; // // @OneToMany(mappedBy = "student", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Seat> seats; // for students // // @OneToMany(mappedBy = "instructor", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Course> courses; // for instructors // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Transient // public String getPasswordConfirm() { // return passwordConfirm; // } // // @Transient // public void setPasswordConfirm(String passwordConfirm) { // this.passwordConfirm = passwordConfirm; // } // // public boolean getHasExtendedPrivileges() { // return hasExtendedPrivileges; // } // // public void setHasExtendedPrivileges(boolean hasExtendedPrivileges) { // this.hasExtendedPrivileges = hasExtendedPrivileges; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public void setCourses(List<Course> courses) { // this.courses = courses; // } // // /** // * This method returns the courses created by the user if they're an instructor or the courses they're currently registered in if they're a student // * @return their courses // */ // public Iterable<Course> getCourses() { // if(this.getHasExtendedPrivileges()) { // return this.courses; // } else { // if(seats == null) { // return null; // } // // List<Course> courses = new ArrayList<>(); // for(Seat s : seats) { // courses.add(s.getCourse()); // } // return courses; // } // } // // public void removeSeat(Seat s) { // seats.remove(s); // } // } // // Path: src/main/java/com/unb/tracker/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // public User findByUsername(String username); // } // Path: src/main/java/com/unb/tracker/service/UserServiceImpl.java import com.unb.tracker.model.User; import com.unb.tracker.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; package com.unb.tracker.service; @Service public class UserServiceImpl implements UserService { @Autowired
private UserRepository userRepository;
SWE-4103-Group-3/Project
src/main/java/com/unb/tracker/service/UserServiceImpl.java
// Path: src/main/java/com/unb/tracker/model/User.java // @Entity // This tells Hibernate to make a table out of this class // public class User { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String username; // // private String email; // // private String password; // // @Transient // private String passwordConfirm; // // private boolean hasExtendedPrivileges; // // @OneToMany(mappedBy = "student", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Seat> seats; // for students // // @OneToMany(mappedBy = "instructor", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Course> courses; // for instructors // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Transient // public String getPasswordConfirm() { // return passwordConfirm; // } // // @Transient // public void setPasswordConfirm(String passwordConfirm) { // this.passwordConfirm = passwordConfirm; // } // // public boolean getHasExtendedPrivileges() { // return hasExtendedPrivileges; // } // // public void setHasExtendedPrivileges(boolean hasExtendedPrivileges) { // this.hasExtendedPrivileges = hasExtendedPrivileges; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public void setCourses(List<Course> courses) { // this.courses = courses; // } // // /** // * This method returns the courses created by the user if they're an instructor or the courses they're currently registered in if they're a student // * @return their courses // */ // public Iterable<Course> getCourses() { // if(this.getHasExtendedPrivileges()) { // return this.courses; // } else { // if(seats == null) { // return null; // } // // List<Course> courses = new ArrayList<>(); // for(Seat s : seats) { // courses.add(s.getCourse()); // } // return courses; // } // } // // public void removeSeat(Seat s) { // seats.remove(s); // } // } // // Path: src/main/java/com/unb/tracker/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // public User findByUsername(String username); // }
import com.unb.tracker.model.User; import com.unb.tracker.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service;
package com.unb.tracker.service; @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Override
// Path: src/main/java/com/unb/tracker/model/User.java // @Entity // This tells Hibernate to make a table out of this class // public class User { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String username; // // private String email; // // private String password; // // @Transient // private String passwordConfirm; // // private boolean hasExtendedPrivileges; // // @OneToMany(mappedBy = "student", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Seat> seats; // for students // // @OneToMany(mappedBy = "instructor", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Course> courses; // for instructors // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Transient // public String getPasswordConfirm() { // return passwordConfirm; // } // // @Transient // public void setPasswordConfirm(String passwordConfirm) { // this.passwordConfirm = passwordConfirm; // } // // public boolean getHasExtendedPrivileges() { // return hasExtendedPrivileges; // } // // public void setHasExtendedPrivileges(boolean hasExtendedPrivileges) { // this.hasExtendedPrivileges = hasExtendedPrivileges; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public void setCourses(List<Course> courses) { // this.courses = courses; // } // // /** // * This method returns the courses created by the user if they're an instructor or the courses they're currently registered in if they're a student // * @return their courses // */ // public Iterable<Course> getCourses() { // if(this.getHasExtendedPrivileges()) { // return this.courses; // } else { // if(seats == null) { // return null; // } // // List<Course> courses = new ArrayList<>(); // for(Seat s : seats) { // courses.add(s.getCourse()); // } // return courses; // } // } // // public void removeSeat(Seat s) { // seats.remove(s); // } // } // // Path: src/main/java/com/unb/tracker/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // public User findByUsername(String username); // } // Path: src/main/java/com/unb/tracker/service/UserServiceImpl.java import com.unb.tracker.model.User; import com.unb.tracker.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; package com.unb.tracker.service; @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Override
public void save(User user) {
SWE-4103-Group-3/Project
src/main/java/com/unb/tracker/validator/CourseValidator.java
// Path: src/main/java/com/unb/tracker/model/Course.java // @Entity // This tells Hibernate to make a table out of this class // public class Course { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // private Date startDate; // private String name; // private String section; // private Integer rows; // private Integer cols; // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // @JsonManagedReference // private List<Seat> seats; // // @ManyToOne(fetch = FetchType.EAGER) // private User instructor; // // @Transient // private Long courseGridReuseID; // // public User getInstructor() { // return instructor; // } // // public void setInstructor(User instructor) { // this.instructor = instructor; // } // // public String getSection() { // return section; // } // // public void setSection(String section) { // this.section = section; // } // // public Integer getRows() { // return rows; // } // // public void setRows(Integer rows) { // this.rows = rows; // } // // public Integer getCols() { // return cols; // } // // public void setCols(Integer cols) { // this.cols = cols; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Date getStartDate() { // return startDate; // } // // public void setStartDate(Date startDate) { // this.startDate = startDate; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Transient // public Long getCourseGridReuseID() { // return courseGridReuseID; // } // // @Transient // public void setCourseGridReuseID(Long courseGridReuseID) { // this.courseGridReuseID = courseGridReuseID; // } // // public void removeSeats(List<Seat> seatsToRemove) { // seats.removeAll(seatsToRemove); // for(Seat s : seatsToRemove) { // s.setCourse(null); // } // } // // public List<Seat> getOutOfBoundsSeats(int rows, int cols) { // List<Seat> seatsToRemove = new ArrayList<>(); // if(seats != null) { // for(Seat s : seats) { // if(s.getRow() >= rows || s.getCol() >= cols) { // seatsToRemove.add(s); // } // } // } // return seatsToRemove; // } // } // // Path: src/main/java/com/unb/tracker/service/CourseService.java // public interface CourseService { // void save(Course course); // // List<Course> findByInstructorUsernameAndNameAndSection(String username, String name, String section); // }
import com.unb.tracker.model.Course; import com.unb.tracker.service.CourseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator;
package com.unb.tracker.validator; @Component public class CourseValidator implements Validator { @Autowired
// Path: src/main/java/com/unb/tracker/model/Course.java // @Entity // This tells Hibernate to make a table out of this class // public class Course { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // private Date startDate; // private String name; // private String section; // private Integer rows; // private Integer cols; // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // @JsonManagedReference // private List<Seat> seats; // // @ManyToOne(fetch = FetchType.EAGER) // private User instructor; // // @Transient // private Long courseGridReuseID; // // public User getInstructor() { // return instructor; // } // // public void setInstructor(User instructor) { // this.instructor = instructor; // } // // public String getSection() { // return section; // } // // public void setSection(String section) { // this.section = section; // } // // public Integer getRows() { // return rows; // } // // public void setRows(Integer rows) { // this.rows = rows; // } // // public Integer getCols() { // return cols; // } // // public void setCols(Integer cols) { // this.cols = cols; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Date getStartDate() { // return startDate; // } // // public void setStartDate(Date startDate) { // this.startDate = startDate; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Transient // public Long getCourseGridReuseID() { // return courseGridReuseID; // } // // @Transient // public void setCourseGridReuseID(Long courseGridReuseID) { // this.courseGridReuseID = courseGridReuseID; // } // // public void removeSeats(List<Seat> seatsToRemove) { // seats.removeAll(seatsToRemove); // for(Seat s : seatsToRemove) { // s.setCourse(null); // } // } // // public List<Seat> getOutOfBoundsSeats(int rows, int cols) { // List<Seat> seatsToRemove = new ArrayList<>(); // if(seats != null) { // for(Seat s : seats) { // if(s.getRow() >= rows || s.getCol() >= cols) { // seatsToRemove.add(s); // } // } // } // return seatsToRemove; // } // } // // Path: src/main/java/com/unb/tracker/service/CourseService.java // public interface CourseService { // void save(Course course); // // List<Course> findByInstructorUsernameAndNameAndSection(String username, String name, String section); // } // Path: src/main/java/com/unb/tracker/validator/CourseValidator.java import com.unb.tracker.model.Course; import com.unb.tracker.service.CourseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; package com.unb.tracker.validator; @Component public class CourseValidator implements Validator { @Autowired
private CourseService courseService;
SWE-4103-Group-3/Project
src/main/java/com/unb/tracker/validator/CourseValidator.java
// Path: src/main/java/com/unb/tracker/model/Course.java // @Entity // This tells Hibernate to make a table out of this class // public class Course { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // private Date startDate; // private String name; // private String section; // private Integer rows; // private Integer cols; // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // @JsonManagedReference // private List<Seat> seats; // // @ManyToOne(fetch = FetchType.EAGER) // private User instructor; // // @Transient // private Long courseGridReuseID; // // public User getInstructor() { // return instructor; // } // // public void setInstructor(User instructor) { // this.instructor = instructor; // } // // public String getSection() { // return section; // } // // public void setSection(String section) { // this.section = section; // } // // public Integer getRows() { // return rows; // } // // public void setRows(Integer rows) { // this.rows = rows; // } // // public Integer getCols() { // return cols; // } // // public void setCols(Integer cols) { // this.cols = cols; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Date getStartDate() { // return startDate; // } // // public void setStartDate(Date startDate) { // this.startDate = startDate; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Transient // public Long getCourseGridReuseID() { // return courseGridReuseID; // } // // @Transient // public void setCourseGridReuseID(Long courseGridReuseID) { // this.courseGridReuseID = courseGridReuseID; // } // // public void removeSeats(List<Seat> seatsToRemove) { // seats.removeAll(seatsToRemove); // for(Seat s : seatsToRemove) { // s.setCourse(null); // } // } // // public List<Seat> getOutOfBoundsSeats(int rows, int cols) { // List<Seat> seatsToRemove = new ArrayList<>(); // if(seats != null) { // for(Seat s : seats) { // if(s.getRow() >= rows || s.getCol() >= cols) { // seatsToRemove.add(s); // } // } // } // return seatsToRemove; // } // } // // Path: src/main/java/com/unb/tracker/service/CourseService.java // public interface CourseService { // void save(Course course); // // List<Course> findByInstructorUsernameAndNameAndSection(String username, String name, String section); // }
import com.unb.tracker.model.Course; import com.unb.tracker.service.CourseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator;
package com.unb.tracker.validator; @Component public class CourseValidator implements Validator { @Autowired private CourseService courseService; @Override public boolean supports(Class<?> aClass) {
// Path: src/main/java/com/unb/tracker/model/Course.java // @Entity // This tells Hibernate to make a table out of this class // public class Course { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // private Date startDate; // private String name; // private String section; // private Integer rows; // private Integer cols; // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // @JsonManagedReference // private List<Seat> seats; // // @ManyToOne(fetch = FetchType.EAGER) // private User instructor; // // @Transient // private Long courseGridReuseID; // // public User getInstructor() { // return instructor; // } // // public void setInstructor(User instructor) { // this.instructor = instructor; // } // // public String getSection() { // return section; // } // // public void setSection(String section) { // this.section = section; // } // // public Integer getRows() { // return rows; // } // // public void setRows(Integer rows) { // this.rows = rows; // } // // public Integer getCols() { // return cols; // } // // public void setCols(Integer cols) { // this.cols = cols; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Date getStartDate() { // return startDate; // } // // public void setStartDate(Date startDate) { // this.startDate = startDate; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Transient // public Long getCourseGridReuseID() { // return courseGridReuseID; // } // // @Transient // public void setCourseGridReuseID(Long courseGridReuseID) { // this.courseGridReuseID = courseGridReuseID; // } // // public void removeSeats(List<Seat> seatsToRemove) { // seats.removeAll(seatsToRemove); // for(Seat s : seatsToRemove) { // s.setCourse(null); // } // } // // public List<Seat> getOutOfBoundsSeats(int rows, int cols) { // List<Seat> seatsToRemove = new ArrayList<>(); // if(seats != null) { // for(Seat s : seats) { // if(s.getRow() >= rows || s.getCol() >= cols) { // seatsToRemove.add(s); // } // } // } // return seatsToRemove; // } // } // // Path: src/main/java/com/unb/tracker/service/CourseService.java // public interface CourseService { // void save(Course course); // // List<Course> findByInstructorUsernameAndNameAndSection(String username, String name, String section); // } // Path: src/main/java/com/unb/tracker/validator/CourseValidator.java import com.unb.tracker.model.Course; import com.unb.tracker.service.CourseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; package com.unb.tracker.validator; @Component public class CourseValidator implements Validator { @Autowired private CourseService courseService; @Override public boolean supports(Class<?> aClass) {
return Course.class.equals(aClass);
SWE-4103-Group-3/Project
src/main/java/com/unb/tracker/service/CourseServiceImpl.java
// Path: src/main/java/com/unb/tracker/model/Course.java // @Entity // This tells Hibernate to make a table out of this class // public class Course { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // private Date startDate; // private String name; // private String section; // private Integer rows; // private Integer cols; // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // @JsonManagedReference // private List<Seat> seats; // // @ManyToOne(fetch = FetchType.EAGER) // private User instructor; // // @Transient // private Long courseGridReuseID; // // public User getInstructor() { // return instructor; // } // // public void setInstructor(User instructor) { // this.instructor = instructor; // } // // public String getSection() { // return section; // } // // public void setSection(String section) { // this.section = section; // } // // public Integer getRows() { // return rows; // } // // public void setRows(Integer rows) { // this.rows = rows; // } // // public Integer getCols() { // return cols; // } // // public void setCols(Integer cols) { // this.cols = cols; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Date getStartDate() { // return startDate; // } // // public void setStartDate(Date startDate) { // this.startDate = startDate; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Transient // public Long getCourseGridReuseID() { // return courseGridReuseID; // } // // @Transient // public void setCourseGridReuseID(Long courseGridReuseID) { // this.courseGridReuseID = courseGridReuseID; // } // // public void removeSeats(List<Seat> seatsToRemove) { // seats.removeAll(seatsToRemove); // for(Seat s : seatsToRemove) { // s.setCourse(null); // } // } // // public List<Seat> getOutOfBoundsSeats(int rows, int cols) { // List<Seat> seatsToRemove = new ArrayList<>(); // if(seats != null) { // for(Seat s : seats) { // if(s.getRow() >= rows || s.getCol() >= cols) { // seatsToRemove.add(s); // } // } // } // return seatsToRemove; // } // } // // Path: src/main/java/com/unb/tracker/repository/CourseRepository.java // public interface CourseRepository extends CrudRepository<Course, Long> { // public List<Course> findByInstructorUsernameAndNameAndSection(String username, String name, String section); // // public List<Course> findByInstructorUsernameAndName(String username, String name); // // @Query(value = "SELECT * FROM course WHERE course.name LIKE CONCAT('%',:pname,'%') OR course.section LIKE CONCAT('%',:pname,'%') LIMIT 10", nativeQuery = true) // public List<Course> findByPartialName(@Param("pname")String partialName); // // }
import com.unb.tracker.model.Course; import com.unb.tracker.repository.CourseRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List;
package com.unb.tracker.service; @Service public class CourseServiceImpl implements CourseService { @Autowired
// Path: src/main/java/com/unb/tracker/model/Course.java // @Entity // This tells Hibernate to make a table out of this class // public class Course { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // private Date startDate; // private String name; // private String section; // private Integer rows; // private Integer cols; // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // @JsonManagedReference // private List<Seat> seats; // // @ManyToOne(fetch = FetchType.EAGER) // private User instructor; // // @Transient // private Long courseGridReuseID; // // public User getInstructor() { // return instructor; // } // // public void setInstructor(User instructor) { // this.instructor = instructor; // } // // public String getSection() { // return section; // } // // public void setSection(String section) { // this.section = section; // } // // public Integer getRows() { // return rows; // } // // public void setRows(Integer rows) { // this.rows = rows; // } // // public Integer getCols() { // return cols; // } // // public void setCols(Integer cols) { // this.cols = cols; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Date getStartDate() { // return startDate; // } // // public void setStartDate(Date startDate) { // this.startDate = startDate; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Transient // public Long getCourseGridReuseID() { // return courseGridReuseID; // } // // @Transient // public void setCourseGridReuseID(Long courseGridReuseID) { // this.courseGridReuseID = courseGridReuseID; // } // // public void removeSeats(List<Seat> seatsToRemove) { // seats.removeAll(seatsToRemove); // for(Seat s : seatsToRemove) { // s.setCourse(null); // } // } // // public List<Seat> getOutOfBoundsSeats(int rows, int cols) { // List<Seat> seatsToRemove = new ArrayList<>(); // if(seats != null) { // for(Seat s : seats) { // if(s.getRow() >= rows || s.getCol() >= cols) { // seatsToRemove.add(s); // } // } // } // return seatsToRemove; // } // } // // Path: src/main/java/com/unb/tracker/repository/CourseRepository.java // public interface CourseRepository extends CrudRepository<Course, Long> { // public List<Course> findByInstructorUsernameAndNameAndSection(String username, String name, String section); // // public List<Course> findByInstructorUsernameAndName(String username, String name); // // @Query(value = "SELECT * FROM course WHERE course.name LIKE CONCAT('%',:pname,'%') OR course.section LIKE CONCAT('%',:pname,'%') LIMIT 10", nativeQuery = true) // public List<Course> findByPartialName(@Param("pname")String partialName); // // } // Path: src/main/java/com/unb/tracker/service/CourseServiceImpl.java import com.unb.tracker.model.Course; import com.unb.tracker.repository.CourseRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; package com.unb.tracker.service; @Service public class CourseServiceImpl implements CourseService { @Autowired
private CourseRepository courseRepository;
SWE-4103-Group-3/Project
src/main/java/com/unb/tracker/service/CourseServiceImpl.java
// Path: src/main/java/com/unb/tracker/model/Course.java // @Entity // This tells Hibernate to make a table out of this class // public class Course { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // private Date startDate; // private String name; // private String section; // private Integer rows; // private Integer cols; // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // @JsonManagedReference // private List<Seat> seats; // // @ManyToOne(fetch = FetchType.EAGER) // private User instructor; // // @Transient // private Long courseGridReuseID; // // public User getInstructor() { // return instructor; // } // // public void setInstructor(User instructor) { // this.instructor = instructor; // } // // public String getSection() { // return section; // } // // public void setSection(String section) { // this.section = section; // } // // public Integer getRows() { // return rows; // } // // public void setRows(Integer rows) { // this.rows = rows; // } // // public Integer getCols() { // return cols; // } // // public void setCols(Integer cols) { // this.cols = cols; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Date getStartDate() { // return startDate; // } // // public void setStartDate(Date startDate) { // this.startDate = startDate; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Transient // public Long getCourseGridReuseID() { // return courseGridReuseID; // } // // @Transient // public void setCourseGridReuseID(Long courseGridReuseID) { // this.courseGridReuseID = courseGridReuseID; // } // // public void removeSeats(List<Seat> seatsToRemove) { // seats.removeAll(seatsToRemove); // for(Seat s : seatsToRemove) { // s.setCourse(null); // } // } // // public List<Seat> getOutOfBoundsSeats(int rows, int cols) { // List<Seat> seatsToRemove = new ArrayList<>(); // if(seats != null) { // for(Seat s : seats) { // if(s.getRow() >= rows || s.getCol() >= cols) { // seatsToRemove.add(s); // } // } // } // return seatsToRemove; // } // } // // Path: src/main/java/com/unb/tracker/repository/CourseRepository.java // public interface CourseRepository extends CrudRepository<Course, Long> { // public List<Course> findByInstructorUsernameAndNameAndSection(String username, String name, String section); // // public List<Course> findByInstructorUsernameAndName(String username, String name); // // @Query(value = "SELECT * FROM course WHERE course.name LIKE CONCAT('%',:pname,'%') OR course.section LIKE CONCAT('%',:pname,'%') LIMIT 10", nativeQuery = true) // public List<Course> findByPartialName(@Param("pname")String partialName); // // }
import com.unb.tracker.model.Course; import com.unb.tracker.repository.CourseRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List;
package com.unb.tracker.service; @Service public class CourseServiceImpl implements CourseService { @Autowired private CourseRepository courseRepository; @Override
// Path: src/main/java/com/unb/tracker/model/Course.java // @Entity // This tells Hibernate to make a table out of this class // public class Course { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // private Date startDate; // private String name; // private String section; // private Integer rows; // private Integer cols; // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // @JsonManagedReference // private List<Seat> seats; // // @ManyToOne(fetch = FetchType.EAGER) // private User instructor; // // @Transient // private Long courseGridReuseID; // // public User getInstructor() { // return instructor; // } // // public void setInstructor(User instructor) { // this.instructor = instructor; // } // // public String getSection() { // return section; // } // // public void setSection(String section) { // this.section = section; // } // // public Integer getRows() { // return rows; // } // // public void setRows(Integer rows) { // this.rows = rows; // } // // public Integer getCols() { // return cols; // } // // public void setCols(Integer cols) { // this.cols = cols; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Date getStartDate() { // return startDate; // } // // public void setStartDate(Date startDate) { // this.startDate = startDate; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Transient // public Long getCourseGridReuseID() { // return courseGridReuseID; // } // // @Transient // public void setCourseGridReuseID(Long courseGridReuseID) { // this.courseGridReuseID = courseGridReuseID; // } // // public void removeSeats(List<Seat> seatsToRemove) { // seats.removeAll(seatsToRemove); // for(Seat s : seatsToRemove) { // s.setCourse(null); // } // } // // public List<Seat> getOutOfBoundsSeats(int rows, int cols) { // List<Seat> seatsToRemove = new ArrayList<>(); // if(seats != null) { // for(Seat s : seats) { // if(s.getRow() >= rows || s.getCol() >= cols) { // seatsToRemove.add(s); // } // } // } // return seatsToRemove; // } // } // // Path: src/main/java/com/unb/tracker/repository/CourseRepository.java // public interface CourseRepository extends CrudRepository<Course, Long> { // public List<Course> findByInstructorUsernameAndNameAndSection(String username, String name, String section); // // public List<Course> findByInstructorUsernameAndName(String username, String name); // // @Query(value = "SELECT * FROM course WHERE course.name LIKE CONCAT('%',:pname,'%') OR course.section LIKE CONCAT('%',:pname,'%') LIMIT 10", nativeQuery = true) // public List<Course> findByPartialName(@Param("pname")String partialName); // // } // Path: src/main/java/com/unb/tracker/service/CourseServiceImpl.java import com.unb.tracker.model.Course; import com.unb.tracker.repository.CourseRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; package com.unb.tracker.service; @Service public class CourseServiceImpl implements CourseService { @Autowired private CourseRepository courseRepository; @Override
public void save(Course course) {
SWE-4103-Group-3/Project
src/main/java/com/unb/tracker/validator/UserValidator.java
// Path: src/main/java/com/unb/tracker/model/User.java // @Entity // This tells Hibernate to make a table out of this class // public class User { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String username; // // private String email; // // private String password; // // @Transient // private String passwordConfirm; // // private boolean hasExtendedPrivileges; // // @OneToMany(mappedBy = "student", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Seat> seats; // for students // // @OneToMany(mappedBy = "instructor", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Course> courses; // for instructors // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Transient // public String getPasswordConfirm() { // return passwordConfirm; // } // // @Transient // public void setPasswordConfirm(String passwordConfirm) { // this.passwordConfirm = passwordConfirm; // } // // public boolean getHasExtendedPrivileges() { // return hasExtendedPrivileges; // } // // public void setHasExtendedPrivileges(boolean hasExtendedPrivileges) { // this.hasExtendedPrivileges = hasExtendedPrivileges; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public void setCourses(List<Course> courses) { // this.courses = courses; // } // // /** // * This method returns the courses created by the user if they're an instructor or the courses they're currently registered in if they're a student // * @return their courses // */ // public Iterable<Course> getCourses() { // if(this.getHasExtendedPrivileges()) { // return this.courses; // } else { // if(seats == null) { // return null; // } // // List<Course> courses = new ArrayList<>(); // for(Seat s : seats) { // courses.add(s.getCourse()); // } // return courses; // } // } // // public void removeSeat(Seat s) { // seats.remove(s); // } // } // // Path: src/main/java/com/unb/tracker/service/UserService.java // public interface UserService { // void save(User user); // // User findByUsername(String username); // }
import com.unb.tracker.model.User; import com.unb.tracker.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import java.util.regex.Matcher; import java.util.regex.Pattern;
package com.unb.tracker.validator; @Component public class UserValidator implements Validator { @Autowired
// Path: src/main/java/com/unb/tracker/model/User.java // @Entity // This tells Hibernate to make a table out of this class // public class User { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String username; // // private String email; // // private String password; // // @Transient // private String passwordConfirm; // // private boolean hasExtendedPrivileges; // // @OneToMany(mappedBy = "student", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Seat> seats; // for students // // @OneToMany(mappedBy = "instructor", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Course> courses; // for instructors // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Transient // public String getPasswordConfirm() { // return passwordConfirm; // } // // @Transient // public void setPasswordConfirm(String passwordConfirm) { // this.passwordConfirm = passwordConfirm; // } // // public boolean getHasExtendedPrivileges() { // return hasExtendedPrivileges; // } // // public void setHasExtendedPrivileges(boolean hasExtendedPrivileges) { // this.hasExtendedPrivileges = hasExtendedPrivileges; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public void setCourses(List<Course> courses) { // this.courses = courses; // } // // /** // * This method returns the courses created by the user if they're an instructor or the courses they're currently registered in if they're a student // * @return their courses // */ // public Iterable<Course> getCourses() { // if(this.getHasExtendedPrivileges()) { // return this.courses; // } else { // if(seats == null) { // return null; // } // // List<Course> courses = new ArrayList<>(); // for(Seat s : seats) { // courses.add(s.getCourse()); // } // return courses; // } // } // // public void removeSeat(Seat s) { // seats.remove(s); // } // } // // Path: src/main/java/com/unb/tracker/service/UserService.java // public interface UserService { // void save(User user); // // User findByUsername(String username); // } // Path: src/main/java/com/unb/tracker/validator/UserValidator.java import com.unb.tracker.model.User; import com.unb.tracker.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import java.util.regex.Matcher; import java.util.regex.Pattern; package com.unb.tracker.validator; @Component public class UserValidator implements Validator { @Autowired
private UserService userService;
SWE-4103-Group-3/Project
src/main/java/com/unb/tracker/validator/UserValidator.java
// Path: src/main/java/com/unb/tracker/model/User.java // @Entity // This tells Hibernate to make a table out of this class // public class User { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String username; // // private String email; // // private String password; // // @Transient // private String passwordConfirm; // // private boolean hasExtendedPrivileges; // // @OneToMany(mappedBy = "student", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Seat> seats; // for students // // @OneToMany(mappedBy = "instructor", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Course> courses; // for instructors // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Transient // public String getPasswordConfirm() { // return passwordConfirm; // } // // @Transient // public void setPasswordConfirm(String passwordConfirm) { // this.passwordConfirm = passwordConfirm; // } // // public boolean getHasExtendedPrivileges() { // return hasExtendedPrivileges; // } // // public void setHasExtendedPrivileges(boolean hasExtendedPrivileges) { // this.hasExtendedPrivileges = hasExtendedPrivileges; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public void setCourses(List<Course> courses) { // this.courses = courses; // } // // /** // * This method returns the courses created by the user if they're an instructor or the courses they're currently registered in if they're a student // * @return their courses // */ // public Iterable<Course> getCourses() { // if(this.getHasExtendedPrivileges()) { // return this.courses; // } else { // if(seats == null) { // return null; // } // // List<Course> courses = new ArrayList<>(); // for(Seat s : seats) { // courses.add(s.getCourse()); // } // return courses; // } // } // // public void removeSeat(Seat s) { // seats.remove(s); // } // } // // Path: src/main/java/com/unb/tracker/service/UserService.java // public interface UserService { // void save(User user); // // User findByUsername(String username); // }
import com.unb.tracker.model.User; import com.unb.tracker.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import java.util.regex.Matcher; import java.util.regex.Pattern;
package com.unb.tracker.validator; @Component public class UserValidator implements Validator { @Autowired private UserService userService; @Override public boolean supports(Class<?> aClass) {
// Path: src/main/java/com/unb/tracker/model/User.java // @Entity // This tells Hibernate to make a table out of this class // public class User { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String username; // // private String email; // // private String password; // // @Transient // private String passwordConfirm; // // private boolean hasExtendedPrivileges; // // @OneToMany(mappedBy = "student", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Seat> seats; // for students // // @OneToMany(mappedBy = "instructor", fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // @JsonIgnore // private List<Course> courses; // for instructors // // @OneToMany(cascade = CascadeType.ALL, mappedBy = "course", fetch = FetchType.EAGER) // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Transient // public String getPasswordConfirm() { // return passwordConfirm; // } // // @Transient // public void setPasswordConfirm(String passwordConfirm) { // this.passwordConfirm = passwordConfirm; // } // // public boolean getHasExtendedPrivileges() { // return hasExtendedPrivileges; // } // // public void setHasExtendedPrivileges(boolean hasExtendedPrivileges) { // this.hasExtendedPrivileges = hasExtendedPrivileges; // } // // public List<Seat> getSeats() { // return seats; // } // // public void setSeats(List<Seat> seats) { // this.seats = seats; // } // // public void setCourses(List<Course> courses) { // this.courses = courses; // } // // /** // * This method returns the courses created by the user if they're an instructor or the courses they're currently registered in if they're a student // * @return their courses // */ // public Iterable<Course> getCourses() { // if(this.getHasExtendedPrivileges()) { // return this.courses; // } else { // if(seats == null) { // return null; // } // // List<Course> courses = new ArrayList<>(); // for(Seat s : seats) { // courses.add(s.getCourse()); // } // return courses; // } // } // // public void removeSeat(Seat s) { // seats.remove(s); // } // } // // Path: src/main/java/com/unb/tracker/service/UserService.java // public interface UserService { // void save(User user); // // User findByUsername(String username); // } // Path: src/main/java/com/unb/tracker/validator/UserValidator.java import com.unb.tracker.model.User; import com.unb.tracker.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import java.util.regex.Matcher; import java.util.regex.Pattern; package com.unb.tracker.validator; @Component public class UserValidator implements Validator { @Autowired private UserService userService; @Override public boolean supports(Class<?> aClass) {
return User.class.equals(aClass);
wieden-kennedy/composite-framework
src/main/java/com/wk/lodge/composite/service/DeviceService.java
// Path: src/main/java/com/wk/lodge/composite/registry/DeviceRegistry.java // public class DeviceRegistry { // private static final Log logger = LogFactory.getLog(DeviceRegistry.class); // private final Set<UUID> healthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Set<UUID> unhealthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Object lock = new Object(); // // /** // * returns a set of unhealthy devices every time the scheduled task defined by DeviceService.deleteUnhealthyDevices // * runs. All devices formerly considered healthy are added to the unhealthy device registry after unhealthy devices // * are added to a temp set, then cleared from the unhealthy device registry. As devices ping the server, they are // * added back into the healthy device registry using the below method, addHealthyDevice. // * // * @return the set of unhealthy device UUIDs // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public Set<UUID> getUnhealthyDevices() { // synchronized(this.lock) { // if(logger.isDebugEnabled()) // logger.debug(String.format("UnhealthyDevices: %d, HealthyDevices: %d", // unhealthyDevices.size(), healthyDevices.size())); // Set<UUID> tempDevices = new CopyOnWriteArraySet<UUID>(); // tempDevices.addAll(unhealthyDevices); // unhealthyDevices.clear(); // unhealthyDevices.addAll(healthyDevices); // healthyDevices.clear(); // return tempDevices; // } // } // // /** // * adds a device UUID to the healthy device registry each time the device pings the server. Devices will always // * be added to the healthy device registry unless they fail to ping the server within the periodic window at which // * the DeviceService.deleteUnhealthyDevices method is called. // * // * @param uuidStr string-form UUID for the device that should be added to the healthy device registry. // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public void addHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // UUID uuid = UUID.fromString(uuidStr); // synchronized(this.lock) { // healthyDevices.add(uuid); // unhealthyDevices.remove(uuid); // } // } // // /** // * checks to see whether a device is healthy or not by looking up the device UUID in the healthy device registry // * // * @param uuidStr string-form UUID for the device to be checked // * @return boolean, whether the device is healthy // */ // public boolean isHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // synchronized(this.lock) { // return healthyDevices.contains(UUID.fromString(uuidStr)); // } // } // }
import com.wk.lodge.composite.registry.DeviceRegistry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.util.Set; import java.util.UUID;
package com.wk.lodge.composite.service; @Service public class DeviceService { private static final Log logger = LogFactory.getLog(DeviceService.class);
// Path: src/main/java/com/wk/lodge/composite/registry/DeviceRegistry.java // public class DeviceRegistry { // private static final Log logger = LogFactory.getLog(DeviceRegistry.class); // private final Set<UUID> healthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Set<UUID> unhealthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Object lock = new Object(); // // /** // * returns a set of unhealthy devices every time the scheduled task defined by DeviceService.deleteUnhealthyDevices // * runs. All devices formerly considered healthy are added to the unhealthy device registry after unhealthy devices // * are added to a temp set, then cleared from the unhealthy device registry. As devices ping the server, they are // * added back into the healthy device registry using the below method, addHealthyDevice. // * // * @return the set of unhealthy device UUIDs // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public Set<UUID> getUnhealthyDevices() { // synchronized(this.lock) { // if(logger.isDebugEnabled()) // logger.debug(String.format("UnhealthyDevices: %d, HealthyDevices: %d", // unhealthyDevices.size(), healthyDevices.size())); // Set<UUID> tempDevices = new CopyOnWriteArraySet<UUID>(); // tempDevices.addAll(unhealthyDevices); // unhealthyDevices.clear(); // unhealthyDevices.addAll(healthyDevices); // healthyDevices.clear(); // return tempDevices; // } // } // // /** // * adds a device UUID to the healthy device registry each time the device pings the server. Devices will always // * be added to the healthy device registry unless they fail to ping the server within the periodic window at which // * the DeviceService.deleteUnhealthyDevices method is called. // * // * @param uuidStr string-form UUID for the device that should be added to the healthy device registry. // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public void addHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // UUID uuid = UUID.fromString(uuidStr); // synchronized(this.lock) { // healthyDevices.add(uuid); // unhealthyDevices.remove(uuid); // } // } // // /** // * checks to see whether a device is healthy or not by looking up the device UUID in the healthy device registry // * // * @param uuidStr string-form UUID for the device to be checked // * @return boolean, whether the device is healthy // */ // public boolean isHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // synchronized(this.lock) { // return healthyDevices.contains(UUID.fromString(uuidStr)); // } // } // } // Path: src/main/java/com/wk/lodge/composite/service/DeviceService.java import com.wk.lodge.composite.registry.DeviceRegistry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.util.Set; import java.util.UUID; package com.wk.lodge.composite.service; @Service public class DeviceService { private static final Log logger = LogFactory.getLog(DeviceService.class);
private DeviceRegistry deviceRegistry;
wieden-kennedy/composite-framework
src/main/java/com/wk/lodge/composite/web/socket/message/inbound/MatchMessage.java
// Path: src/main/java/com/wk/lodge/composite/model/Device.java // public class Device { // private UUID uuid; // private int width; // private int height; // private int performance; // private int instructions; // private String location; // private String country; // // public Device(){ // this.uuid = UUID.randomUUID(); // } // // public Device(String uuid){ // this.uuid = UUID.fromString(uuid); // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public UUID getUuid() { // return uuid; // } // // public void setUuid(UUID uuid) { // this.uuid = uuid; // } // // public int getPerformance() { // return performance; // } // // public void setPerformance(int performance) { // this.performance = performance; // } // // public int getInstructions() { // return instructions; // } // // public void setInstructions(int instructions) { // this.instructions = instructions; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // }
import com.fasterxml.jackson.annotation.JsonCreator; import com.google.gson.Gson; import com.wk.lodge.composite.model.Device;
package com.wk.lodge.composite.web.socket.message.inbound; public class MatchMessage { private String applicationId;
// Path: src/main/java/com/wk/lodge/composite/model/Device.java // public class Device { // private UUID uuid; // private int width; // private int height; // private int performance; // private int instructions; // private String location; // private String country; // // public Device(){ // this.uuid = UUID.randomUUID(); // } // // public Device(String uuid){ // this.uuid = UUID.fromString(uuid); // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public UUID getUuid() { // return uuid; // } // // public void setUuid(UUID uuid) { // this.uuid = uuid; // } // // public int getPerformance() { // return performance; // } // // public void setPerformance(int performance) { // this.performance = performance; // } // // public int getInstructions() { // return instructions; // } // // public void setInstructions(int instructions) { // this.instructions = instructions; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // } // Path: src/main/java/com/wk/lodge/composite/web/socket/message/inbound/MatchMessage.java import com.fasterxml.jackson.annotation.JsonCreator; import com.google.gson.Gson; import com.wk.lodge.composite.model.Device; package com.wk.lodge.composite.web.socket.message.inbound; public class MatchMessage { private String applicationId;
private Device device;
wieden-kennedy/composite-framework
src/test/java/com/wk/lodge/composite/config/TestWebSocketConfig.java
// Path: src/main/java/com/wk/lodge/composite/registry/DeviceRegistry.java // public class DeviceRegistry { // private static final Log logger = LogFactory.getLog(DeviceRegistry.class); // private final Set<UUID> healthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Set<UUID> unhealthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Object lock = new Object(); // // /** // * returns a set of unhealthy devices every time the scheduled task defined by DeviceService.deleteUnhealthyDevices // * runs. All devices formerly considered healthy are added to the unhealthy device registry after unhealthy devices // * are added to a temp set, then cleared from the unhealthy device registry. As devices ping the server, they are // * added back into the healthy device registry using the below method, addHealthyDevice. // * // * @return the set of unhealthy device UUIDs // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public Set<UUID> getUnhealthyDevices() { // synchronized(this.lock) { // if(logger.isDebugEnabled()) // logger.debug(String.format("UnhealthyDevices: %d, HealthyDevices: %d", // unhealthyDevices.size(), healthyDevices.size())); // Set<UUID> tempDevices = new CopyOnWriteArraySet<UUID>(); // tempDevices.addAll(unhealthyDevices); // unhealthyDevices.clear(); // unhealthyDevices.addAll(healthyDevices); // healthyDevices.clear(); // return tempDevices; // } // } // // /** // * adds a device UUID to the healthy device registry each time the device pings the server. Devices will always // * be added to the healthy device registry unless they fail to ping the server within the periodic window at which // * the DeviceService.deleteUnhealthyDevices method is called. // * // * @param uuidStr string-form UUID for the device that should be added to the healthy device registry. // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public void addHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // UUID uuid = UUID.fromString(uuidStr); // synchronized(this.lock) { // healthyDevices.add(uuid); // unhealthyDevices.remove(uuid); // } // } // // /** // * checks to see whether a device is healthy or not by looking up the device UUID in the healthy device registry // * // * @param uuidStr string-form UUID for the device to be checked // * @return boolean, whether the device is healthy // */ // public boolean isHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // synchronized(this.lock) { // return healthyDevices.contains(UUID.fromString(uuidStr)); // } // } // } // // Path: src/main/java/com/wk/lodge/composite/web/socket/server/support/CompositeHandshakeHandler.java // public class CompositeHandshakeHandler extends DefaultHandshakeHandler { // // public CompositeHandshakeHandler() { // super(); // } // // public CompositeHandshakeHandler(RequestUpgradeStrategy requestUpgradeStrategy) { // super(requestUpgradeStrategy); // } // // @Override // protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, // Map<String, Object> attributes) { // Principal principal = new DevicePrincipal(UUID.randomUUID().toString()); // return principal; // } // }
import com.wk.lodge.composite.registry.DeviceRegistry; import com.wk.lodge.composite.web.socket.server.support.CompositeHandshakeHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.env.Environment; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy; import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
package com.wk.lodge.composite.config; @Configuration @EnableScheduling @PropertySource("classpath:/rabbitmq.properties") @ComponentScan( basePackages="com.wk.lodge.composite", excludeFilters = @ComponentScan.Filter(type= FilterType.ANNOTATION, value = Configuration.class) ) @EnableWebSocketMessageBroker public class TestWebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { private @Value(value = "${rabbitmq.host}") String relayHost; private @Value(value = "${rabbitmq.port}") Integer relayPort; private @Value(value = "${rabbitmq.clientLogin}") String clientLogin; private @Value(value = "${rabbitmq.clientPasscode}") String clientPasscode; private @Value(value = "${rabbitmq.systemLogin}") String systemLogin; private @Value(value = "${rabbitmq.systemPasscode}") String systemPasscode; @Bean public DefaultHandshakeHandler handshakeHandler() {
// Path: src/main/java/com/wk/lodge/composite/registry/DeviceRegistry.java // public class DeviceRegistry { // private static final Log logger = LogFactory.getLog(DeviceRegistry.class); // private final Set<UUID> healthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Set<UUID> unhealthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Object lock = new Object(); // // /** // * returns a set of unhealthy devices every time the scheduled task defined by DeviceService.deleteUnhealthyDevices // * runs. All devices formerly considered healthy are added to the unhealthy device registry after unhealthy devices // * are added to a temp set, then cleared from the unhealthy device registry. As devices ping the server, they are // * added back into the healthy device registry using the below method, addHealthyDevice. // * // * @return the set of unhealthy device UUIDs // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public Set<UUID> getUnhealthyDevices() { // synchronized(this.lock) { // if(logger.isDebugEnabled()) // logger.debug(String.format("UnhealthyDevices: %d, HealthyDevices: %d", // unhealthyDevices.size(), healthyDevices.size())); // Set<UUID> tempDevices = new CopyOnWriteArraySet<UUID>(); // tempDevices.addAll(unhealthyDevices); // unhealthyDevices.clear(); // unhealthyDevices.addAll(healthyDevices); // healthyDevices.clear(); // return tempDevices; // } // } // // /** // * adds a device UUID to the healthy device registry each time the device pings the server. Devices will always // * be added to the healthy device registry unless they fail to ping the server within the periodic window at which // * the DeviceService.deleteUnhealthyDevices method is called. // * // * @param uuidStr string-form UUID for the device that should be added to the healthy device registry. // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public void addHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // UUID uuid = UUID.fromString(uuidStr); // synchronized(this.lock) { // healthyDevices.add(uuid); // unhealthyDevices.remove(uuid); // } // } // // /** // * checks to see whether a device is healthy or not by looking up the device UUID in the healthy device registry // * // * @param uuidStr string-form UUID for the device to be checked // * @return boolean, whether the device is healthy // */ // public boolean isHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // synchronized(this.lock) { // return healthyDevices.contains(UUID.fromString(uuidStr)); // } // } // } // // Path: src/main/java/com/wk/lodge/composite/web/socket/server/support/CompositeHandshakeHandler.java // public class CompositeHandshakeHandler extends DefaultHandshakeHandler { // // public CompositeHandshakeHandler() { // super(); // } // // public CompositeHandshakeHandler(RequestUpgradeStrategy requestUpgradeStrategy) { // super(requestUpgradeStrategy); // } // // @Override // protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, // Map<String, Object> attributes) { // Principal principal = new DevicePrincipal(UUID.randomUUID().toString()); // return principal; // } // } // Path: src/test/java/com/wk/lodge/composite/config/TestWebSocketConfig.java import com.wk.lodge.composite.registry.DeviceRegistry; import com.wk.lodge.composite.web.socket.server.support.CompositeHandshakeHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.env.Environment; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; package com.wk.lodge.composite.config; @Configuration @EnableScheduling @PropertySource("classpath:/rabbitmq.properties") @ComponentScan( basePackages="com.wk.lodge.composite", excludeFilters = @ComponentScan.Filter(type= FilterType.ANNOTATION, value = Configuration.class) ) @EnableWebSocketMessageBroker public class TestWebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { private @Value(value = "${rabbitmq.host}") String relayHost; private @Value(value = "${rabbitmq.port}") Integer relayPort; private @Value(value = "${rabbitmq.clientLogin}") String clientLogin; private @Value(value = "${rabbitmq.clientPasscode}") String clientPasscode; private @Value(value = "${rabbitmq.systemLogin}") String systemLogin; private @Value(value = "${rabbitmq.systemPasscode}") String systemPasscode; @Bean public DefaultHandshakeHandler handshakeHandler() {
return new CompositeHandshakeHandler(new TomcatRequestUpgradeStrategy());
wieden-kennedy/composite-framework
src/test/java/com/wk/lodge/composite/config/TestWebSocketConfig.java
// Path: src/main/java/com/wk/lodge/composite/registry/DeviceRegistry.java // public class DeviceRegistry { // private static final Log logger = LogFactory.getLog(DeviceRegistry.class); // private final Set<UUID> healthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Set<UUID> unhealthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Object lock = new Object(); // // /** // * returns a set of unhealthy devices every time the scheduled task defined by DeviceService.deleteUnhealthyDevices // * runs. All devices formerly considered healthy are added to the unhealthy device registry after unhealthy devices // * are added to a temp set, then cleared from the unhealthy device registry. As devices ping the server, they are // * added back into the healthy device registry using the below method, addHealthyDevice. // * // * @return the set of unhealthy device UUIDs // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public Set<UUID> getUnhealthyDevices() { // synchronized(this.lock) { // if(logger.isDebugEnabled()) // logger.debug(String.format("UnhealthyDevices: %d, HealthyDevices: %d", // unhealthyDevices.size(), healthyDevices.size())); // Set<UUID> tempDevices = new CopyOnWriteArraySet<UUID>(); // tempDevices.addAll(unhealthyDevices); // unhealthyDevices.clear(); // unhealthyDevices.addAll(healthyDevices); // healthyDevices.clear(); // return tempDevices; // } // } // // /** // * adds a device UUID to the healthy device registry each time the device pings the server. Devices will always // * be added to the healthy device registry unless they fail to ping the server within the periodic window at which // * the DeviceService.deleteUnhealthyDevices method is called. // * // * @param uuidStr string-form UUID for the device that should be added to the healthy device registry. // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public void addHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // UUID uuid = UUID.fromString(uuidStr); // synchronized(this.lock) { // healthyDevices.add(uuid); // unhealthyDevices.remove(uuid); // } // } // // /** // * checks to see whether a device is healthy or not by looking up the device UUID in the healthy device registry // * // * @param uuidStr string-form UUID for the device to be checked // * @return boolean, whether the device is healthy // */ // public boolean isHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // synchronized(this.lock) { // return healthyDevices.contains(UUID.fromString(uuidStr)); // } // } // } // // Path: src/main/java/com/wk/lodge/composite/web/socket/server/support/CompositeHandshakeHandler.java // public class CompositeHandshakeHandler extends DefaultHandshakeHandler { // // public CompositeHandshakeHandler() { // super(); // } // // public CompositeHandshakeHandler(RequestUpgradeStrategy requestUpgradeStrategy) { // super(requestUpgradeStrategy); // } // // @Override // protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, // Map<String, Object> attributes) { // Principal principal = new DevicePrincipal(UUID.randomUUID().toString()); // return principal; // } // }
import com.wk.lodge.composite.registry.DeviceRegistry; import com.wk.lodge.composite.web.socket.server.support.CompositeHandshakeHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.env.Environment; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy; import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
package com.wk.lodge.composite.config; @Configuration @EnableScheduling @PropertySource("classpath:/rabbitmq.properties") @ComponentScan( basePackages="com.wk.lodge.composite", excludeFilters = @ComponentScan.Filter(type= FilterType.ANNOTATION, value = Configuration.class) ) @EnableWebSocketMessageBroker public class TestWebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { private @Value(value = "${rabbitmq.host}") String relayHost; private @Value(value = "${rabbitmq.port}") Integer relayPort; private @Value(value = "${rabbitmq.clientLogin}") String clientLogin; private @Value(value = "${rabbitmq.clientPasscode}") String clientPasscode; private @Value(value = "${rabbitmq.systemLogin}") String systemLogin; private @Value(value = "${rabbitmq.systemPasscode}") String systemPasscode; @Bean public DefaultHandshakeHandler handshakeHandler() { return new CompositeHandshakeHandler(new TomcatRequestUpgradeStrategy()); } @Bean public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); } @Bean
// Path: src/main/java/com/wk/lodge/composite/registry/DeviceRegistry.java // public class DeviceRegistry { // private static final Log logger = LogFactory.getLog(DeviceRegistry.class); // private final Set<UUID> healthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Set<UUID> unhealthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Object lock = new Object(); // // /** // * returns a set of unhealthy devices every time the scheduled task defined by DeviceService.deleteUnhealthyDevices // * runs. All devices formerly considered healthy are added to the unhealthy device registry after unhealthy devices // * are added to a temp set, then cleared from the unhealthy device registry. As devices ping the server, they are // * added back into the healthy device registry using the below method, addHealthyDevice. // * // * @return the set of unhealthy device UUIDs // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public Set<UUID> getUnhealthyDevices() { // synchronized(this.lock) { // if(logger.isDebugEnabled()) // logger.debug(String.format("UnhealthyDevices: %d, HealthyDevices: %d", // unhealthyDevices.size(), healthyDevices.size())); // Set<UUID> tempDevices = new CopyOnWriteArraySet<UUID>(); // tempDevices.addAll(unhealthyDevices); // unhealthyDevices.clear(); // unhealthyDevices.addAll(healthyDevices); // healthyDevices.clear(); // return tempDevices; // } // } // // /** // * adds a device UUID to the healthy device registry each time the device pings the server. Devices will always // * be added to the healthy device registry unless they fail to ping the server within the periodic window at which // * the DeviceService.deleteUnhealthyDevices method is called. // * // * @param uuidStr string-form UUID for the device that should be added to the healthy device registry. // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public void addHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // UUID uuid = UUID.fromString(uuidStr); // synchronized(this.lock) { // healthyDevices.add(uuid); // unhealthyDevices.remove(uuid); // } // } // // /** // * checks to see whether a device is healthy or not by looking up the device UUID in the healthy device registry // * // * @param uuidStr string-form UUID for the device to be checked // * @return boolean, whether the device is healthy // */ // public boolean isHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // synchronized(this.lock) { // return healthyDevices.contains(UUID.fromString(uuidStr)); // } // } // } // // Path: src/main/java/com/wk/lodge/composite/web/socket/server/support/CompositeHandshakeHandler.java // public class CompositeHandshakeHandler extends DefaultHandshakeHandler { // // public CompositeHandshakeHandler() { // super(); // } // // public CompositeHandshakeHandler(RequestUpgradeStrategy requestUpgradeStrategy) { // super(requestUpgradeStrategy); // } // // @Override // protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, // Map<String, Object> attributes) { // Principal principal = new DevicePrincipal(UUID.randomUUID().toString()); // return principal; // } // } // Path: src/test/java/com/wk/lodge/composite/config/TestWebSocketConfig.java import com.wk.lodge.composite.registry.DeviceRegistry; import com.wk.lodge.composite.web.socket.server.support.CompositeHandshakeHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.env.Environment; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; package com.wk.lodge.composite.config; @Configuration @EnableScheduling @PropertySource("classpath:/rabbitmq.properties") @ComponentScan( basePackages="com.wk.lodge.composite", excludeFilters = @ComponentScan.Filter(type= FilterType.ANNOTATION, value = Configuration.class) ) @EnableWebSocketMessageBroker public class TestWebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { private @Value(value = "${rabbitmq.host}") String relayHost; private @Value(value = "${rabbitmq.port}") Integer relayPort; private @Value(value = "${rabbitmq.clientLogin}") String clientLogin; private @Value(value = "${rabbitmq.clientPasscode}") String clientPasscode; private @Value(value = "${rabbitmq.systemLogin}") String systemLogin; private @Value(value = "${rabbitmq.systemPasscode}") String systemPasscode; @Bean public DefaultHandshakeHandler handshakeHandler() { return new CompositeHandshakeHandler(new TomcatRequestUpgradeStrategy()); } @Bean public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); } @Bean
public DeviceRegistry deviceRegistry() {
wieden-kennedy/composite-framework
src/main/java/com/wk/lodge/composite/web/socket/message/outbound/JoinResponse.java
// Path: src/main/java/com/wk/lodge/composite/model/Device.java // public class Device { // private UUID uuid; // private int width; // private int height; // private int performance; // private int instructions; // private String location; // private String country; // // public Device(){ // this.uuid = UUID.randomUUID(); // } // // public Device(String uuid){ // this.uuid = UUID.fromString(uuid); // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public UUID getUuid() { // return uuid; // } // // public void setUuid(UUID uuid) { // this.uuid = uuid; // } // // public int getPerformance() { // return performance; // } // // public void setPerformance(int performance) { // this.performance = performance; // } // // public int getInstructions() { // return instructions; // } // // public void setInstructions(int instructions) { // this.instructions = instructions; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // }
import com.wk.lodge.composite.model.Device; import java.util.ArrayList;
package com.wk.lodge.composite.web.socket.message.outbound; public class JoinResponse extends MatchResponse { private String roomName;
// Path: src/main/java/com/wk/lodge/composite/model/Device.java // public class Device { // private UUID uuid; // private int width; // private int height; // private int performance; // private int instructions; // private String location; // private String country; // // public Device(){ // this.uuid = UUID.randomUUID(); // } // // public Device(String uuid){ // this.uuid = UUID.fromString(uuid); // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public UUID getUuid() { // return uuid; // } // // public void setUuid(UUID uuid) { // this.uuid = uuid; // } // // public int getPerformance() { // return performance; // } // // public void setPerformance(int performance) { // this.performance = performance; // } // // public int getInstructions() { // return instructions; // } // // public void setInstructions(int instructions) { // this.instructions = instructions; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // } // Path: src/main/java/com/wk/lodge/composite/web/socket/message/outbound/JoinResponse.java import com.wk.lodge.composite.model.Device; import java.util.ArrayList; package com.wk.lodge.composite.web.socket.message.outbound; public class JoinResponse extends MatchResponse { private String roomName;
public JoinResponse(String applicationId, String id, ArrayList<Device> devices, String roomName) {
wieden-kennedy/composite-framework
src/main/java/com/wk/lodge/composite/config/RootConfig.java
// Path: src/main/java/com/wk/lodge/composite/repository/DeviceLimiter.java // public class DeviceLimiter { // private HashMap<String,Integer> maxDevicesPerSession; // private float minDistanceThresholdBetweenDevices; // private float maxDistanceThresholdBetweenDevices; // // public DeviceLimiter(HashMap<String,Integer> maxDevicesPerSession, float minDistanceThresholdBetweenDevices, float maxDistanceThresholdBetweenDevices){ // this.maxDevicesPerSession = maxDevicesPerSession; // this.minDistanceThresholdBetweenDevices = minDistanceThresholdBetweenDevices; // this.maxDistanceThresholdBetweenDevices = maxDistanceThresholdBetweenDevices; // } // public HashMap<String,Integer> getMaxDevicesPerSession() { // return maxDevicesPerSession; // } // public float getMinDistanceThresholdBetweenDevices() { // return minDistanceThresholdBetweenDevices; // } // public float getMaxDistanceThresholdBetweenDevices() { // return maxDistanceThresholdBetweenDevices; // } // // public int getMaxDevicesPerSessionForGame(String applicationId){ // return maxDevicesPerSession.get(applicationId); // } // // } // // Path: src/main/java/com/wk/lodge/composite/service/RoomService.java // public class RoomService { // private HashMap<String,String[]> roomNames; // public RoomService(){} // public RoomService(HashMap<String, String[]> roomNames){ // this.roomNames = roomNames; // } // // public String[] getRoomNamesForApplication(String applicationId){ // if(roomNames.containsKey(applicationId)){ // return roomNames.get(applicationId); // } // else{ // return null; // } // } // }
import com.wk.lodge.composite.repository.DeviceLimiter; import com.wk.lodge.composite.service.RoomService; import org.lightcouch.CouchDbClient; import org.lightcouch.CouchDbProperties; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import java.util.HashMap;
@Value(value = "${couchdb.host}") private String couchDbHostname; @Value(value = "${couchdb.port}") private int couchDbHostPort; @Value(value = "${couchdb.createdb.if-not-exist}") private boolean couchDbCreateIfNotExist; @Value(value = "${couchdb.protocol}") private String couchDbProtocol; @Value(value = "${couchdb.max.connections}") private int couchDbMaxConnections; @Value(value = "${couchdb.sessions.database.name}") private String sessionDatabaseName; @Value(value = "${couchdb.username}") private String couchDbAdminUser; @Value(value = "${couchdb.password}") private String couchDbAdminPassword; @Bean public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); } @Bean(destroyMethod = "shutdown") public CouchDbClient couchDbSessionClient(){ CouchDbProperties couchDbProperties = new CouchDbProperties(); couchDbProperties.setHost(couchDbHostname); couchDbProperties.setPort(couchDbHostPort); couchDbProperties.setCreateDbIfNotExist(couchDbCreateIfNotExist); couchDbProperties.setProtocol(couchDbProtocol); couchDbProperties.setMaxConnections(couchDbMaxConnections); couchDbProperties.setDbName(sessionDatabaseName); couchDbProperties.setUsername(couchDbAdminUser); couchDbProperties.setPassword(couchDbAdminPassword); return new CouchDbClient(couchDbProperties); } @Bean
// Path: src/main/java/com/wk/lodge/composite/repository/DeviceLimiter.java // public class DeviceLimiter { // private HashMap<String,Integer> maxDevicesPerSession; // private float minDistanceThresholdBetweenDevices; // private float maxDistanceThresholdBetweenDevices; // // public DeviceLimiter(HashMap<String,Integer> maxDevicesPerSession, float minDistanceThresholdBetweenDevices, float maxDistanceThresholdBetweenDevices){ // this.maxDevicesPerSession = maxDevicesPerSession; // this.minDistanceThresholdBetweenDevices = minDistanceThresholdBetweenDevices; // this.maxDistanceThresholdBetweenDevices = maxDistanceThresholdBetweenDevices; // } // public HashMap<String,Integer> getMaxDevicesPerSession() { // return maxDevicesPerSession; // } // public float getMinDistanceThresholdBetweenDevices() { // return minDistanceThresholdBetweenDevices; // } // public float getMaxDistanceThresholdBetweenDevices() { // return maxDistanceThresholdBetweenDevices; // } // // public int getMaxDevicesPerSessionForGame(String applicationId){ // return maxDevicesPerSession.get(applicationId); // } // // } // // Path: src/main/java/com/wk/lodge/composite/service/RoomService.java // public class RoomService { // private HashMap<String,String[]> roomNames; // public RoomService(){} // public RoomService(HashMap<String, String[]> roomNames){ // this.roomNames = roomNames; // } // // public String[] getRoomNamesForApplication(String applicationId){ // if(roomNames.containsKey(applicationId)){ // return roomNames.get(applicationId); // } // else{ // return null; // } // } // } // Path: src/main/java/com/wk/lodge/composite/config/RootConfig.java import com.wk.lodge.composite.repository.DeviceLimiter; import com.wk.lodge.composite.service.RoomService; import org.lightcouch.CouchDbClient; import org.lightcouch.CouchDbProperties; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import java.util.HashMap; @Value(value = "${couchdb.host}") private String couchDbHostname; @Value(value = "${couchdb.port}") private int couchDbHostPort; @Value(value = "${couchdb.createdb.if-not-exist}") private boolean couchDbCreateIfNotExist; @Value(value = "${couchdb.protocol}") private String couchDbProtocol; @Value(value = "${couchdb.max.connections}") private int couchDbMaxConnections; @Value(value = "${couchdb.sessions.database.name}") private String sessionDatabaseName; @Value(value = "${couchdb.username}") private String couchDbAdminUser; @Value(value = "${couchdb.password}") private String couchDbAdminPassword; @Bean public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); } @Bean(destroyMethod = "shutdown") public CouchDbClient couchDbSessionClient(){ CouchDbProperties couchDbProperties = new CouchDbProperties(); couchDbProperties.setHost(couchDbHostname); couchDbProperties.setPort(couchDbHostPort); couchDbProperties.setCreateDbIfNotExist(couchDbCreateIfNotExist); couchDbProperties.setProtocol(couchDbProtocol); couchDbProperties.setMaxConnections(couchDbMaxConnections); couchDbProperties.setDbName(sessionDatabaseName); couchDbProperties.setUsername(couchDbAdminUser); couchDbProperties.setPassword(couchDbAdminPassword); return new CouchDbClient(couchDbProperties); } @Bean
public DeviceLimiter getDeviceLimiter(){
wieden-kennedy/composite-framework
src/main/java/com/wk/lodge/composite/config/RootConfig.java
// Path: src/main/java/com/wk/lodge/composite/repository/DeviceLimiter.java // public class DeviceLimiter { // private HashMap<String,Integer> maxDevicesPerSession; // private float minDistanceThresholdBetweenDevices; // private float maxDistanceThresholdBetweenDevices; // // public DeviceLimiter(HashMap<String,Integer> maxDevicesPerSession, float minDistanceThresholdBetweenDevices, float maxDistanceThresholdBetweenDevices){ // this.maxDevicesPerSession = maxDevicesPerSession; // this.minDistanceThresholdBetweenDevices = minDistanceThresholdBetweenDevices; // this.maxDistanceThresholdBetweenDevices = maxDistanceThresholdBetweenDevices; // } // public HashMap<String,Integer> getMaxDevicesPerSession() { // return maxDevicesPerSession; // } // public float getMinDistanceThresholdBetweenDevices() { // return minDistanceThresholdBetweenDevices; // } // public float getMaxDistanceThresholdBetweenDevices() { // return maxDistanceThresholdBetweenDevices; // } // // public int getMaxDevicesPerSessionForGame(String applicationId){ // return maxDevicesPerSession.get(applicationId); // } // // } // // Path: src/main/java/com/wk/lodge/composite/service/RoomService.java // public class RoomService { // private HashMap<String,String[]> roomNames; // public RoomService(){} // public RoomService(HashMap<String, String[]> roomNames){ // this.roomNames = roomNames; // } // // public String[] getRoomNamesForApplication(String applicationId){ // if(roomNames.containsKey(applicationId)){ // return roomNames.get(applicationId); // } // else{ // return null; // } // } // }
import com.wk.lodge.composite.repository.DeviceLimiter; import com.wk.lodge.composite.service.RoomService; import org.lightcouch.CouchDbClient; import org.lightcouch.CouchDbProperties; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import java.util.HashMap;
@Bean public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); } @Bean(destroyMethod = "shutdown") public CouchDbClient couchDbSessionClient(){ CouchDbProperties couchDbProperties = new CouchDbProperties(); couchDbProperties.setHost(couchDbHostname); couchDbProperties.setPort(couchDbHostPort); couchDbProperties.setCreateDbIfNotExist(couchDbCreateIfNotExist); couchDbProperties.setProtocol(couchDbProtocol); couchDbProperties.setMaxConnections(couchDbMaxConnections); couchDbProperties.setDbName(sessionDatabaseName); couchDbProperties.setUsername(couchDbAdminUser); couchDbProperties.setPassword(couchDbAdminPassword); return new CouchDbClient(couchDbProperties); } @Bean public DeviceLimiter getDeviceLimiter(){ HashMap<String,Integer> maxDevicesPerSession = new HashMap<>(); maxDevicesPerSession.put(appOneApplicationId, appOneMaxDevicesPerSession); maxDevicesPerSession.put(appTwoApplicationId, appTwoMaxDevicesPerSession); return new DeviceLimiter(maxDevicesPerSession,minDistanceThresholdBetweenDevices,maxDistanceThresholdBetweenDevices); } @Bean
// Path: src/main/java/com/wk/lodge/composite/repository/DeviceLimiter.java // public class DeviceLimiter { // private HashMap<String,Integer> maxDevicesPerSession; // private float minDistanceThresholdBetweenDevices; // private float maxDistanceThresholdBetweenDevices; // // public DeviceLimiter(HashMap<String,Integer> maxDevicesPerSession, float minDistanceThresholdBetweenDevices, float maxDistanceThresholdBetweenDevices){ // this.maxDevicesPerSession = maxDevicesPerSession; // this.minDistanceThresholdBetweenDevices = minDistanceThresholdBetweenDevices; // this.maxDistanceThresholdBetweenDevices = maxDistanceThresholdBetweenDevices; // } // public HashMap<String,Integer> getMaxDevicesPerSession() { // return maxDevicesPerSession; // } // public float getMinDistanceThresholdBetweenDevices() { // return minDistanceThresholdBetweenDevices; // } // public float getMaxDistanceThresholdBetweenDevices() { // return maxDistanceThresholdBetweenDevices; // } // // public int getMaxDevicesPerSessionForGame(String applicationId){ // return maxDevicesPerSession.get(applicationId); // } // // } // // Path: src/main/java/com/wk/lodge/composite/service/RoomService.java // public class RoomService { // private HashMap<String,String[]> roomNames; // public RoomService(){} // public RoomService(HashMap<String, String[]> roomNames){ // this.roomNames = roomNames; // } // // public String[] getRoomNamesForApplication(String applicationId){ // if(roomNames.containsKey(applicationId)){ // return roomNames.get(applicationId); // } // else{ // return null; // } // } // } // Path: src/main/java/com/wk/lodge/composite/config/RootConfig.java import com.wk.lodge.composite.repository.DeviceLimiter; import com.wk.lodge.composite.service.RoomService; import org.lightcouch.CouchDbClient; import org.lightcouch.CouchDbProperties; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import java.util.HashMap; @Bean public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); } @Bean(destroyMethod = "shutdown") public CouchDbClient couchDbSessionClient(){ CouchDbProperties couchDbProperties = new CouchDbProperties(); couchDbProperties.setHost(couchDbHostname); couchDbProperties.setPort(couchDbHostPort); couchDbProperties.setCreateDbIfNotExist(couchDbCreateIfNotExist); couchDbProperties.setProtocol(couchDbProtocol); couchDbProperties.setMaxConnections(couchDbMaxConnections); couchDbProperties.setDbName(sessionDatabaseName); couchDbProperties.setUsername(couchDbAdminUser); couchDbProperties.setPassword(couchDbAdminPassword); return new CouchDbClient(couchDbProperties); } @Bean public DeviceLimiter getDeviceLimiter(){ HashMap<String,Integer> maxDevicesPerSession = new HashMap<>(); maxDevicesPerSession.put(appOneApplicationId, appOneMaxDevicesPerSession); maxDevicesPerSession.put(appTwoApplicationId, appTwoMaxDevicesPerSession); return new DeviceLimiter(maxDevicesPerSession,minDistanceThresholdBetweenDevices,maxDistanceThresholdBetweenDevices); } @Bean
public RoomService getRoomService(){
wieden-kennedy/composite-framework
src/main/java/com/wk/lodge/composite/config/WebSocketConfig.java
// Path: src/main/java/com/wk/lodge/composite/registry/DeviceRegistry.java // public class DeviceRegistry { // private static final Log logger = LogFactory.getLog(DeviceRegistry.class); // private final Set<UUID> healthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Set<UUID> unhealthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Object lock = new Object(); // // /** // * returns a set of unhealthy devices every time the scheduled task defined by DeviceService.deleteUnhealthyDevices // * runs. All devices formerly considered healthy are added to the unhealthy device registry after unhealthy devices // * are added to a temp set, then cleared from the unhealthy device registry. As devices ping the server, they are // * added back into the healthy device registry using the below method, addHealthyDevice. // * // * @return the set of unhealthy device UUIDs // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public Set<UUID> getUnhealthyDevices() { // synchronized(this.lock) { // if(logger.isDebugEnabled()) // logger.debug(String.format("UnhealthyDevices: %d, HealthyDevices: %d", // unhealthyDevices.size(), healthyDevices.size())); // Set<UUID> tempDevices = new CopyOnWriteArraySet<UUID>(); // tempDevices.addAll(unhealthyDevices); // unhealthyDevices.clear(); // unhealthyDevices.addAll(healthyDevices); // healthyDevices.clear(); // return tempDevices; // } // } // // /** // * adds a device UUID to the healthy device registry each time the device pings the server. Devices will always // * be added to the healthy device registry unless they fail to ping the server within the periodic window at which // * the DeviceService.deleteUnhealthyDevices method is called. // * // * @param uuidStr string-form UUID for the device that should be added to the healthy device registry. // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public void addHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // UUID uuid = UUID.fromString(uuidStr); // synchronized(this.lock) { // healthyDevices.add(uuid); // unhealthyDevices.remove(uuid); // } // } // // /** // * checks to see whether a device is healthy or not by looking up the device UUID in the healthy device registry // * // * @param uuidStr string-form UUID for the device to be checked // * @return boolean, whether the device is healthy // */ // public boolean isHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // synchronized(this.lock) { // return healthyDevices.contains(UUID.fromString(uuidStr)); // } // } // } // // Path: src/main/java/com/wk/lodge/composite/web/socket/server/support/CompositeHandshakeHandler.java // public class CompositeHandshakeHandler extends DefaultHandshakeHandler { // // public CompositeHandshakeHandler() { // super(); // } // // public CompositeHandshakeHandler(RequestUpgradeStrategy requestUpgradeStrategy) { // super(requestUpgradeStrategy); // } // // @Override // protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, // Map<String, Object> attributes) { // Principal principal = new DevicePrincipal(UUID.randomUUID().toString()); // return principal; // } // }
import com.wk.lodge.composite.registry.DeviceRegistry; import com.wk.lodge.composite.web.socket.server.support.CompositeHandshakeHandler; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.messaging.simp.config.ChannelRegistration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport; import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration; import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
public void configureClientInboundChannel(ChannelRegistration registration) { registration.taskExecutor().corePoolSize(inboundChannelCorePoolSize); } @Override public void configureClientOutboundChannel(ChannelRegistration registration) { registration.taskExecutor().corePoolSize(outboundChannelCorePoolSize); } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableStompBrokerRelay("/queue/", "/topic/") .setRelayHost(host).setRelayPort(port).setAutoStartup(true) .setClientLogin(clientLogin).setClientPasscode(clientPasscode) .setSystemLogin(systemLogin).setSystemPasscode(systemPasscode) .setSystemHeartbeatSendInterval(systemHeartbeatSendInterval) .setSystemHeartbeatReceiveInterval(systemHeartbeatReceiveInterval); registry.setApplicationDestinationPrefixes("/app"); registry.configureBrokerChannel().taskExecutor().corePoolSize(brokerChannelCorePoolSize); } @Override public void configureWebSocketTransport(WebSocketTransportRegistration registration) { registration.setSendTimeLimit(sendTimeLimit).setSendBufferSizeLimit(sendBufferSizeLimit * 1024); registration.setMessageSizeLimit(messageSizeLimit * 1024); } @Bean public DefaultHandshakeHandler handshakeHandler() {
// Path: src/main/java/com/wk/lodge/composite/registry/DeviceRegistry.java // public class DeviceRegistry { // private static final Log logger = LogFactory.getLog(DeviceRegistry.class); // private final Set<UUID> healthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Set<UUID> unhealthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Object lock = new Object(); // // /** // * returns a set of unhealthy devices every time the scheduled task defined by DeviceService.deleteUnhealthyDevices // * runs. All devices formerly considered healthy are added to the unhealthy device registry after unhealthy devices // * are added to a temp set, then cleared from the unhealthy device registry. As devices ping the server, they are // * added back into the healthy device registry using the below method, addHealthyDevice. // * // * @return the set of unhealthy device UUIDs // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public Set<UUID> getUnhealthyDevices() { // synchronized(this.lock) { // if(logger.isDebugEnabled()) // logger.debug(String.format("UnhealthyDevices: %d, HealthyDevices: %d", // unhealthyDevices.size(), healthyDevices.size())); // Set<UUID> tempDevices = new CopyOnWriteArraySet<UUID>(); // tempDevices.addAll(unhealthyDevices); // unhealthyDevices.clear(); // unhealthyDevices.addAll(healthyDevices); // healthyDevices.clear(); // return tempDevices; // } // } // // /** // * adds a device UUID to the healthy device registry each time the device pings the server. Devices will always // * be added to the healthy device registry unless they fail to ping the server within the periodic window at which // * the DeviceService.deleteUnhealthyDevices method is called. // * // * @param uuidStr string-form UUID for the device that should be added to the healthy device registry. // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public void addHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // UUID uuid = UUID.fromString(uuidStr); // synchronized(this.lock) { // healthyDevices.add(uuid); // unhealthyDevices.remove(uuid); // } // } // // /** // * checks to see whether a device is healthy or not by looking up the device UUID in the healthy device registry // * // * @param uuidStr string-form UUID for the device to be checked // * @return boolean, whether the device is healthy // */ // public boolean isHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // synchronized(this.lock) { // return healthyDevices.contains(UUID.fromString(uuidStr)); // } // } // } // // Path: src/main/java/com/wk/lodge/composite/web/socket/server/support/CompositeHandshakeHandler.java // public class CompositeHandshakeHandler extends DefaultHandshakeHandler { // // public CompositeHandshakeHandler() { // super(); // } // // public CompositeHandshakeHandler(RequestUpgradeStrategy requestUpgradeStrategy) { // super(requestUpgradeStrategy); // } // // @Override // protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, // Map<String, Object> attributes) { // Principal principal = new DevicePrincipal(UUID.randomUUID().toString()); // return principal; // } // } // Path: src/main/java/com/wk/lodge/composite/config/WebSocketConfig.java import com.wk.lodge.composite.registry.DeviceRegistry; import com.wk.lodge.composite.web.socket.server.support.CompositeHandshakeHandler; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.messaging.simp.config.ChannelRegistration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport; import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration; import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; public void configureClientInboundChannel(ChannelRegistration registration) { registration.taskExecutor().corePoolSize(inboundChannelCorePoolSize); } @Override public void configureClientOutboundChannel(ChannelRegistration registration) { registration.taskExecutor().corePoolSize(outboundChannelCorePoolSize); } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableStompBrokerRelay("/queue/", "/topic/") .setRelayHost(host).setRelayPort(port).setAutoStartup(true) .setClientLogin(clientLogin).setClientPasscode(clientPasscode) .setSystemLogin(systemLogin).setSystemPasscode(systemPasscode) .setSystemHeartbeatSendInterval(systemHeartbeatSendInterval) .setSystemHeartbeatReceiveInterval(systemHeartbeatReceiveInterval); registry.setApplicationDestinationPrefixes("/app"); registry.configureBrokerChannel().taskExecutor().corePoolSize(brokerChannelCorePoolSize); } @Override public void configureWebSocketTransport(WebSocketTransportRegistration registration) { registration.setSendTimeLimit(sendTimeLimit).setSendBufferSizeLimit(sendBufferSizeLimit * 1024); registration.setMessageSizeLimit(messageSizeLimit * 1024); } @Bean public DefaultHandshakeHandler handshakeHandler() {
return new CompositeHandshakeHandler();
wieden-kennedy/composite-framework
src/main/java/com/wk/lodge/composite/config/WebSocketConfig.java
// Path: src/main/java/com/wk/lodge/composite/registry/DeviceRegistry.java // public class DeviceRegistry { // private static final Log logger = LogFactory.getLog(DeviceRegistry.class); // private final Set<UUID> healthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Set<UUID> unhealthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Object lock = new Object(); // // /** // * returns a set of unhealthy devices every time the scheduled task defined by DeviceService.deleteUnhealthyDevices // * runs. All devices formerly considered healthy are added to the unhealthy device registry after unhealthy devices // * are added to a temp set, then cleared from the unhealthy device registry. As devices ping the server, they are // * added back into the healthy device registry using the below method, addHealthyDevice. // * // * @return the set of unhealthy device UUIDs // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public Set<UUID> getUnhealthyDevices() { // synchronized(this.lock) { // if(logger.isDebugEnabled()) // logger.debug(String.format("UnhealthyDevices: %d, HealthyDevices: %d", // unhealthyDevices.size(), healthyDevices.size())); // Set<UUID> tempDevices = new CopyOnWriteArraySet<UUID>(); // tempDevices.addAll(unhealthyDevices); // unhealthyDevices.clear(); // unhealthyDevices.addAll(healthyDevices); // healthyDevices.clear(); // return tempDevices; // } // } // // /** // * adds a device UUID to the healthy device registry each time the device pings the server. Devices will always // * be added to the healthy device registry unless they fail to ping the server within the periodic window at which // * the DeviceService.deleteUnhealthyDevices method is called. // * // * @param uuidStr string-form UUID for the device that should be added to the healthy device registry. // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public void addHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // UUID uuid = UUID.fromString(uuidStr); // synchronized(this.lock) { // healthyDevices.add(uuid); // unhealthyDevices.remove(uuid); // } // } // // /** // * checks to see whether a device is healthy or not by looking up the device UUID in the healthy device registry // * // * @param uuidStr string-form UUID for the device to be checked // * @return boolean, whether the device is healthy // */ // public boolean isHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // synchronized(this.lock) { // return healthyDevices.contains(UUID.fromString(uuidStr)); // } // } // } // // Path: src/main/java/com/wk/lodge/composite/web/socket/server/support/CompositeHandshakeHandler.java // public class CompositeHandshakeHandler extends DefaultHandshakeHandler { // // public CompositeHandshakeHandler() { // super(); // } // // public CompositeHandshakeHandler(RequestUpgradeStrategy requestUpgradeStrategy) { // super(requestUpgradeStrategy); // } // // @Override // protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, // Map<String, Object> attributes) { // Principal principal = new DevicePrincipal(UUID.randomUUID().toString()); // return principal; // } // }
import com.wk.lodge.composite.registry.DeviceRegistry; import com.wk.lodge.composite.web.socket.server.support.CompositeHandshakeHandler; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.messaging.simp.config.ChannelRegistration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport; import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration; import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
@Override public void configureClientOutboundChannel(ChannelRegistration registration) { registration.taskExecutor().corePoolSize(outboundChannelCorePoolSize); } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableStompBrokerRelay("/queue/", "/topic/") .setRelayHost(host).setRelayPort(port).setAutoStartup(true) .setClientLogin(clientLogin).setClientPasscode(clientPasscode) .setSystemLogin(systemLogin).setSystemPasscode(systemPasscode) .setSystemHeartbeatSendInterval(systemHeartbeatSendInterval) .setSystemHeartbeatReceiveInterval(systemHeartbeatReceiveInterval); registry.setApplicationDestinationPrefixes("/app"); registry.configureBrokerChannel().taskExecutor().corePoolSize(brokerChannelCorePoolSize); } @Override public void configureWebSocketTransport(WebSocketTransportRegistration registration) { registration.setSendTimeLimit(sendTimeLimit).setSendBufferSizeLimit(sendBufferSizeLimit * 1024); registration.setMessageSizeLimit(messageSizeLimit * 1024); } @Bean public DefaultHandshakeHandler handshakeHandler() { return new CompositeHandshakeHandler(); } @Bean
// Path: src/main/java/com/wk/lodge/composite/registry/DeviceRegistry.java // public class DeviceRegistry { // private static final Log logger = LogFactory.getLog(DeviceRegistry.class); // private final Set<UUID> healthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Set<UUID> unhealthyDevices = new CopyOnWriteArraySet<UUID>(); // private final Object lock = new Object(); // // /** // * returns a set of unhealthy devices every time the scheduled task defined by DeviceService.deleteUnhealthyDevices // * runs. All devices formerly considered healthy are added to the unhealthy device registry after unhealthy devices // * are added to a temp set, then cleared from the unhealthy device registry. As devices ping the server, they are // * added back into the healthy device registry using the below method, addHealthyDevice. // * // * @return the set of unhealthy device UUIDs // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public Set<UUID> getUnhealthyDevices() { // synchronized(this.lock) { // if(logger.isDebugEnabled()) // logger.debug(String.format("UnhealthyDevices: %d, HealthyDevices: %d", // unhealthyDevices.size(), healthyDevices.size())); // Set<UUID> tempDevices = new CopyOnWriteArraySet<UUID>(); // tempDevices.addAll(unhealthyDevices); // unhealthyDevices.clear(); // unhealthyDevices.addAll(healthyDevices); // healthyDevices.clear(); // return tempDevices; // } // } // // /** // * adds a device UUID to the healthy device registry each time the device pings the server. Devices will always // * be added to the healthy device registry unless they fail to ping the server within the periodic window at which // * the DeviceService.deleteUnhealthyDevices method is called. // * // * @param uuidStr string-form UUID for the device that should be added to the healthy device registry. // * // * @see com.wk.lodge.composite.service.DeviceService#deleteUnhealthyDevices() // */ // public void addHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // UUID uuid = UUID.fromString(uuidStr); // synchronized(this.lock) { // healthyDevices.add(uuid); // unhealthyDevices.remove(uuid); // } // } // // /** // * checks to see whether a device is healthy or not by looking up the device UUID in the healthy device registry // * // * @param uuidStr string-form UUID for the device to be checked // * @return boolean, whether the device is healthy // */ // public boolean isHealthyDevice(String uuidStr) { // Assert.notNull(uuidStr, "UUID must not be null"); // synchronized(this.lock) { // return healthyDevices.contains(UUID.fromString(uuidStr)); // } // } // } // // Path: src/main/java/com/wk/lodge/composite/web/socket/server/support/CompositeHandshakeHandler.java // public class CompositeHandshakeHandler extends DefaultHandshakeHandler { // // public CompositeHandshakeHandler() { // super(); // } // // public CompositeHandshakeHandler(RequestUpgradeStrategy requestUpgradeStrategy) { // super(requestUpgradeStrategy); // } // // @Override // protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, // Map<String, Object> attributes) { // Principal principal = new DevicePrincipal(UUID.randomUUID().toString()); // return principal; // } // } // Path: src/main/java/com/wk/lodge/composite/config/WebSocketConfig.java import com.wk.lodge.composite.registry.DeviceRegistry; import com.wk.lodge.composite.web.socket.server.support.CompositeHandshakeHandler; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.messaging.simp.config.ChannelRegistration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport; import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration; import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; @Override public void configureClientOutboundChannel(ChannelRegistration registration) { registration.taskExecutor().corePoolSize(outboundChannelCorePoolSize); } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableStompBrokerRelay("/queue/", "/topic/") .setRelayHost(host).setRelayPort(port).setAutoStartup(true) .setClientLogin(clientLogin).setClientPasscode(clientPasscode) .setSystemLogin(systemLogin).setSystemPasscode(systemPasscode) .setSystemHeartbeatSendInterval(systemHeartbeatSendInterval) .setSystemHeartbeatReceiveInterval(systemHeartbeatReceiveInterval); registry.setApplicationDestinationPrefixes("/app"); registry.configureBrokerChannel().taskExecutor().corePoolSize(brokerChannelCorePoolSize); } @Override public void configureWebSocketTransport(WebSocketTransportRegistration registration) { registration.setSendTimeLimit(sendTimeLimit).setSendBufferSizeLimit(sendBufferSizeLimit * 1024); registration.setMessageSizeLimit(messageSizeLimit * 1024); } @Bean public DefaultHandshakeHandler handshakeHandler() { return new CompositeHandshakeHandler(); } @Bean
public DeviceRegistry deviceRegistry() {
wieden-kennedy/composite-framework
src/test/java/com/wk/lodge/composite/config/TestRootConfig.java
// Path: src/main/java/com/wk/lodge/composite/repository/DeviceLimiter.java // public class DeviceLimiter { // private HashMap<String,Integer> maxDevicesPerSession; // private float minDistanceThresholdBetweenDevices; // private float maxDistanceThresholdBetweenDevices; // // public DeviceLimiter(HashMap<String,Integer> maxDevicesPerSession, float minDistanceThresholdBetweenDevices, float maxDistanceThresholdBetweenDevices){ // this.maxDevicesPerSession = maxDevicesPerSession; // this.minDistanceThresholdBetweenDevices = minDistanceThresholdBetweenDevices; // this.maxDistanceThresholdBetweenDevices = maxDistanceThresholdBetweenDevices; // } // public HashMap<String,Integer> getMaxDevicesPerSession() { // return maxDevicesPerSession; // } // public float getMinDistanceThresholdBetweenDevices() { // return minDistanceThresholdBetweenDevices; // } // public float getMaxDistanceThresholdBetweenDevices() { // return maxDistanceThresholdBetweenDevices; // } // // public int getMaxDevicesPerSessionForGame(String applicationId){ // return maxDevicesPerSession.get(applicationId); // } // // } // // Path: src/main/java/com/wk/lodge/composite/service/RoomService.java // public class RoomService { // private HashMap<String,String[]> roomNames; // public RoomService(){} // public RoomService(HashMap<String, String[]> roomNames){ // this.roomNames = roomNames; // } // // public String[] getRoomNamesForApplication(String applicationId){ // if(roomNames.containsKey(applicationId)){ // return roomNames.get(applicationId); // } // else{ // return null; // } // } // }
import com.wk.lodge.composite.repository.DeviceLimiter; import com.wk.lodge.composite.service.RoomService; import org.lightcouch.CouchDbClient; import org.lightcouch.CouchDbProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.*; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.env.Environment; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.SubscribableChannel; import org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler; import java.util.HashMap; import java.util.List;
@Value(value = "${couchdb.host}") private String couchDbHostname; @Value(value = "${couchdb.port}") private int couchDbHostPort; @Value(value = "${couchdb.createdb.if-not-exist}") private boolean couchDbCreateIfNotExist; @Value(value = "${couchdb.protocol}") private String couchDbProtocol; @Value(value = "${couchdb.max.connections}") private int couchDbMaxConnections; @Value(value = "${couchdb.sessions.database.name}") private String sessionDatabaseName; @Value(value = "${couchdb.username}") private String couchDbAdminUser; @Value(value = "${couchdb.password}") private String couchDbAdminPassword; @Bean public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); } @Bean(destroyMethod = "shutdown") public CouchDbClient couchDbSessionClient(){ CouchDbProperties couchDbProperties = new CouchDbProperties(); couchDbProperties.setHost(couchDbHostname); couchDbProperties.setPort(couchDbHostPort); couchDbProperties.setCreateDbIfNotExist(couchDbCreateIfNotExist); couchDbProperties.setProtocol(couchDbProtocol); couchDbProperties.setMaxConnections(couchDbMaxConnections); couchDbProperties.setDbName(sessionDatabaseName); couchDbProperties.setUsername(couchDbAdminUser); couchDbProperties.setPassword(couchDbAdminPassword); return new CouchDbClient(couchDbProperties); } @Bean
// Path: src/main/java/com/wk/lodge/composite/repository/DeviceLimiter.java // public class DeviceLimiter { // private HashMap<String,Integer> maxDevicesPerSession; // private float minDistanceThresholdBetweenDevices; // private float maxDistanceThresholdBetweenDevices; // // public DeviceLimiter(HashMap<String,Integer> maxDevicesPerSession, float minDistanceThresholdBetweenDevices, float maxDistanceThresholdBetweenDevices){ // this.maxDevicesPerSession = maxDevicesPerSession; // this.minDistanceThresholdBetweenDevices = minDistanceThresholdBetweenDevices; // this.maxDistanceThresholdBetweenDevices = maxDistanceThresholdBetweenDevices; // } // public HashMap<String,Integer> getMaxDevicesPerSession() { // return maxDevicesPerSession; // } // public float getMinDistanceThresholdBetweenDevices() { // return minDistanceThresholdBetweenDevices; // } // public float getMaxDistanceThresholdBetweenDevices() { // return maxDistanceThresholdBetweenDevices; // } // // public int getMaxDevicesPerSessionForGame(String applicationId){ // return maxDevicesPerSession.get(applicationId); // } // // } // // Path: src/main/java/com/wk/lodge/composite/service/RoomService.java // public class RoomService { // private HashMap<String,String[]> roomNames; // public RoomService(){} // public RoomService(HashMap<String, String[]> roomNames){ // this.roomNames = roomNames; // } // // public String[] getRoomNamesForApplication(String applicationId){ // if(roomNames.containsKey(applicationId)){ // return roomNames.get(applicationId); // } // else{ // return null; // } // } // } // Path: src/test/java/com/wk/lodge/composite/config/TestRootConfig.java import com.wk.lodge.composite.repository.DeviceLimiter; import com.wk.lodge.composite.service.RoomService; import org.lightcouch.CouchDbClient; import org.lightcouch.CouchDbProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.*; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.env.Environment; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.SubscribableChannel; import org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler; import java.util.HashMap; import java.util.List; @Value(value = "${couchdb.host}") private String couchDbHostname; @Value(value = "${couchdb.port}") private int couchDbHostPort; @Value(value = "${couchdb.createdb.if-not-exist}") private boolean couchDbCreateIfNotExist; @Value(value = "${couchdb.protocol}") private String couchDbProtocol; @Value(value = "${couchdb.max.connections}") private int couchDbMaxConnections; @Value(value = "${couchdb.sessions.database.name}") private String sessionDatabaseName; @Value(value = "${couchdb.username}") private String couchDbAdminUser; @Value(value = "${couchdb.password}") private String couchDbAdminPassword; @Bean public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); } @Bean(destroyMethod = "shutdown") public CouchDbClient couchDbSessionClient(){ CouchDbProperties couchDbProperties = new CouchDbProperties(); couchDbProperties.setHost(couchDbHostname); couchDbProperties.setPort(couchDbHostPort); couchDbProperties.setCreateDbIfNotExist(couchDbCreateIfNotExist); couchDbProperties.setProtocol(couchDbProtocol); couchDbProperties.setMaxConnections(couchDbMaxConnections); couchDbProperties.setDbName(sessionDatabaseName); couchDbProperties.setUsername(couchDbAdminUser); couchDbProperties.setPassword(couchDbAdminPassword); return new CouchDbClient(couchDbProperties); } @Bean
public DeviceLimiter deviceLimiter(){
wieden-kennedy/composite-framework
src/test/java/com/wk/lodge/composite/config/TestRootConfig.java
// Path: src/main/java/com/wk/lodge/composite/repository/DeviceLimiter.java // public class DeviceLimiter { // private HashMap<String,Integer> maxDevicesPerSession; // private float minDistanceThresholdBetweenDevices; // private float maxDistanceThresholdBetweenDevices; // // public DeviceLimiter(HashMap<String,Integer> maxDevicesPerSession, float minDistanceThresholdBetweenDevices, float maxDistanceThresholdBetweenDevices){ // this.maxDevicesPerSession = maxDevicesPerSession; // this.minDistanceThresholdBetweenDevices = minDistanceThresholdBetweenDevices; // this.maxDistanceThresholdBetweenDevices = maxDistanceThresholdBetweenDevices; // } // public HashMap<String,Integer> getMaxDevicesPerSession() { // return maxDevicesPerSession; // } // public float getMinDistanceThresholdBetweenDevices() { // return minDistanceThresholdBetweenDevices; // } // public float getMaxDistanceThresholdBetweenDevices() { // return maxDistanceThresholdBetweenDevices; // } // // public int getMaxDevicesPerSessionForGame(String applicationId){ // return maxDevicesPerSession.get(applicationId); // } // // } // // Path: src/main/java/com/wk/lodge/composite/service/RoomService.java // public class RoomService { // private HashMap<String,String[]> roomNames; // public RoomService(){} // public RoomService(HashMap<String, String[]> roomNames){ // this.roomNames = roomNames; // } // // public String[] getRoomNamesForApplication(String applicationId){ // if(roomNames.containsKey(applicationId)){ // return roomNames.get(applicationId); // } // else{ // return null; // } // } // }
import com.wk.lodge.composite.repository.DeviceLimiter; import com.wk.lodge.composite.service.RoomService; import org.lightcouch.CouchDbClient; import org.lightcouch.CouchDbProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.*; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.env.Environment; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.SubscribableChannel; import org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler; import java.util.HashMap; import java.util.List;
@Bean public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); } @Bean(destroyMethod = "shutdown") public CouchDbClient couchDbSessionClient(){ CouchDbProperties couchDbProperties = new CouchDbProperties(); couchDbProperties.setHost(couchDbHostname); couchDbProperties.setPort(couchDbHostPort); couchDbProperties.setCreateDbIfNotExist(couchDbCreateIfNotExist); couchDbProperties.setProtocol(couchDbProtocol); couchDbProperties.setMaxConnections(couchDbMaxConnections); couchDbProperties.setDbName(sessionDatabaseName); couchDbProperties.setUsername(couchDbAdminUser); couchDbProperties.setPassword(couchDbAdminPassword); return new CouchDbClient(couchDbProperties); } @Bean public DeviceLimiter deviceLimiter(){ HashMap<String,Integer> maxDevicesPerSession = new HashMap<>(); maxDevicesPerSession.put(appOneApplicationId, appOneMaxDevicesPerSession); maxDevicesPerSession.put(appTwoApplicationId, appTwoMaxDevicesPerSession); return new DeviceLimiter(maxDevicesPerSession,minDistanceThresholdBetweenDevices,maxDistanceThresholdBetweenDevices); } @Bean
// Path: src/main/java/com/wk/lodge/composite/repository/DeviceLimiter.java // public class DeviceLimiter { // private HashMap<String,Integer> maxDevicesPerSession; // private float minDistanceThresholdBetweenDevices; // private float maxDistanceThresholdBetweenDevices; // // public DeviceLimiter(HashMap<String,Integer> maxDevicesPerSession, float minDistanceThresholdBetweenDevices, float maxDistanceThresholdBetweenDevices){ // this.maxDevicesPerSession = maxDevicesPerSession; // this.minDistanceThresholdBetweenDevices = minDistanceThresholdBetweenDevices; // this.maxDistanceThresholdBetweenDevices = maxDistanceThresholdBetweenDevices; // } // public HashMap<String,Integer> getMaxDevicesPerSession() { // return maxDevicesPerSession; // } // public float getMinDistanceThresholdBetweenDevices() { // return minDistanceThresholdBetweenDevices; // } // public float getMaxDistanceThresholdBetweenDevices() { // return maxDistanceThresholdBetweenDevices; // } // // public int getMaxDevicesPerSessionForGame(String applicationId){ // return maxDevicesPerSession.get(applicationId); // } // // } // // Path: src/main/java/com/wk/lodge/composite/service/RoomService.java // public class RoomService { // private HashMap<String,String[]> roomNames; // public RoomService(){} // public RoomService(HashMap<String, String[]> roomNames){ // this.roomNames = roomNames; // } // // public String[] getRoomNamesForApplication(String applicationId){ // if(roomNames.containsKey(applicationId)){ // return roomNames.get(applicationId); // } // else{ // return null; // } // } // } // Path: src/test/java/com/wk/lodge/composite/config/TestRootConfig.java import com.wk.lodge.composite.repository.DeviceLimiter; import com.wk.lodge.composite.service.RoomService; import org.lightcouch.CouchDbClient; import org.lightcouch.CouchDbProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.*; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.env.Environment; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.SubscribableChannel; import org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler; import java.util.HashMap; import java.util.List; @Bean public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); } @Bean(destroyMethod = "shutdown") public CouchDbClient couchDbSessionClient(){ CouchDbProperties couchDbProperties = new CouchDbProperties(); couchDbProperties.setHost(couchDbHostname); couchDbProperties.setPort(couchDbHostPort); couchDbProperties.setCreateDbIfNotExist(couchDbCreateIfNotExist); couchDbProperties.setProtocol(couchDbProtocol); couchDbProperties.setMaxConnections(couchDbMaxConnections); couchDbProperties.setDbName(sessionDatabaseName); couchDbProperties.setUsername(couchDbAdminUser); couchDbProperties.setPassword(couchDbAdminPassword); return new CouchDbClient(couchDbProperties); } @Bean public DeviceLimiter deviceLimiter(){ HashMap<String,Integer> maxDevicesPerSession = new HashMap<>(); maxDevicesPerSession.put(appOneApplicationId, appOneMaxDevicesPerSession); maxDevicesPerSession.put(appTwoApplicationId, appTwoMaxDevicesPerSession); return new DeviceLimiter(maxDevicesPerSession,minDistanceThresholdBetweenDevices,maxDistanceThresholdBetweenDevices); } @Bean
public RoomService roomService(){
mkenne11/nogotofail-pii
nogotofail/test/android/app/src/main/java/net/nogotofail/mitmtester/BackgroundTestForHttpPii.java
// Path: nogotofail/test/android/app/src/main/java/net/nogotofail/mitmtester/util/ClientProperties.java // public class ClientProperties { // // public static String getAndroidId(Context context) { // return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); // } // // public static Info getAdvertisingId(Context context) { // Info advertising_info; // try { // advertising_info = AdvertisingIdClient.getAdvertisingIdInfo(context); // /** // * TODO: Include check to alert when device user has enabled "Limit Ad Tracking" // * for their Google account. This will allow testers to verify apps sending the // * user's "Android ID" to advertisers when they shouldn't. // */ // //final boolean ad_tracking_limited = advertising_info.isLimitAdTrackingEnabled(); // } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException | // IOException e) { // /** Encountered a recoverable error connecting to Google Play services OR // * Google Play services is not available entirely OR // * a general IO exception. // */ // advertising_info = null; // } // return advertising_info; // } // // public static String getDeviceId(Context context) { // //Retrieve a reference to an instance of TelephonyManager // TelephonyManager telephonyManager = // (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); // // Fetch the device's unique ID if it exists. // // Note. This varies depending on network e.g. IMEI for GSM, MEID/ESN for CDMA. // String device_id = telephonyManager.getDeviceId(); // if (device_id == null){ // return null; // } // else { // return device_id; // } // } // // public static String getMacAddress (Context context) { // WifiManager wifi_manager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); // WifiInfo wifi_info = wifi_manager.getConnectionInfo(); // // // Fetch the device's WiFi MAC address. // String mac_address = wifi_info.getMacAddress(); // if (mac_address == null) { // return null; // } // else { // return mac_address; // } // } // // public static Location getDeviceLocation (Context context) { // Location last_known_location = null; // try { // LocationManager location_manager = // (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); // // Criteria criteria = new Criteria(); // criteria.setAccuracy(Criteria.ACCURACY_FINE); // String location_provider = location_manager.getBestProvider(criteria, false); // last_known_location = location_manager.getLastKnownLocation(location_provider); // } // catch (Exception e) { // // } // return last_known_location; // } // }
import android.content.Context; import android.location.Location; import com.google.android.gms.ads.identifier.AdvertisingIdClient; import net.nogotofail.mitmtester.util.ClientProperties;
/* * Copyright 2014 Google Inc. All Rights Reserved. * * 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.nogotofail.mitmtester; /** * Extension of BackgroundTest class with awareness of application context. * Note. Application context is needed to access system resources (Device IDs & * location) and application resources (strings.xml). */ public abstract class BackgroundTestForHttpPii extends BackgroundTest { protected static final String HTTP_TARGET = "http://android.com/"; protected static final String HTTPS_TARGET = "https://google.com/"; protected static final int CONNECTION_TIMEOUT = 10000; protected String android_id, google_ad_id; protected AdvertisingIdClient.Info advertising_info; protected Location client_location; protected String location_longitude, location_latitude; protected String email; private Context mContext; protected BackgroundTestForHttpPii(Context app_context) { mContext = app_context; } protected abstract void runTest() throws Exception; protected Context getContext(){ return this.mContext; } protected void FetchPIITestData() {
// Path: nogotofail/test/android/app/src/main/java/net/nogotofail/mitmtester/util/ClientProperties.java // public class ClientProperties { // // public static String getAndroidId(Context context) { // return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); // } // // public static Info getAdvertisingId(Context context) { // Info advertising_info; // try { // advertising_info = AdvertisingIdClient.getAdvertisingIdInfo(context); // /** // * TODO: Include check to alert when device user has enabled "Limit Ad Tracking" // * for their Google account. This will allow testers to verify apps sending the // * user's "Android ID" to advertisers when they shouldn't. // */ // //final boolean ad_tracking_limited = advertising_info.isLimitAdTrackingEnabled(); // } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException | // IOException e) { // /** Encountered a recoverable error connecting to Google Play services OR // * Google Play services is not available entirely OR // * a general IO exception. // */ // advertising_info = null; // } // return advertising_info; // } // // public static String getDeviceId(Context context) { // //Retrieve a reference to an instance of TelephonyManager // TelephonyManager telephonyManager = // (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); // // Fetch the device's unique ID if it exists. // // Note. This varies depending on network e.g. IMEI for GSM, MEID/ESN for CDMA. // String device_id = telephonyManager.getDeviceId(); // if (device_id == null){ // return null; // } // else { // return device_id; // } // } // // public static String getMacAddress (Context context) { // WifiManager wifi_manager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); // WifiInfo wifi_info = wifi_manager.getConnectionInfo(); // // // Fetch the device's WiFi MAC address. // String mac_address = wifi_info.getMacAddress(); // if (mac_address == null) { // return null; // } // else { // return mac_address; // } // } // // public static Location getDeviceLocation (Context context) { // Location last_known_location = null; // try { // LocationManager location_manager = // (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); // // Criteria criteria = new Criteria(); // criteria.setAccuracy(Criteria.ACCURACY_FINE); // String location_provider = location_manager.getBestProvider(criteria, false); // last_known_location = location_manager.getLastKnownLocation(location_provider); // } // catch (Exception e) { // // } // return last_known_location; // } // } // Path: nogotofail/test/android/app/src/main/java/net/nogotofail/mitmtester/BackgroundTestForHttpPii.java import android.content.Context; import android.location.Location; import com.google.android.gms.ads.identifier.AdvertisingIdClient; import net.nogotofail.mitmtester.util.ClientProperties; /* * Copyright 2014 Google Inc. All Rights Reserved. * * 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.nogotofail.mitmtester; /** * Extension of BackgroundTest class with awareness of application context. * Note. Application context is needed to access system resources (Device IDs & * location) and application resources (strings.xml). */ public abstract class BackgroundTestForHttpPii extends BackgroundTest { protected static final String HTTP_TARGET = "http://android.com/"; protected static final String HTTPS_TARGET = "https://google.com/"; protected static final int CONNECTION_TIMEOUT = 10000; protected String android_id, google_ad_id; protected AdvertisingIdClient.Info advertising_info; protected Location client_location; protected String location_longitude, location_latitude; protected String email; private Context mContext; protected BackgroundTestForHttpPii(Context app_context) { mContext = app_context; } protected abstract void runTest() throws Exception; protected Context getContext(){ return this.mContext; } protected void FetchPIITestData() {
android_id = ClientProperties.getAndroidId(mContext);
lukasniemeier/mensaapp
MensaApp/src/main/java/de/lukasniemeier/mensa/ui/adapter/NavigationAdapter.java
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/WeeklyMenu.java // public class WeeklyMenu implements Serializable { // // private final Mensa mensa; // private SerializableTime timestamp; // private BiMap<SerializableTime, Menu> menuMap; // // public WeeklyMenu(Mensa mensa, SerializableTime timestamp) { // this.mensa = mensa; // this.timestamp = timestamp; // this.menuMap = HashBiMap.create(); // } // // public Mensa getMensa() { // return mensa; // } // // public Time getTimestamp() { // return timestamp.getTime(); // } // // public BiMap<SerializableTime, Menu> getMenus() { // return menuMap; // } // // public void addMenu(SerializableTime date, Menu menu) { // menuMap.put(date, menu); // } // // public Menu getMenu(SerializableTime date) { // return menuMap.get(date); // } // // public boolean hasMenu(SerializableTime date) { // return menuMap.keySet().contains(date); // } // // public static WeeklyMenu merge(Mensa mensa, SerializableTime timestamp, List<WeeklyMenu> menus) { // WeeklyMenu merged = new WeeklyMenu(mensa, timestamp); // for (WeeklyMenu weeklyMenu : menus) { // for (Map.Entry<SerializableTime, Menu> entry : weeklyMenu.menuMap.entrySet()) { // merged.addMenu(entry.getKey(), entry.getValue()); // } // } // return merged; // } // // public boolean isOutdated() { // SerializableTime now = Utils.now(); // return now.getYearDay() > timestamp.getYearDay() || now.getYear() > timestamp.getYear(); // } // }
import android.app.ActionBar; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import de.lukasniemeier.mensa.model.WeeklyMenu;
this.fragmentManager = fragmentManager; this.state = new NavigationAdapterState(this, context) { @Override public Fragment getItem(int position) { return null; } @Override public int getItemPosition(Object object) { return POSITION_NONE; } @Override public int getCount() { return 0; } }; pager.setAdapter(this); } public ActionBar getActionBar() { return actionBar; } public ViewPager getPager() { return pager; }
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/WeeklyMenu.java // public class WeeklyMenu implements Serializable { // // private final Mensa mensa; // private SerializableTime timestamp; // private BiMap<SerializableTime, Menu> menuMap; // // public WeeklyMenu(Mensa mensa, SerializableTime timestamp) { // this.mensa = mensa; // this.timestamp = timestamp; // this.menuMap = HashBiMap.create(); // } // // public Mensa getMensa() { // return mensa; // } // // public Time getTimestamp() { // return timestamp.getTime(); // } // // public BiMap<SerializableTime, Menu> getMenus() { // return menuMap; // } // // public void addMenu(SerializableTime date, Menu menu) { // menuMap.put(date, menu); // } // // public Menu getMenu(SerializableTime date) { // return menuMap.get(date); // } // // public boolean hasMenu(SerializableTime date) { // return menuMap.keySet().contains(date); // } // // public static WeeklyMenu merge(Mensa mensa, SerializableTime timestamp, List<WeeklyMenu> menus) { // WeeklyMenu merged = new WeeklyMenu(mensa, timestamp); // for (WeeklyMenu weeklyMenu : menus) { // for (Map.Entry<SerializableTime, Menu> entry : weeklyMenu.menuMap.entrySet()) { // merged.addMenu(entry.getKey(), entry.getValue()); // } // } // return merged; // } // // public boolean isOutdated() { // SerializableTime now = Utils.now(); // return now.getYearDay() > timestamp.getYearDay() || now.getYear() > timestamp.getYear(); // } // } // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ui/adapter/NavigationAdapter.java import android.app.ActionBar; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import de.lukasniemeier.mensa.model.WeeklyMenu; this.fragmentManager = fragmentManager; this.state = new NavigationAdapterState(this, context) { @Override public Fragment getItem(int position) { return null; } @Override public int getItemPosition(Object object) { return POSITION_NONE; } @Override public int getCount() { return 0; } }; pager.setAdapter(this); } public ActionBar getActionBar() { return actionBar; } public ViewPager getPager() { return pager; }
public void displayMenu(WeeklyMenu menu, int initialMenuIndex) {
lukasniemeier/mensaapp
MensaApp/src/main/java/de/lukasniemeier/mensa/ui/preference/ThemedPreferenceActivity.java
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ui/ThemeHelper.java // public class ThemeHelper { // // public static int getRefreshBarColor(Context context) { // TypedArray attributes = context.getTheme().obtainStyledAttributes( // new int[]{R.attr.refresh_bar_color}); // int colorId; // if (attributes != null) { // colorId = attributes.getColor(0, R.color.dark_green_studi); // attributes.recycle(); // } else { // colorId = context.getResources().getColor(R.color.dark_green_studi); // } // return colorId; // } // // public static int currentTheme(Context context) { // SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); // String themeValue = preferences.getString("settings_list_theme", String.valueOf(R.style.Theme_Studi_Theme)); // // ensure value is saved // preferences.edit().putString("settings_list_theme", themeValue).commit(); // return Integer.valueOf(themeValue); // } // }
import android.os.Bundle; import android.preference.PreferenceActivity; import de.lukasniemeier.mensa.ui.ThemeHelper;
package de.lukasniemeier.mensa.ui.preference; /** * Created on 19.11.13. */ public abstract class ThemedPreferenceActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) {
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ui/ThemeHelper.java // public class ThemeHelper { // // public static int getRefreshBarColor(Context context) { // TypedArray attributes = context.getTheme().obtainStyledAttributes( // new int[]{R.attr.refresh_bar_color}); // int colorId; // if (attributes != null) { // colorId = attributes.getColor(0, R.color.dark_green_studi); // attributes.recycle(); // } else { // colorId = context.getResources().getColor(R.color.dark_green_studi); // } // return colorId; // } // // public static int currentTheme(Context context) { // SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); // String themeValue = preferences.getString("settings_list_theme", String.valueOf(R.style.Theme_Studi_Theme)); // // ensure value is saved // preferences.edit().putString("settings_list_theme", themeValue).commit(); // return Integer.valueOf(themeValue); // } // } // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ui/preference/ThemedPreferenceActivity.java import android.os.Bundle; import android.preference.PreferenceActivity; import de.lukasniemeier.mensa.ui.ThemeHelper; package de.lukasniemeier.mensa.ui.preference; /** * Created on 19.11.13. */ public abstract class ThemedPreferenceActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) {
setTheme(ThemeHelper.currentTheme(this));
lukasniemeier/mensaapp
MensaApp/src/main/java/de/lukasniemeier/mensa/model/WeeklyMenu.java
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/utils/SerializableTime.java // public class SerializableTime implements Comparable<SerializableTime>, Serializable { // // private static Time toTime(Date date) { // Time time = new Time(); // time.set(date.getTime()); // return time; // } // // private Time timestamp; // // public SerializableTime(Time timestamp) { // this.timestamp = timestamp; // } // // public SerializableTime(Date date) { // this(toTime(date)); // } // // public Time getTime() { // return timestamp; // } // // private void writeObject(java.io.ObjectOutputStream out) // throws IOException { // out.writeObject(timestamp.toMillis(false)); // } // // private void readObject(java.io.ObjectInputStream in) // throws IOException, ClassNotFoundException { // long ms = (Long) in.readObject(); // this.timestamp = new Time(); // this.timestamp.set(ms); // } // // public long toMillis() { // return timestamp.toMillis(false); // } // // public int getYearDay() { // return timestamp.yearDay; // } // // public int getYear() { // return timestamp.year; // } // // public Date toDate() { // return new Date(toMillis()); // } // // @Override // public int compareTo(SerializableTime other) { // return Time.compare(this.getTime(), other.getTime()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SerializableTime that = (SerializableTime) o; // return timestamp.toMillis(false) == that.timestamp.toMillis(false); // } // // @Override // public int hashCode() { // long ht = timestamp.toMillis(false); // return (int) ht ^ (int) (ht >> 32); // } // } // // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/utils/Utils.java // public class Utils { // // private static final DateFormat defaultMenuDateFormat = new SimpleDateFormat("c, d.MM"); // // public static String formatDate(Context context, SerializableTime time) { // return formatDate(context, time, defaultMenuDateFormat); // } // // public static String formatDate(Context context, SerializableTime time, DateFormat format) { // if (DateUtils.isToday(time.toMillis())) { // return context.getString(R.string.today); // } else if(DateUtils.isToday(time.toMillis() - 1000 * 60 * 60 * 24)) { // return context.getString(R.string.tomorrow); // } else { // return format.format(time.toDate()); // } // } // // public static SerializableTime today() { // Calendar today = Calendar.getInstance(); // today.set(Calendar.HOUR, 0); // today.set(Calendar.MINUTE, 0); // today.set(Calendar.SECOND, 0); // today.set(Calendar.MILLISECOND, 0); // return new SerializableTime(today.getTime()); // } // // public static SerializableTime now() { // Time now = new Time(); // now.setToNow(); // return new SerializableTime(now); // } // // public static void restartApp(Activity context) { // Intent i = context.getBaseContext().getPackageManager().getLaunchIntentForPackage(context.getBaseContext().getPackageName()); // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // context.startActivity(i); // } // // public static int dpToPx(Context context, int dp) { // float density = context.getResources().getDisplayMetrics().density; // return (int)(dp * density); // } // // private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); // // /** // * Generate a value suitable for use in {@link android.view.View#setId(int)}. // * This value will not collide with ID values generated at build time by aapt for R.id. // * // * @return a generated ID value // */ // public static int generateViewId() { // for (;;) { // final int result = sNextGeneratedId.get(); // // aapt-generated IDs have the high byte nonzero; clamp to the range under that. // int newValue = result + 1; // if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. // if (sNextGeneratedId.compareAndSet(result, newValue)) { // return result; // } // } // } // }
import android.text.format.Time; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import java.io.Serializable; import java.util.List; import java.util.Map; import de.lukasniemeier.mensa.utils.SerializableTime; import de.lukasniemeier.mensa.utils.Utils;
package de.lukasniemeier.mensa.model; /** * Created on 17.09.13. */ public class WeeklyMenu implements Serializable { private final Mensa mensa;
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/utils/SerializableTime.java // public class SerializableTime implements Comparable<SerializableTime>, Serializable { // // private static Time toTime(Date date) { // Time time = new Time(); // time.set(date.getTime()); // return time; // } // // private Time timestamp; // // public SerializableTime(Time timestamp) { // this.timestamp = timestamp; // } // // public SerializableTime(Date date) { // this(toTime(date)); // } // // public Time getTime() { // return timestamp; // } // // private void writeObject(java.io.ObjectOutputStream out) // throws IOException { // out.writeObject(timestamp.toMillis(false)); // } // // private void readObject(java.io.ObjectInputStream in) // throws IOException, ClassNotFoundException { // long ms = (Long) in.readObject(); // this.timestamp = new Time(); // this.timestamp.set(ms); // } // // public long toMillis() { // return timestamp.toMillis(false); // } // // public int getYearDay() { // return timestamp.yearDay; // } // // public int getYear() { // return timestamp.year; // } // // public Date toDate() { // return new Date(toMillis()); // } // // @Override // public int compareTo(SerializableTime other) { // return Time.compare(this.getTime(), other.getTime()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SerializableTime that = (SerializableTime) o; // return timestamp.toMillis(false) == that.timestamp.toMillis(false); // } // // @Override // public int hashCode() { // long ht = timestamp.toMillis(false); // return (int) ht ^ (int) (ht >> 32); // } // } // // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/utils/Utils.java // public class Utils { // // private static final DateFormat defaultMenuDateFormat = new SimpleDateFormat("c, d.MM"); // // public static String formatDate(Context context, SerializableTime time) { // return formatDate(context, time, defaultMenuDateFormat); // } // // public static String formatDate(Context context, SerializableTime time, DateFormat format) { // if (DateUtils.isToday(time.toMillis())) { // return context.getString(R.string.today); // } else if(DateUtils.isToday(time.toMillis() - 1000 * 60 * 60 * 24)) { // return context.getString(R.string.tomorrow); // } else { // return format.format(time.toDate()); // } // } // // public static SerializableTime today() { // Calendar today = Calendar.getInstance(); // today.set(Calendar.HOUR, 0); // today.set(Calendar.MINUTE, 0); // today.set(Calendar.SECOND, 0); // today.set(Calendar.MILLISECOND, 0); // return new SerializableTime(today.getTime()); // } // // public static SerializableTime now() { // Time now = new Time(); // now.setToNow(); // return new SerializableTime(now); // } // // public static void restartApp(Activity context) { // Intent i = context.getBaseContext().getPackageManager().getLaunchIntentForPackage(context.getBaseContext().getPackageName()); // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // context.startActivity(i); // } // // public static int dpToPx(Context context, int dp) { // float density = context.getResources().getDisplayMetrics().density; // return (int)(dp * density); // } // // private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); // // /** // * Generate a value suitable for use in {@link android.view.View#setId(int)}. // * This value will not collide with ID values generated at build time by aapt for R.id. // * // * @return a generated ID value // */ // public static int generateViewId() { // for (;;) { // final int result = sNextGeneratedId.get(); // // aapt-generated IDs have the high byte nonzero; clamp to the range under that. // int newValue = result + 1; // if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. // if (sNextGeneratedId.compareAndSet(result, newValue)) { // return result; // } // } // } // } // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/WeeklyMenu.java import android.text.format.Time; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import java.io.Serializable; import java.util.List; import java.util.Map; import de.lukasniemeier.mensa.utils.SerializableTime; import de.lukasniemeier.mensa.utils.Utils; package de.lukasniemeier.mensa.model; /** * Created on 17.09.13. */ public class WeeklyMenu implements Serializable { private final Mensa mensa;
private SerializableTime timestamp;
lukasniemeier/mensaapp
MensaApp/src/main/java/de/lukasniemeier/mensa/model/WeeklyMenu.java
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/utils/SerializableTime.java // public class SerializableTime implements Comparable<SerializableTime>, Serializable { // // private static Time toTime(Date date) { // Time time = new Time(); // time.set(date.getTime()); // return time; // } // // private Time timestamp; // // public SerializableTime(Time timestamp) { // this.timestamp = timestamp; // } // // public SerializableTime(Date date) { // this(toTime(date)); // } // // public Time getTime() { // return timestamp; // } // // private void writeObject(java.io.ObjectOutputStream out) // throws IOException { // out.writeObject(timestamp.toMillis(false)); // } // // private void readObject(java.io.ObjectInputStream in) // throws IOException, ClassNotFoundException { // long ms = (Long) in.readObject(); // this.timestamp = new Time(); // this.timestamp.set(ms); // } // // public long toMillis() { // return timestamp.toMillis(false); // } // // public int getYearDay() { // return timestamp.yearDay; // } // // public int getYear() { // return timestamp.year; // } // // public Date toDate() { // return new Date(toMillis()); // } // // @Override // public int compareTo(SerializableTime other) { // return Time.compare(this.getTime(), other.getTime()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SerializableTime that = (SerializableTime) o; // return timestamp.toMillis(false) == that.timestamp.toMillis(false); // } // // @Override // public int hashCode() { // long ht = timestamp.toMillis(false); // return (int) ht ^ (int) (ht >> 32); // } // } // // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/utils/Utils.java // public class Utils { // // private static final DateFormat defaultMenuDateFormat = new SimpleDateFormat("c, d.MM"); // // public static String formatDate(Context context, SerializableTime time) { // return formatDate(context, time, defaultMenuDateFormat); // } // // public static String formatDate(Context context, SerializableTime time, DateFormat format) { // if (DateUtils.isToday(time.toMillis())) { // return context.getString(R.string.today); // } else if(DateUtils.isToday(time.toMillis() - 1000 * 60 * 60 * 24)) { // return context.getString(R.string.tomorrow); // } else { // return format.format(time.toDate()); // } // } // // public static SerializableTime today() { // Calendar today = Calendar.getInstance(); // today.set(Calendar.HOUR, 0); // today.set(Calendar.MINUTE, 0); // today.set(Calendar.SECOND, 0); // today.set(Calendar.MILLISECOND, 0); // return new SerializableTime(today.getTime()); // } // // public static SerializableTime now() { // Time now = new Time(); // now.setToNow(); // return new SerializableTime(now); // } // // public static void restartApp(Activity context) { // Intent i = context.getBaseContext().getPackageManager().getLaunchIntentForPackage(context.getBaseContext().getPackageName()); // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // context.startActivity(i); // } // // public static int dpToPx(Context context, int dp) { // float density = context.getResources().getDisplayMetrics().density; // return (int)(dp * density); // } // // private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); // // /** // * Generate a value suitable for use in {@link android.view.View#setId(int)}. // * This value will not collide with ID values generated at build time by aapt for R.id. // * // * @return a generated ID value // */ // public static int generateViewId() { // for (;;) { // final int result = sNextGeneratedId.get(); // // aapt-generated IDs have the high byte nonzero; clamp to the range under that. // int newValue = result + 1; // if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. // if (sNextGeneratedId.compareAndSet(result, newValue)) { // return result; // } // } // } // }
import android.text.format.Time; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import java.io.Serializable; import java.util.List; import java.util.Map; import de.lukasniemeier.mensa.utils.SerializableTime; import de.lukasniemeier.mensa.utils.Utils;
return timestamp.getTime(); } public BiMap<SerializableTime, Menu> getMenus() { return menuMap; } public void addMenu(SerializableTime date, Menu menu) { menuMap.put(date, menu); } public Menu getMenu(SerializableTime date) { return menuMap.get(date); } public boolean hasMenu(SerializableTime date) { return menuMap.keySet().contains(date); } public static WeeklyMenu merge(Mensa mensa, SerializableTime timestamp, List<WeeklyMenu> menus) { WeeklyMenu merged = new WeeklyMenu(mensa, timestamp); for (WeeklyMenu weeklyMenu : menus) { for (Map.Entry<SerializableTime, Menu> entry : weeklyMenu.menuMap.entrySet()) { merged.addMenu(entry.getKey(), entry.getValue()); } } return merged; } public boolean isOutdated() {
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/utils/SerializableTime.java // public class SerializableTime implements Comparable<SerializableTime>, Serializable { // // private static Time toTime(Date date) { // Time time = new Time(); // time.set(date.getTime()); // return time; // } // // private Time timestamp; // // public SerializableTime(Time timestamp) { // this.timestamp = timestamp; // } // // public SerializableTime(Date date) { // this(toTime(date)); // } // // public Time getTime() { // return timestamp; // } // // private void writeObject(java.io.ObjectOutputStream out) // throws IOException { // out.writeObject(timestamp.toMillis(false)); // } // // private void readObject(java.io.ObjectInputStream in) // throws IOException, ClassNotFoundException { // long ms = (Long) in.readObject(); // this.timestamp = new Time(); // this.timestamp.set(ms); // } // // public long toMillis() { // return timestamp.toMillis(false); // } // // public int getYearDay() { // return timestamp.yearDay; // } // // public int getYear() { // return timestamp.year; // } // // public Date toDate() { // return new Date(toMillis()); // } // // @Override // public int compareTo(SerializableTime other) { // return Time.compare(this.getTime(), other.getTime()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SerializableTime that = (SerializableTime) o; // return timestamp.toMillis(false) == that.timestamp.toMillis(false); // } // // @Override // public int hashCode() { // long ht = timestamp.toMillis(false); // return (int) ht ^ (int) (ht >> 32); // } // } // // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/utils/Utils.java // public class Utils { // // private static final DateFormat defaultMenuDateFormat = new SimpleDateFormat("c, d.MM"); // // public static String formatDate(Context context, SerializableTime time) { // return formatDate(context, time, defaultMenuDateFormat); // } // // public static String formatDate(Context context, SerializableTime time, DateFormat format) { // if (DateUtils.isToday(time.toMillis())) { // return context.getString(R.string.today); // } else if(DateUtils.isToday(time.toMillis() - 1000 * 60 * 60 * 24)) { // return context.getString(R.string.tomorrow); // } else { // return format.format(time.toDate()); // } // } // // public static SerializableTime today() { // Calendar today = Calendar.getInstance(); // today.set(Calendar.HOUR, 0); // today.set(Calendar.MINUTE, 0); // today.set(Calendar.SECOND, 0); // today.set(Calendar.MILLISECOND, 0); // return new SerializableTime(today.getTime()); // } // // public static SerializableTime now() { // Time now = new Time(); // now.setToNow(); // return new SerializableTime(now); // } // // public static void restartApp(Activity context) { // Intent i = context.getBaseContext().getPackageManager().getLaunchIntentForPackage(context.getBaseContext().getPackageName()); // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // context.startActivity(i); // } // // public static int dpToPx(Context context, int dp) { // float density = context.getResources().getDisplayMetrics().density; // return (int)(dp * density); // } // // private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); // // /** // * Generate a value suitable for use in {@link android.view.View#setId(int)}. // * This value will not collide with ID values generated at build time by aapt for R.id. // * // * @return a generated ID value // */ // public static int generateViewId() { // for (;;) { // final int result = sNextGeneratedId.get(); // // aapt-generated IDs have the high byte nonzero; clamp to the range under that. // int newValue = result + 1; // if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. // if (sNextGeneratedId.compareAndSet(result, newValue)) { // return result; // } // } // } // } // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/WeeklyMenu.java import android.text.format.Time; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import java.io.Serializable; import java.util.List; import java.util.Map; import de.lukasniemeier.mensa.utils.SerializableTime; import de.lukasniemeier.mensa.utils.Utils; return timestamp.getTime(); } public BiMap<SerializableTime, Menu> getMenus() { return menuMap; } public void addMenu(SerializableTime date, Menu menu) { menuMap.put(date, menu); } public Menu getMenu(SerializableTime date) { return menuMap.get(date); } public boolean hasMenu(SerializableTime date) { return menuMap.keySet().contains(date); } public static WeeklyMenu merge(Mensa mensa, SerializableTime timestamp, List<WeeklyMenu> menus) { WeeklyMenu merged = new WeeklyMenu(mensa, timestamp); for (WeeklyMenu weeklyMenu : menus) { for (Map.Entry<SerializableTime, Menu> entry : weeklyMenu.menuMap.entrySet()) { merged.addMenu(entry.getKey(), entry.getValue()); } } return merged; } public boolean isOutdated() {
SerializableTime now = Utils.now();
lukasniemeier/mensaapp
MensaApp/src/main/java/de/lukasniemeier/mensa/ui/adapter/NavigationAdapterErrorState.java
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ui/MenuViewErrorFragment.java // public class MenuViewErrorFragment extends MenuViewSpecialFragment { // // private static final String ARGS_MESSAGE = "errorMessageArgument"; // // public static MenuViewErrorFragment create(String errorMessage) { // MenuViewErrorFragment fragment = new MenuViewErrorFragment(); // fragment.setArguments(createArgumentBundle(errorMessage)); // return fragment; // } // // private static Bundle createArgumentBundle(String errorMessage) { // Bundle arguments = new Bundle(); // arguments.putString(ARGS_MESSAGE, errorMessage); // return arguments; // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_menu_error_view, container, false); // } // // @Override // public void onActivityCreated(Bundle savedInstanceState) { // super.onActivityCreated(savedInstanceState); // // Bundle arguments = getArguments(); // // Button button = (Button) getView().findViewById(R.id.fragment_menu_error_button); // button.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // listener.onRefreshRequested(); // } // }); // // TextView text = (TextView) getView().findViewById(R.id.fragment_menu_error_text); // if (arguments.containsKey(ARGS_MESSAGE)) { // text.setText(arguments.getString(ARGS_MESSAGE)); // } else { // text.setText(getString(R.string.menu_error_description)); // } // } // }
import android.app.ActionBar; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import de.lukasniemeier.mensa.ui.MenuViewErrorFragment;
package de.lukasniemeier.mensa.ui.adapter; /** * Created on 26.11.13. */ public class NavigationAdapterErrorState extends NavigationAdapterState { private final Fragment errorFragment; public NavigationAdapterErrorState(NavigationAdapter stateContext, Context context, String errorMessage) { super(stateContext, context);
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ui/MenuViewErrorFragment.java // public class MenuViewErrorFragment extends MenuViewSpecialFragment { // // private static final String ARGS_MESSAGE = "errorMessageArgument"; // // public static MenuViewErrorFragment create(String errorMessage) { // MenuViewErrorFragment fragment = new MenuViewErrorFragment(); // fragment.setArguments(createArgumentBundle(errorMessage)); // return fragment; // } // // private static Bundle createArgumentBundle(String errorMessage) { // Bundle arguments = new Bundle(); // arguments.putString(ARGS_MESSAGE, errorMessage); // return arguments; // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_menu_error_view, container, false); // } // // @Override // public void onActivityCreated(Bundle savedInstanceState) { // super.onActivityCreated(savedInstanceState); // // Bundle arguments = getArguments(); // // Button button = (Button) getView().findViewById(R.id.fragment_menu_error_button); // button.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // listener.onRefreshRequested(); // } // }); // // TextView text = (TextView) getView().findViewById(R.id.fragment_menu_error_text); // if (arguments.containsKey(ARGS_MESSAGE)) { // text.setText(arguments.getString(ARGS_MESSAGE)); // } else { // text.setText(getString(R.string.menu_error_description)); // } // } // } // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ui/adapter/NavigationAdapterErrorState.java import android.app.ActionBar; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import de.lukasniemeier.mensa.ui.MenuViewErrorFragment; package de.lukasniemeier.mensa.ui.adapter; /** * Created on 26.11.13. */ public class NavigationAdapterErrorState extends NavigationAdapterState { private final Fragment errorFragment; public NavigationAdapterErrorState(NavigationAdapter stateContext, Context context, String errorMessage) { super(stateContext, context);
this.errorFragment = MenuViewErrorFragment.create(errorMessage);
lukasniemeier/mensaapp
MensaApp/src/main/java/de/lukasniemeier/mensa/model/MealType.java
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/MensaApplication.java // public class MensaApplication extends Application implements ResourceService { // // private static ResourceService resourceService; // // public static ResourceService getResourceService() { // return resourceService; // } // // @Override // public void onCreate() { // super.onCreate(); // MensaApplication.resourceService = this; // } // // @Override // public String localizeString(int id) { // return getString(id); // } // // } // // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ResourceService.java // public interface ResourceService { // String localizeString(int id); // Resources getResources(); // }
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import de.lukasniemeier.mensa.MensaApplication; import de.lukasniemeier.mensa.R; import de.lukasniemeier.mensa.ResourceService;
package de.lukasniemeier.mensa.model; /** * Created on 18.09.13. */ public enum MealType { UNKNOWN(R.string.meal_type_unknown, R.drawable.unknown, ""), FISH(R.string.meal_type_fish, R.drawable.fish, "mit Fisch"), PORK(R.string.meal_type_pork, R.drawable.pork, "mit Schweinefleisch"), CHICKEN(R.string.meal_type_chicken, R.drawable.chicken, "mit Geflügelfleisch"), BEEF(R.string.meal_type_beef, R.drawable.beef, "mit Rindfleisch"), VEGAN(R.string.meal_type_vegan, R.drawable.vegan, "vegan"), OVOLACTOVEGETABIL(R.string.meal_type_ovolactovegetabil, R.drawable.lacto, "ovo-lacto-vegetabil"), MENSAVITAL(R.string.meal_type_mensavital, R.drawable.vital, "mensaVital"); private final String name; private final Bitmap icon; private final String parseString; private MealType(int nameId, int iconId, String displayName) {
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/MensaApplication.java // public class MensaApplication extends Application implements ResourceService { // // private static ResourceService resourceService; // // public static ResourceService getResourceService() { // return resourceService; // } // // @Override // public void onCreate() { // super.onCreate(); // MensaApplication.resourceService = this; // } // // @Override // public String localizeString(int id) { // return getString(id); // } // // } // // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ResourceService.java // public interface ResourceService { // String localizeString(int id); // Resources getResources(); // } // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/MealType.java import android.graphics.Bitmap; import android.graphics.BitmapFactory; import de.lukasniemeier.mensa.MensaApplication; import de.lukasniemeier.mensa.R; import de.lukasniemeier.mensa.ResourceService; package de.lukasniemeier.mensa.model; /** * Created on 18.09.13. */ public enum MealType { UNKNOWN(R.string.meal_type_unknown, R.drawable.unknown, ""), FISH(R.string.meal_type_fish, R.drawable.fish, "mit Fisch"), PORK(R.string.meal_type_pork, R.drawable.pork, "mit Schweinefleisch"), CHICKEN(R.string.meal_type_chicken, R.drawable.chicken, "mit Geflügelfleisch"), BEEF(R.string.meal_type_beef, R.drawable.beef, "mit Rindfleisch"), VEGAN(R.string.meal_type_vegan, R.drawable.vegan, "vegan"), OVOLACTOVEGETABIL(R.string.meal_type_ovolactovegetabil, R.drawable.lacto, "ovo-lacto-vegetabil"), MENSAVITAL(R.string.meal_type_mensavital, R.drawable.vital, "mensaVital"); private final String name; private final Bitmap icon; private final String parseString; private MealType(int nameId, int iconId, String displayName) {
ResourceService service = MensaApplication.getResourceService();
lukasniemeier/mensaapp
MensaApp/src/main/java/de/lukasniemeier/mensa/model/MealType.java
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/MensaApplication.java // public class MensaApplication extends Application implements ResourceService { // // private static ResourceService resourceService; // // public static ResourceService getResourceService() { // return resourceService; // } // // @Override // public void onCreate() { // super.onCreate(); // MensaApplication.resourceService = this; // } // // @Override // public String localizeString(int id) { // return getString(id); // } // // } // // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ResourceService.java // public interface ResourceService { // String localizeString(int id); // Resources getResources(); // }
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import de.lukasniemeier.mensa.MensaApplication; import de.lukasniemeier.mensa.R; import de.lukasniemeier.mensa.ResourceService;
package de.lukasniemeier.mensa.model; /** * Created on 18.09.13. */ public enum MealType { UNKNOWN(R.string.meal_type_unknown, R.drawable.unknown, ""), FISH(R.string.meal_type_fish, R.drawable.fish, "mit Fisch"), PORK(R.string.meal_type_pork, R.drawable.pork, "mit Schweinefleisch"), CHICKEN(R.string.meal_type_chicken, R.drawable.chicken, "mit Geflügelfleisch"), BEEF(R.string.meal_type_beef, R.drawable.beef, "mit Rindfleisch"), VEGAN(R.string.meal_type_vegan, R.drawable.vegan, "vegan"), OVOLACTOVEGETABIL(R.string.meal_type_ovolactovegetabil, R.drawable.lacto, "ovo-lacto-vegetabil"), MENSAVITAL(R.string.meal_type_mensavital, R.drawable.vital, "mensaVital"); private final String name; private final Bitmap icon; private final String parseString; private MealType(int nameId, int iconId, String displayName) {
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/MensaApplication.java // public class MensaApplication extends Application implements ResourceService { // // private static ResourceService resourceService; // // public static ResourceService getResourceService() { // return resourceService; // } // // @Override // public void onCreate() { // super.onCreate(); // MensaApplication.resourceService = this; // } // // @Override // public String localizeString(int id) { // return getString(id); // } // // } // // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ResourceService.java // public interface ResourceService { // String localizeString(int id); // Resources getResources(); // } // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/MealType.java import android.graphics.Bitmap; import android.graphics.BitmapFactory; import de.lukasniemeier.mensa.MensaApplication; import de.lukasniemeier.mensa.R; import de.lukasniemeier.mensa.ResourceService; package de.lukasniemeier.mensa.model; /** * Created on 18.09.13. */ public enum MealType { UNKNOWN(R.string.meal_type_unknown, R.drawable.unknown, ""), FISH(R.string.meal_type_fish, R.drawable.fish, "mit Fisch"), PORK(R.string.meal_type_pork, R.drawable.pork, "mit Schweinefleisch"), CHICKEN(R.string.meal_type_chicken, R.drawable.chicken, "mit Geflügelfleisch"), BEEF(R.string.meal_type_beef, R.drawable.beef, "mit Rindfleisch"), VEGAN(R.string.meal_type_vegan, R.drawable.vegan, "vegan"), OVOLACTOVEGETABIL(R.string.meal_type_ovolactovegetabil, R.drawable.lacto, "ovo-lacto-vegetabil"), MENSAVITAL(R.string.meal_type_mensavital, R.drawable.vital, "mensaVital"); private final String name; private final Bitmap icon; private final String parseString; private MealType(int nameId, int iconId, String displayName) {
ResourceService service = MensaApplication.getResourceService();
lukasniemeier/mensaapp
MensaApp/src/main/java/de/lukasniemeier/mensa/ui/BaseActivity.java
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ui/preference/GeneralPreferenceFragment.java // public class GeneralPreferenceFragment extends BasePreferenceFragment { // // public static Intent createIntent(Context context) { // Intent intent = new Intent(context, SettingsActivity.class); // intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, GeneralPreferenceFragment.class.getName()); // intent.putExtra(SettingsActivity.EXTRA_NO_HEADERS, true ); // return intent; // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // addPreferencesFromResource(R.xml.pref_general); // // ListPreference selectTheme = (ListPreference) findPreference("settings_list_theme"); // setupThemeList(selectTheme); // // CheckBoxPreference enableDefaultMensa = (CheckBoxPreference) findPreference("settings_check_mensa_default"); // ListPreference selectDefaultMensa = (ListPreference) findPreference("settings_list_mensa_default"); // setupMensaList(selectDefaultMensa); // // bindPreferenceSummaryToValue(selectTheme); // bindPreferenceToCheckbox(enableDefaultMensa, selectDefaultMensa); // bindPreferenceSummaryToValue(selectDefaultMensa); // } // // private void setupThemeList(ListPreference selectTheme) { // Collection<String> entries = Arrays.asList("Studi", "Girly"); // Collection<String> values = Arrays.asList(String.valueOf(R.style.Theme_Studi_Theme), // String.valueOf(R.style.Theme_Girly_Theme)); // selectTheme.setDefaultValue(String.valueOf(R.style.Theme_Studi_Theme)); // selectTheme.setEntries(entries.toArray(new String[entries.size()])); // selectTheme.setEntryValues(values.toArray(new String[values.size()])); // // selectTheme.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { // @Override // public boolean onPreferenceChange(Preference preference, Object o) { // Utils.restartApp(getActivity()); // return true; // } // }); // } // // private void setupMensaList(ListPreference selectDefault) { // Collection<Mensa> mensas = Mensa.getMensas(); // selectDefault.setDefaultValue(""); // Collection<String> entries = new ArrayList<String>(Collections2.transform(mensas, new Function<Mensa, String>() { // @Override // public String apply(Mensa mensa) { // return mensa.getName(); // } // })); // entries.add(getString(R.string.pref_none_select_mensa_default)); // Collection<String> values = new ArrayList<String>(Collections2.transform(mensas, new Function<Mensa, String>() { // @Override // public String apply(Mensa mensa) { // return mensa.getShortName(); // } // })); // values.add(""); // selectDefault.setEntries(entries.toArray(new String[entries.size()])); // selectDefault.setEntryValues(values.toArray(new String[values.size()])); // } // }
import android.app.DialogFragment; import android.view.Menu; import android.view.MenuItem; import de.lukasniemeier.mensa.R; import de.lukasniemeier.mensa.ui.preference.GeneralPreferenceFragment;
package de.lukasniemeier.mensa.ui; /** * Created on 21.11.13. */ public abstract class BaseActivity extends ThemedActivity { public static final String ABOUT_DIALOG_TAG = "AboutDialog"; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.mensa, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings:
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ui/preference/GeneralPreferenceFragment.java // public class GeneralPreferenceFragment extends BasePreferenceFragment { // // public static Intent createIntent(Context context) { // Intent intent = new Intent(context, SettingsActivity.class); // intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, GeneralPreferenceFragment.class.getName()); // intent.putExtra(SettingsActivity.EXTRA_NO_HEADERS, true ); // return intent; // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // addPreferencesFromResource(R.xml.pref_general); // // ListPreference selectTheme = (ListPreference) findPreference("settings_list_theme"); // setupThemeList(selectTheme); // // CheckBoxPreference enableDefaultMensa = (CheckBoxPreference) findPreference("settings_check_mensa_default"); // ListPreference selectDefaultMensa = (ListPreference) findPreference("settings_list_mensa_default"); // setupMensaList(selectDefaultMensa); // // bindPreferenceSummaryToValue(selectTheme); // bindPreferenceToCheckbox(enableDefaultMensa, selectDefaultMensa); // bindPreferenceSummaryToValue(selectDefaultMensa); // } // // private void setupThemeList(ListPreference selectTheme) { // Collection<String> entries = Arrays.asList("Studi", "Girly"); // Collection<String> values = Arrays.asList(String.valueOf(R.style.Theme_Studi_Theme), // String.valueOf(R.style.Theme_Girly_Theme)); // selectTheme.setDefaultValue(String.valueOf(R.style.Theme_Studi_Theme)); // selectTheme.setEntries(entries.toArray(new String[entries.size()])); // selectTheme.setEntryValues(values.toArray(new String[values.size()])); // // selectTheme.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { // @Override // public boolean onPreferenceChange(Preference preference, Object o) { // Utils.restartApp(getActivity()); // return true; // } // }); // } // // private void setupMensaList(ListPreference selectDefault) { // Collection<Mensa> mensas = Mensa.getMensas(); // selectDefault.setDefaultValue(""); // Collection<String> entries = new ArrayList<String>(Collections2.transform(mensas, new Function<Mensa, String>() { // @Override // public String apply(Mensa mensa) { // return mensa.getName(); // } // })); // entries.add(getString(R.string.pref_none_select_mensa_default)); // Collection<String> values = new ArrayList<String>(Collections2.transform(mensas, new Function<Mensa, String>() { // @Override // public String apply(Mensa mensa) { // return mensa.getShortName(); // } // })); // values.add(""); // selectDefault.setEntries(entries.toArray(new String[entries.size()])); // selectDefault.setEntryValues(values.toArray(new String[values.size()])); // } // } // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ui/BaseActivity.java import android.app.DialogFragment; import android.view.Menu; import android.view.MenuItem; import de.lukasniemeier.mensa.R; import de.lukasniemeier.mensa.ui.preference.GeneralPreferenceFragment; package de.lukasniemeier.mensa.ui; /** * Created on 21.11.13. */ public abstract class BaseActivity extends ThemedActivity { public static final String ABOUT_DIALOG_TAG = "AboutDialog"; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.mensa, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings:
startActivity(GeneralPreferenceFragment.createIntent(this));
lukasniemeier/mensaapp
MensaApp/src/main/java/de/lukasniemeier/mensa/model/Mensa.java
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/utils/Utils.java // public class Utils { // // private static final DateFormat defaultMenuDateFormat = new SimpleDateFormat("c, d.MM"); // // public static String formatDate(Context context, SerializableTime time) { // return formatDate(context, time, defaultMenuDateFormat); // } // // public static String formatDate(Context context, SerializableTime time, DateFormat format) { // if (DateUtils.isToday(time.toMillis())) { // return context.getString(R.string.today); // } else if(DateUtils.isToday(time.toMillis() - 1000 * 60 * 60 * 24)) { // return context.getString(R.string.tomorrow); // } else { // return format.format(time.toDate()); // } // } // // public static SerializableTime today() { // Calendar today = Calendar.getInstance(); // today.set(Calendar.HOUR, 0); // today.set(Calendar.MINUTE, 0); // today.set(Calendar.SECOND, 0); // today.set(Calendar.MILLISECOND, 0); // return new SerializableTime(today.getTime()); // } // // public static SerializableTime now() { // Time now = new Time(); // now.setToNow(); // return new SerializableTime(now); // } // // public static void restartApp(Activity context) { // Intent i = context.getBaseContext().getPackageManager().getLaunchIntentForPackage(context.getBaseContext().getPackageName()); // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // context.startActivity(i); // } // // public static int dpToPx(Context context, int dp) { // float density = context.getResources().getDisplayMetrics().density; // return (int)(dp * density); // } // // private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); // // /** // * Generate a value suitable for use in {@link android.view.View#setId(int)}. // * This value will not collide with ID values generated at build time by aapt for R.id. // * // * @return a generated ID value // */ // public static int generateViewId() { // for (;;) { // final int result = sNextGeneratedId.get(); // // aapt-generated IDs have the high byte nonzero; clamp to the range under that. // int newValue = result + 1; // if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. // if (sNextGeneratedId.compareAndSet(result, newValue)) { // return result; // } // } // } // }
import android.text.format.Time; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import java.io.ObjectStreamException; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.List; import de.lukasniemeier.mensa.utils.Utils;
private final String openingTimes; private final String openingTimesOffSeason; private final URL detailMenuURL; public Mensa(String name, String address, String openingTimes, String openingTimesOffSeason, URL detailMenuURL) { this(name, name, address, openingTimes, openingTimesOffSeason, detailMenuURL); } public Mensa(String name, String shortName, String address, String openingTimes, String openingTimesOffSeason, URL detailMenuURL) { this.name = name; this.shortName = shortName; this.address = address; this.openingTimes = openingTimes; this.openingTimesOffSeason = openingTimesOffSeason; this.detailMenuURL = detailMenuURL; } public String getName() { return name; } public String getShortName() { return shortName; } public String getAddress() { return address; } public String getOpeningTimes() {
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/utils/Utils.java // public class Utils { // // private static final DateFormat defaultMenuDateFormat = new SimpleDateFormat("c, d.MM"); // // public static String formatDate(Context context, SerializableTime time) { // return formatDate(context, time, defaultMenuDateFormat); // } // // public static String formatDate(Context context, SerializableTime time, DateFormat format) { // if (DateUtils.isToday(time.toMillis())) { // return context.getString(R.string.today); // } else if(DateUtils.isToday(time.toMillis() - 1000 * 60 * 60 * 24)) { // return context.getString(R.string.tomorrow); // } else { // return format.format(time.toDate()); // } // } // // public static SerializableTime today() { // Calendar today = Calendar.getInstance(); // today.set(Calendar.HOUR, 0); // today.set(Calendar.MINUTE, 0); // today.set(Calendar.SECOND, 0); // today.set(Calendar.MILLISECOND, 0); // return new SerializableTime(today.getTime()); // } // // public static SerializableTime now() { // Time now = new Time(); // now.setToNow(); // return new SerializableTime(now); // } // // public static void restartApp(Activity context) { // Intent i = context.getBaseContext().getPackageManager().getLaunchIntentForPackage(context.getBaseContext().getPackageName()); // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // context.startActivity(i); // } // // public static int dpToPx(Context context, int dp) { // float density = context.getResources().getDisplayMetrics().density; // return (int)(dp * density); // } // // private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); // // /** // * Generate a value suitable for use in {@link android.view.View#setId(int)}. // * This value will not collide with ID values generated at build time by aapt for R.id. // * // * @return a generated ID value // */ // public static int generateViewId() { // for (;;) { // final int result = sNextGeneratedId.get(); // // aapt-generated IDs have the high byte nonzero; clamp to the range under that. // int newValue = result + 1; // if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. // if (sNextGeneratedId.compareAndSet(result, newValue)) { // return result; // } // } // } // } // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/Mensa.java import android.text.format.Time; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import java.io.ObjectStreamException; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.List; import de.lukasniemeier.mensa.utils.Utils; private final String openingTimes; private final String openingTimesOffSeason; private final URL detailMenuURL; public Mensa(String name, String address, String openingTimes, String openingTimesOffSeason, URL detailMenuURL) { this(name, name, address, openingTimes, openingTimesOffSeason, detailMenuURL); } public Mensa(String name, String shortName, String address, String openingTimes, String openingTimesOffSeason, URL detailMenuURL) { this.name = name; this.shortName = shortName; this.address = address; this.openingTimes = openingTimes; this.openingTimesOffSeason = openingTimesOffSeason; this.detailMenuURL = detailMenuURL; } public String getName() { return name; } public String getShortName() { return shortName; } public String getAddress() { return address; } public String getOpeningTimes() {
Time now = Utils.now().getTime();
lukasniemeier/mensaapp
MensaApp/src/main/java/de/lukasniemeier/mensa/ui/adapter/MealAdapterMealTypeFilter.java
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/Meal.java // public class Meal implements Serializable { // // private final Menu menu; // private final String name; // private final String description; // private final Collection<MealType> types; // private final Collection<String> additives; // private final String price; // // public Meal(Menu menu, String name, String description, Collection<MealType> types, // Collection<String> additives, String price) { // this.menu = menu; // this.name = name; // this.description = description; // this.types = types; // this.additives = additives; // this.price = price; // } // // public Menu getMenu() { // return menu; // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public Collection<MealType> getTypes() { // return types; // } // // public Collection<String> getAdditives() { // return additives; // } // // public String getPrice() { // return price; // } // // @Override // public String toString() { // return "Meal{" + // "name='" + name + '\'' + // ", description='" + description + '\'' + // ", types='" + types + '\'' + // ", additives='" + additives + '\'' + // ", price='" + price + '\'' + // '}'; // } // } // // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/MealType.java // public enum MealType { // UNKNOWN(R.string.meal_type_unknown, R.drawable.unknown, ""), // FISH(R.string.meal_type_fish, R.drawable.fish, "mit Fisch"), // PORK(R.string.meal_type_pork, R.drawable.pork, "mit Schweinefleisch"), // CHICKEN(R.string.meal_type_chicken, R.drawable.chicken, "mit Geflügelfleisch"), // BEEF(R.string.meal_type_beef, R.drawable.beef, "mit Rindfleisch"), // VEGAN(R.string.meal_type_vegan, R.drawable.vegan, "vegan"), // OVOLACTOVEGETABIL(R.string.meal_type_ovolactovegetabil, R.drawable.lacto, "ovo-lacto-vegetabil"), // MENSAVITAL(R.string.meal_type_mensavital, R.drawable.vital, "mensaVital"); // // private final String name; // private final Bitmap icon; // private final String parseString; // // private MealType(int nameId, int iconId, String displayName) { // ResourceService service = MensaApplication.getResourceService(); // this.name = service.localizeString(nameId); // this.icon = BitmapFactory.decodeResource(service.getResources(), iconId); // this.parseString = displayName; // } // // public String getParseString() { // return parseString; // } // // public String getName() { // return name; // } // // public Bitmap getIcon() { // return icon; // } // // @Override // public String toString() { // return getName(); // } // }
import android.text.TextUtils; import android.widget.Filter; import android.widget.TextView; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import de.lukasniemeier.mensa.model.Meal; import de.lukasniemeier.mensa.model.MealType;
package de.lukasniemeier.mensa.ui.adapter; /** * Created on 27.11.13. */ public class MealAdapterMealTypeFilter extends Filter { private final MealAdapter adapter; private final TextView informationView;
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/Meal.java // public class Meal implements Serializable { // // private final Menu menu; // private final String name; // private final String description; // private final Collection<MealType> types; // private final Collection<String> additives; // private final String price; // // public Meal(Menu menu, String name, String description, Collection<MealType> types, // Collection<String> additives, String price) { // this.menu = menu; // this.name = name; // this.description = description; // this.types = types; // this.additives = additives; // this.price = price; // } // // public Menu getMenu() { // return menu; // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public Collection<MealType> getTypes() { // return types; // } // // public Collection<String> getAdditives() { // return additives; // } // // public String getPrice() { // return price; // } // // @Override // public String toString() { // return "Meal{" + // "name='" + name + '\'' + // ", description='" + description + '\'' + // ", types='" + types + '\'' + // ", additives='" + additives + '\'' + // ", price='" + price + '\'' + // '}'; // } // } // // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/MealType.java // public enum MealType { // UNKNOWN(R.string.meal_type_unknown, R.drawable.unknown, ""), // FISH(R.string.meal_type_fish, R.drawable.fish, "mit Fisch"), // PORK(R.string.meal_type_pork, R.drawable.pork, "mit Schweinefleisch"), // CHICKEN(R.string.meal_type_chicken, R.drawable.chicken, "mit Geflügelfleisch"), // BEEF(R.string.meal_type_beef, R.drawable.beef, "mit Rindfleisch"), // VEGAN(R.string.meal_type_vegan, R.drawable.vegan, "vegan"), // OVOLACTOVEGETABIL(R.string.meal_type_ovolactovegetabil, R.drawable.lacto, "ovo-lacto-vegetabil"), // MENSAVITAL(R.string.meal_type_mensavital, R.drawable.vital, "mensaVital"); // // private final String name; // private final Bitmap icon; // private final String parseString; // // private MealType(int nameId, int iconId, String displayName) { // ResourceService service = MensaApplication.getResourceService(); // this.name = service.localizeString(nameId); // this.icon = BitmapFactory.decodeResource(service.getResources(), iconId); // this.parseString = displayName; // } // // public String getParseString() { // return parseString; // } // // public String getName() { // return name; // } // // public Bitmap getIcon() { // return icon; // } // // @Override // public String toString() { // return getName(); // } // } // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ui/adapter/MealAdapterMealTypeFilter.java import android.text.TextUtils; import android.widget.Filter; import android.widget.TextView; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import de.lukasniemeier.mensa.model.Meal; import de.lukasniemeier.mensa.model.MealType; package de.lukasniemeier.mensa.ui.adapter; /** * Created on 27.11.13. */ public class MealAdapterMealTypeFilter extends Filter { private final MealAdapter adapter; private final TextView informationView;
private EnumSet<MealType> filterQuery = EnumSet.allOf(MealType.class);
lukasniemeier/mensaapp
MensaApp/src/main/java/de/lukasniemeier/mensa/ui/adapter/MealAdapterMealTypeFilter.java
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/Meal.java // public class Meal implements Serializable { // // private final Menu menu; // private final String name; // private final String description; // private final Collection<MealType> types; // private final Collection<String> additives; // private final String price; // // public Meal(Menu menu, String name, String description, Collection<MealType> types, // Collection<String> additives, String price) { // this.menu = menu; // this.name = name; // this.description = description; // this.types = types; // this.additives = additives; // this.price = price; // } // // public Menu getMenu() { // return menu; // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public Collection<MealType> getTypes() { // return types; // } // // public Collection<String> getAdditives() { // return additives; // } // // public String getPrice() { // return price; // } // // @Override // public String toString() { // return "Meal{" + // "name='" + name + '\'' + // ", description='" + description + '\'' + // ", types='" + types + '\'' + // ", additives='" + additives + '\'' + // ", price='" + price + '\'' + // '}'; // } // } // // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/MealType.java // public enum MealType { // UNKNOWN(R.string.meal_type_unknown, R.drawable.unknown, ""), // FISH(R.string.meal_type_fish, R.drawable.fish, "mit Fisch"), // PORK(R.string.meal_type_pork, R.drawable.pork, "mit Schweinefleisch"), // CHICKEN(R.string.meal_type_chicken, R.drawable.chicken, "mit Geflügelfleisch"), // BEEF(R.string.meal_type_beef, R.drawable.beef, "mit Rindfleisch"), // VEGAN(R.string.meal_type_vegan, R.drawable.vegan, "vegan"), // OVOLACTOVEGETABIL(R.string.meal_type_ovolactovegetabil, R.drawable.lacto, "ovo-lacto-vegetabil"), // MENSAVITAL(R.string.meal_type_mensavital, R.drawable.vital, "mensaVital"); // // private final String name; // private final Bitmap icon; // private final String parseString; // // private MealType(int nameId, int iconId, String displayName) { // ResourceService service = MensaApplication.getResourceService(); // this.name = service.localizeString(nameId); // this.icon = BitmapFactory.decodeResource(service.getResources(), iconId); // this.parseString = displayName; // } // // public String getParseString() { // return parseString; // } // // public String getName() { // return name; // } // // public Bitmap getIcon() { // return icon; // } // // @Override // public String toString() { // return getName(); // } // }
import android.text.TextUtils; import android.widget.Filter; import android.widget.TextView; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import de.lukasniemeier.mensa.model.Meal; import de.lukasniemeier.mensa.model.MealType;
package de.lukasniemeier.mensa.ui.adapter; /** * Created on 27.11.13. */ public class MealAdapterMealTypeFilter extends Filter { private final MealAdapter adapter; private final TextView informationView; private EnumSet<MealType> filterQuery = EnumSet.allOf(MealType.class); public MealAdapterMealTypeFilter(MealAdapter adapter, TextView informationView) { this.adapter = adapter; this.informationView = informationView; } public void filter(EnumSet<MealType> mealTypes) { filterQuery = mealTypes; filter(""); } public void filter() { filter(filterQuery); } @Override protected FilterResults performFiltering(CharSequence charSequence) { FilterResults results = new FilterResults();
// Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/Meal.java // public class Meal implements Serializable { // // private final Menu menu; // private final String name; // private final String description; // private final Collection<MealType> types; // private final Collection<String> additives; // private final String price; // // public Meal(Menu menu, String name, String description, Collection<MealType> types, // Collection<String> additives, String price) { // this.menu = menu; // this.name = name; // this.description = description; // this.types = types; // this.additives = additives; // this.price = price; // } // // public Menu getMenu() { // return menu; // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public Collection<MealType> getTypes() { // return types; // } // // public Collection<String> getAdditives() { // return additives; // } // // public String getPrice() { // return price; // } // // @Override // public String toString() { // return "Meal{" + // "name='" + name + '\'' + // ", description='" + description + '\'' + // ", types='" + types + '\'' + // ", additives='" + additives + '\'' + // ", price='" + price + '\'' + // '}'; // } // } // // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/model/MealType.java // public enum MealType { // UNKNOWN(R.string.meal_type_unknown, R.drawable.unknown, ""), // FISH(R.string.meal_type_fish, R.drawable.fish, "mit Fisch"), // PORK(R.string.meal_type_pork, R.drawable.pork, "mit Schweinefleisch"), // CHICKEN(R.string.meal_type_chicken, R.drawable.chicken, "mit Geflügelfleisch"), // BEEF(R.string.meal_type_beef, R.drawable.beef, "mit Rindfleisch"), // VEGAN(R.string.meal_type_vegan, R.drawable.vegan, "vegan"), // OVOLACTOVEGETABIL(R.string.meal_type_ovolactovegetabil, R.drawable.lacto, "ovo-lacto-vegetabil"), // MENSAVITAL(R.string.meal_type_mensavital, R.drawable.vital, "mensaVital"); // // private final String name; // private final Bitmap icon; // private final String parseString; // // private MealType(int nameId, int iconId, String displayName) { // ResourceService service = MensaApplication.getResourceService(); // this.name = service.localizeString(nameId); // this.icon = BitmapFactory.decodeResource(service.getResources(), iconId); // this.parseString = displayName; // } // // public String getParseString() { // return parseString; // } // // public String getName() { // return name; // } // // public Bitmap getIcon() { // return icon; // } // // @Override // public String toString() { // return getName(); // } // } // Path: MensaApp/src/main/java/de/lukasniemeier/mensa/ui/adapter/MealAdapterMealTypeFilter.java import android.text.TextUtils; import android.widget.Filter; import android.widget.TextView; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import de.lukasniemeier.mensa.model.Meal; import de.lukasniemeier.mensa.model.MealType; package de.lukasniemeier.mensa.ui.adapter; /** * Created on 27.11.13. */ public class MealAdapterMealTypeFilter extends Filter { private final MealAdapter adapter; private final TextView informationView; private EnumSet<MealType> filterQuery = EnumSet.allOf(MealType.class); public MealAdapterMealTypeFilter(MealAdapter adapter, TextView informationView) { this.adapter = adapter; this.informationView = informationView; } public void filter(EnumSet<MealType> mealTypes) { filterQuery = mealTypes; filter(""); } public void filter() { filter(filterQuery); } @Override protected FilterResults performFiltering(CharSequence charSequence) { FilterResults results = new FilterResults();
List<CardState<Meal>> allItems = adapter.getAllItems();