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
lucas-dolsan/tcc-rpg
TCC/src/ClienteVoIP/MicThread.java
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // }
import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.zip.GZIPOutputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.TargetDataLine;
package ClienteVoIP; public class MicThread extends Thread { public static double amplification = 1.0; private ObjectOutputStream toServer; private TargetDataLine mic; public MicThread(ObjectOutputStream toServer) throws LineUnavailableException { this.toServer = toServer; //open microphone line, an exception is thrown in case of error AudioFormat af = SoundPacket.defaultFormat; DataLine.Info info = new DataLine.Info(TargetDataLine.class, null); mic = (TargetDataLine) (AudioSystem.getLine(info)); mic.open(af); mic.start(); } @Override public void run() { for (;;) { if (mic.available() >= SoundPacket.defaultDataLenght) { //we got enough data to send byte[] buff = new byte[SoundPacket.defaultDataLenght]; while (mic.available() >= SoundPacket.defaultDataLenght) { //flush old data from mic to reduce lag, and read most recent data mic.read(buff, 0, buff.length); //read from microphone } try { //this part is used to decide whether to send or not the packet. if volume is too low, an empty packet will be sent and the remote client will play some comfort noise long tot = 0; for (int i = 0; i < buff.length; i++) { buff[i] *= amplification; tot += Math.abs(buff[i]); } tot *= 2.5; tot /= buff.length; //create and send packet
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // } // Path: TCC/src/ClienteVoIP/MicThread.java import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.zip.GZIPOutputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.TargetDataLine; package ClienteVoIP; public class MicThread extends Thread { public static double amplification = 1.0; private ObjectOutputStream toServer; private TargetDataLine mic; public MicThread(ObjectOutputStream toServer) throws LineUnavailableException { this.toServer = toServer; //open microphone line, an exception is thrown in case of error AudioFormat af = SoundPacket.defaultFormat; DataLine.Info info = new DataLine.Info(TargetDataLine.class, null); mic = (TargetDataLine) (AudioSystem.getLine(info)); mic.open(af); mic.start(); } @Override public void run() { for (;;) { if (mic.available() >= SoundPacket.defaultDataLenght) { //we got enough data to send byte[] buff = new byte[SoundPacket.defaultDataLenght]; while (mic.available() >= SoundPacket.defaultDataLenght) { //flush old data from mic to reduce lag, and read most recent data mic.read(buff, 0, buff.length); //read from microphone } try { //this part is used to decide whether to send or not the packet. if volume is too low, an empty packet will be sent and the remote client will play some comfort noise long tot = 0; for (int i = 0; i < buff.length; i++) { buff[i] *= amplification; tot += Math.abs(buff[i]); } tot *= 2.5; tot /= buff.length; //create and send packet
Message m = null;
lucas-dolsan/tcc-rpg
TCC/src/ClienteVoIP/MicThread.java
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // }
import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.zip.GZIPOutputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.TargetDataLine;
} try { //this part is used to decide whether to send or not the packet. if volume is too low, an empty packet will be sent and the remote client will play some comfort noise long tot = 0; for (int i = 0; i < buff.length; i++) { buff[i] *= amplification; tot += Math.abs(buff[i]); } tot *= 2.5; tot /= buff.length; //create and send packet Message m = null; if (tot == 0) {//send empty packet m = new Message(-1, -1, new SoundPacket(null)); } else { //send data //compress the sound packet with GZIP ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream go = new GZIPOutputStream(baos); go.write(buff); go.flush(); go.close(); baos.flush(); baos.close(); m = new Message(-1, -1, new SoundPacket(baos.toByteArray())); //create message for server, will generate chId and timestamp from this computer's IP and this socket's port } toServer.writeObject(m); //send message } catch (IOException ex) { //connection error stop(); } } else {
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // } // Path: TCC/src/ClienteVoIP/MicThread.java import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.zip.GZIPOutputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.TargetDataLine; } try { //this part is used to decide whether to send or not the packet. if volume is too low, an empty packet will be sent and the remote client will play some comfort noise long tot = 0; for (int i = 0; i < buff.length; i++) { buff[i] *= amplification; tot += Math.abs(buff[i]); } tot *= 2.5; tot /= buff.length; //create and send packet Message m = null; if (tot == 0) {//send empty packet m = new Message(-1, -1, new SoundPacket(null)); } else { //send data //compress the sound packet with GZIP ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream go = new GZIPOutputStream(baos); go.write(buff); go.flush(); go.close(); baos.flush(); baos.close(); m = new Message(-1, -1, new SoundPacket(baos.toByteArray())); //create message for server, will generate chId and timestamp from this computer's IP and this socket's port } toServer.writeObject(m); //send message } catch (IOException ex) { //connection error stop(); } } else {
Utils.sleep(10); //sleep to avoid busy wait
lucas-dolsan/tcc-rpg
TCC/src/ConexaoBanco/DAO.java
// Path: TCC/src/Telas/TelaJogo.java // public static ImageIcon imagemIcone = null;
import Objetos.*; import Telas.*; import static Telas.TelaJogo.imagemIcone; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.*; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.table.DefaultTableModel;
} public boolean verificarImagemNPCExiste() { String sqlExists = ("SELECT pk_imagemNPC FROM imagemNPC WHERE fk_personagem = ?"); int pkPersonagem = this.pegarPk_personagem(nomePersonagem); try { PreparedStatement stmtE = c.prepareStatement(sqlExists); stmtE.setInt(1, pkPersonagem); ResultSet rs = stmtE.executeQuery(); if (rs.next()) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; } public void pegarDadosMon(String nomeMon) { DAO.nomePersonagem = nomeMon; final String sql = ("SELECT * FROM personagem WHERE nomePersonagem_fic = ?"); try { PreparedStatement stmt = c.prepareStatement(sql); stmt.setString(1, nomeMon); ResultSet rs = stmt.executeQuery(); if (rs.next()) { TelaMonstro telaMonstro = new TelaMonstro(null, true); if (verificarImagemMonExiste()) { try { BufferedImage imagem = ImageIO.read(this.downloadImagemMon().getBinaryStream());
// Path: TCC/src/Telas/TelaJogo.java // public static ImageIcon imagemIcone = null; // Path: TCC/src/ConexaoBanco/DAO.java import Objetos.*; import Telas.*; import static Telas.TelaJogo.imagemIcone; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.*; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.table.DefaultTableModel; } public boolean verificarImagemNPCExiste() { String sqlExists = ("SELECT pk_imagemNPC FROM imagemNPC WHERE fk_personagem = ?"); int pkPersonagem = this.pegarPk_personagem(nomePersonagem); try { PreparedStatement stmtE = c.prepareStatement(sqlExists); stmtE.setInt(1, pkPersonagem); ResultSet rs = stmtE.executeQuery(); if (rs.next()) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; } public void pegarDadosMon(String nomeMon) { DAO.nomePersonagem = nomeMon; final String sql = ("SELECT * FROM personagem WHERE nomePersonagem_fic = ?"); try { PreparedStatement stmt = c.prepareStatement(sql); stmt.setString(1, nomeMon); ResultSet rs = stmt.executeQuery(); if (rs.next()) { TelaMonstro telaMonstro = new TelaMonstro(null, true); if (verificarImagemMonExiste()) { try { BufferedImage imagem = ImageIO.read(this.downloadImagemMon().getBinaryStream());
imagemIcone = new ImageIcon(imagem);
lucas-dolsan/tcc-rpg
TCC/src/ServidorVoIP/ClientConnection.java
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // }
import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList;
package ServidorVoIP; public class ClientConnection extends Thread { private Server serv; //instance of server, needed to put messages in the server's broadcast queue private Socket s; //connection to client private ObjectInputStream in; //object streams to/from client private ObjectOutputStream out; private long chId; //unique id of this client, generated in the costructor
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // } // Path: TCC/src/ServidorVoIP/ClientConnection.java import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList; package ServidorVoIP; public class ClientConnection extends Thread { private Server serv; //instance of server, needed to put messages in the server's broadcast queue private Socket s; //connection to client private ObjectInputStream in; //object streams to/from client private ObjectOutputStream out; private long chId; //unique id of this client, generated in the costructor
private ArrayList<Message> toSend = new ArrayList<Message>(); //queue of messages to be sent to the client
lucas-dolsan/tcc-rpg
TCC/src/ServidorVoIP/ClientConnection.java
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // }
import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList;
} @Override public void run() { try { out = new ObjectOutputStream(s.getOutputStream()); //create object streams to/from client in = new ObjectInputStream(s.getInputStream()); } catch (IOException ex) { //connection error, close connection try { s.close(); Log.add("ERROR " + getInetAddress() + ":" + getPort() + " " + ex); } catch (IOException ex1) { } stop(); } for (;;) { try { if (s.getInputStream().available() > 0) { //we got something from the client Message toBroadcast = (Message) in.readObject(); //read data from client if (toBroadcast.getChId() == -1) { //set its chId and timestamp and pass it to the server toBroadcast.setChId(chId); toBroadcast.setTimestamp(System.nanoTime() / 1000000L); serv.addTofilaDeTransmissao(toBroadcast); } else { continue; //invalid message } } try { if (!toSend.isEmpty()) { Message toClient = toSend.get(0); //we got something to send to the client
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // } // Path: TCC/src/ServidorVoIP/ClientConnection.java import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList; } @Override public void run() { try { out = new ObjectOutputStream(s.getOutputStream()); //create object streams to/from client in = new ObjectInputStream(s.getInputStream()); } catch (IOException ex) { //connection error, close connection try { s.close(); Log.add("ERROR " + getInetAddress() + ":" + getPort() + " " + ex); } catch (IOException ex1) { } stop(); } for (;;) { try { if (s.getInputStream().available() > 0) { //we got something from the client Message toBroadcast = (Message) in.readObject(); //read data from client if (toBroadcast.getChId() == -1) { //set its chId and timestamp and pass it to the server toBroadcast.setChId(chId); toBroadcast.setTimestamp(System.nanoTime() / 1000000L); serv.addTofilaDeTransmissao(toBroadcast); } else { continue; //invalid message } } try { if (!toSend.isEmpty()) { Message toClient = toSend.get(0); //we got something to send to the client
if (!(toClient.getData() instanceof SoundPacket) || toClient.getTimestamp() + toClient.getTtl() < System.nanoTime() / 1000000L) { //is the message too old or of an unknown type?
lucas-dolsan/tcc-rpg
TCC/src/ServidorVoIP/ClientConnection.java
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // }
import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList;
} catch (IOException ex) { //connection error, close connection try { s.close(); Log.add("ERROR " + getInetAddress() + ":" + getPort() + " " + ex); } catch (IOException ex1) { } stop(); } for (;;) { try { if (s.getInputStream().available() > 0) { //we got something from the client Message toBroadcast = (Message) in.readObject(); //read data from client if (toBroadcast.getChId() == -1) { //set its chId and timestamp and pass it to the server toBroadcast.setChId(chId); toBroadcast.setTimestamp(System.nanoTime() / 1000000L); serv.addTofilaDeTransmissao(toBroadcast); } else { continue; //invalid message } } try { if (!toSend.isEmpty()) { Message toClient = toSend.get(0); //we got something to send to the client if (!(toClient.getData() instanceof SoundPacket) || toClient.getTimestamp() + toClient.getTtl() < System.nanoTime() / 1000000L) { //is the message too old or of an unknown type? Log.add("dropping packet from " + toClient.getChId() + " to " + chId); continue; } out.writeObject(toClient); //send the message toSend.remove(toClient); //and remove it from the queue } else {
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // } // Path: TCC/src/ServidorVoIP/ClientConnection.java import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList; } catch (IOException ex) { //connection error, close connection try { s.close(); Log.add("ERROR " + getInetAddress() + ":" + getPort() + " " + ex); } catch (IOException ex1) { } stop(); } for (;;) { try { if (s.getInputStream().available() > 0) { //we got something from the client Message toBroadcast = (Message) in.readObject(); //read data from client if (toBroadcast.getChId() == -1) { //set its chId and timestamp and pass it to the server toBroadcast.setChId(chId); toBroadcast.setTimestamp(System.nanoTime() / 1000000L); serv.addTofilaDeTransmissao(toBroadcast); } else { continue; //invalid message } } try { if (!toSend.isEmpty()) { Message toClient = toSend.get(0); //we got something to send to the client if (!(toClient.getData() instanceof SoundPacket) || toClient.getTimestamp() + toClient.getTtl() < System.nanoTime() / 1000000L) { //is the message too old or of an unknown type? Log.add("dropping packet from " + toClient.getChId() + " to " + chId); continue; } out.writeObject(toClient); //send the message toSend.remove(toClient); //and remove it from the queue } else {
Utils.sleep(10); //avoid busy wait
lucas-dolsan/tcc-rpg
TCC/src/ClienteVoIP/Client.java
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // }
import Dependencias.Message; import Dependencias.Utils; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList;
package ClienteVoIP; public class Client extends Thread { private Socket s; private ArrayList<AudioChannel> chs = new ArrayList<AudioChannel>(); private MicThread st; public Client(String serverIp, int serverPort) throws UnknownHostException, IOException { s = new Socket(serverIp, serverPort); } @Override public void run() { try { ObjectInputStream fromServer = new ObjectInputStream(s.getInputStream()); //create object streams with the server ObjectOutputStream toServer = new ObjectOutputStream(s.getOutputStream()); try {
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // } // Path: TCC/src/ClienteVoIP/Client.java import Dependencias.Message; import Dependencias.Utils; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; package ClienteVoIP; public class Client extends Thread { private Socket s; private ArrayList<AudioChannel> chs = new ArrayList<AudioChannel>(); private MicThread st; public Client(String serverIp, int serverPort) throws UnknownHostException, IOException { s = new Socket(serverIp, serverPort); } @Override public void run() { try { ObjectInputStream fromServer = new ObjectInputStream(s.getInputStream()); //create object streams with the server ObjectOutputStream toServer = new ObjectOutputStream(s.getOutputStream()); try {
Utils.sleep(100); //wait for the GUI microphone test to release the microphone
lucas-dolsan/tcc-rpg
TCC/src/ClienteVoIP/Client.java
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // }
import Dependencias.Message; import Dependencias.Utils; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList;
package ClienteVoIP; public class Client extends Thread { private Socket s; private ArrayList<AudioChannel> chs = new ArrayList<AudioChannel>(); private MicThread st; public Client(String serverIp, int serverPort) throws UnknownHostException, IOException { s = new Socket(serverIp, serverPort); } @Override public void run() { try { ObjectInputStream fromServer = new ObjectInputStream(s.getInputStream()); //create object streams with the server ObjectOutputStream toServer = new ObjectOutputStream(s.getOutputStream()); try { Utils.sleep(100); //wait for the GUI microphone test to release the microphone st = new MicThread(toServer); //creates a MicThread that sends microphone data to the server st.start(); //starts the MicThread } catch (Exception e) { //error acquiring microphone. causes: no microphone or microphone busy System.out.println("mic unavailable " + e); } for (;;) { //this infinite cycle checks for new data from the server, then sends it to the correct AudioChannel. if needed, a new AudioChannel is created if (s.getInputStream().available() > 0) { //we got something from the server (workaround: used available method from InputStream instead of the one from ObjetInputStream because of a bug in the JRE)
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // } // Path: TCC/src/ClienteVoIP/Client.java import Dependencias.Message; import Dependencias.Utils; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; package ClienteVoIP; public class Client extends Thread { private Socket s; private ArrayList<AudioChannel> chs = new ArrayList<AudioChannel>(); private MicThread st; public Client(String serverIp, int serverPort) throws UnknownHostException, IOException { s = new Socket(serverIp, serverPort); } @Override public void run() { try { ObjectInputStream fromServer = new ObjectInputStream(s.getInputStream()); //create object streams with the server ObjectOutputStream toServer = new ObjectOutputStream(s.getOutputStream()); try { Utils.sleep(100); //wait for the GUI microphone test to release the microphone st = new MicThread(toServer); //creates a MicThread that sends microphone data to the server st.start(); //starts the MicThread } catch (Exception e) { //error acquiring microphone. causes: no microphone or microphone busy System.out.println("mic unavailable " + e); } for (;;) { //this infinite cycle checks for new data from the server, then sends it to the correct AudioChannel. if needed, a new AudioChannel is created if (s.getInputStream().available() > 0) { //we got something from the server (workaround: used available method from InputStream instead of the one from ObjetInputStream because of a bug in the JRE)
Message in = (Message) (fromServer.readObject()); //read message
lucas-dolsan/tcc-rpg
TCC/src/ClienteVoIP/AudioChannel.java
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // }
import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.zip.GZIPInputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.SourceDataLine;
package ClienteVoIP; public class AudioChannel extends Thread { private long chId; //an id unique for each user. generated by IP and port
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // } // Path: TCC/src/ClienteVoIP/AudioChannel.java import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.zip.GZIPInputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.SourceDataLine; package ClienteVoIP; public class AudioChannel extends Thread { private long chId; //an id unique for each user. generated by IP and port
private ArrayList<Message> queue = new ArrayList<Message>(); //queue of messages to be played
lucas-dolsan/tcc-rpg
TCC/src/ClienteVoIP/AudioChannel.java
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // }
import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.zip.GZIPInputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.SourceDataLine;
package ClienteVoIP; public class AudioChannel extends Thread { private long chId; //an id unique for each user. generated by IP and port private ArrayList<Message> queue = new ArrayList<Message>(); //queue of messages to be played
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // } // Path: TCC/src/ClienteVoIP/AudioChannel.java import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.zip.GZIPInputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.SourceDataLine; package ClienteVoIP; public class AudioChannel extends Thread { private long chId; //an id unique for each user. generated by IP and port private ArrayList<Message> queue = new ArrayList<Message>(); //queue of messages to be played
private int lastSoundPacketLen = SoundPacket.defaultDataLenght;
lucas-dolsan/tcc-rpg
TCC/src/ClienteVoIP/AudioChannel.java
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // }
import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.zip.GZIPInputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.SourceDataLine;
speaker.close(); } stop(); } public AudioChannel(long chId) { this.chId = chId; } public long getChId() { return chId; } public void addToQueue(Message m) { //adds a message to the play queue queue.add(m); } private SourceDataLine speaker = null; //speaker @Override public void run() { try { //open channel to sound card AudioFormat af = SoundPacket.defaultFormat; DataLine.Info info = new DataLine.Info(SourceDataLine.class, af); speaker = (SourceDataLine) AudioSystem.getLine(info); speaker.open(af); speaker.start(); //sound card ready for (;;) { //this infinite cycle checks for new packets to be played in the queue, and plays them. to avoid busy wait, a sleep(10) is executed at the beginning of each iteration if (queue.isEmpty()) { //nothing to play, wait
// Path: TCC/src/Dependencias/Message.java // public class Message implements Serializable { // // private long chId; //-1 means from client to server, otherwise chId generated by the server // private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message // ttl = 2000; //2 seconds TTL // private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ... // // public Message(long chId, long timestamp, Object data) { // this.chId = chId; // this.timestamp = timestamp; // this.data = data; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // public long getChId() { // return chId; // } // // public Object getData() { // return data; // } // // public long getTimestamp() { // return timestamp; // } // // public long getTtl() { // return ttl; // } // // public void setTtl(long ttl) { // this.ttl = ttl; // } // // public void setChId(long chId) { // this.chId = chId; // } // // } // // Path: TCC/src/Dependencias/SoundPacket.java // public class SoundPacket implements Serializable { // // public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s // public static int defaultDataLenght = 1200; //send 1200 samples/packet by default // private byte[] data; //actual data. if null, comfort noise will be played // // public SoundPacket(byte[] data) { // this.data = data; // } // // public byte[] getData() { // return data; // } // // } // // Path: TCC/src/Dependencias/Utils.java // public class Utils { // // public static void sleep(int ms) { // try { // Thread.sleep(ms); // } catch (InterruptedException ex) { // } // } // // public static String getExternalIP() { // try { // URL myIp = new URL("http://checkip.dyndns.org/"); // BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream())); // String s = in.readLine(); // return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>")); // } catch (Exception ex) { // return "error " + ex; // } // } // // public static String getInternalIP() { // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException ex) { // return "error"; // } // } // } // Path: TCC/src/ClienteVoIP/AudioChannel.java import Dependencias.Message; import Dependencias.SoundPacket; import Dependencias.Utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.zip.GZIPInputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.SourceDataLine; speaker.close(); } stop(); } public AudioChannel(long chId) { this.chId = chId; } public long getChId() { return chId; } public void addToQueue(Message m) { //adds a message to the play queue queue.add(m); } private SourceDataLine speaker = null; //speaker @Override public void run() { try { //open channel to sound card AudioFormat af = SoundPacket.defaultFormat; DataLine.Info info = new DataLine.Info(SourceDataLine.class, af); speaker = (SourceDataLine) AudioSystem.getLine(info); speaker.open(af); speaker.start(); //sound card ready for (;;) { //this infinite cycle checks for new packets to be played in the queue, and plays them. to avoid busy wait, a sleep(10) is executed at the beginning of each iteration if (queue.isEmpty()) { //nothing to play, wait
Utils.sleep(10);
maoruibin/AppPlus
app/src/main/java/com/gudong/appkit/App.java
// Path: app/src/main/java/com/gudong/appkit/utils/logger/LogLevel.java // public enum LogLevel { // /** // * Prints all logs // */ // FULL, // // /** // * No log will be printed // */ // NONE // } // // Path: app/src/main/java/com/gudong/appkit/utils/logger/Logger.java // public class Logger { // private static Setting setting; // public static Setting init(String tag){ // if (tag == null) { // throw new NullPointerException("tag may not be null"); // } // if (tag.trim().length() == 0) { // throw new IllegalStateException("tag may not be empty"); // } // setting = Setting.getInstance(); // setting.setTag(tag); // return setting; // } // // // public static void i(String message){ // log(Log.INFO, setting.getDefTag(), message); // } // // public static void e(String message){ // log(Log.ERROR, setting.getDefTag(), message); // } // // public static void i(String tag,String message){ // log(Log.INFO,tag, message); // } // // public static void e(String tag,String message){ // log(Log.ERROR,tag, message); // } // // public static void d(String tag,String message){ // log(Log.DEBUG,tag, message); // } // // public static void w(String tag,String message){ // log(Log.WARN,tag, message); // } // // private static synchronized void log(int logType, String tag,String msg) { // if(setting == null){ // throw new NullPointerException("before use Logger ,please init Logger in Application and set param"); // } // if (setting.getLevel() == LogLevel.NONE) { // return; // } // String finalTag = formatTag(tag); // switch (logType){ // case Log.INFO: // Log.i(finalTag,msg); // break; // case Log.ERROR: // Log.e(finalTag,msg); // break; // case Log.WARN: // Log.w(finalTag,msg); // break; // case Log.DEBUG: // Log.d(finalTag,msg); // break; // } // } // private static String formatTag(String tag) { // if (!TextUtils.isEmpty(tag) && !TextUtils.equals(setting.getDefTag(), tag)) { // return setting.getTag() + "-" + tag; // } // return setting.getTag(); // } // }
import android.app.Application; import android.content.Context; import com.gudong.appkit.utils.logger.LogLevel; import com.gudong.appkit.utils.logger.Logger; import com.litesuits.orm.LiteOrm; import jonathanfinerty.once.Once;
/* * Copyright (c) 2015 GuDong * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.gudong.appkit; /** * 应用程序入口 * Created by mao on 7/16/15. */ public class App extends Application { private static final String DB_NAME = "appplus.db"; public static LiteOrm sDb; public static Context sContext; @Override public void onCreate() { super.onCreate(); sDb = LiteOrm.newSingleInstance(this, DB_NAME); sContext = this; Once.initialise(this);
// Path: app/src/main/java/com/gudong/appkit/utils/logger/LogLevel.java // public enum LogLevel { // /** // * Prints all logs // */ // FULL, // // /** // * No log will be printed // */ // NONE // } // // Path: app/src/main/java/com/gudong/appkit/utils/logger/Logger.java // public class Logger { // private static Setting setting; // public static Setting init(String tag){ // if (tag == null) { // throw new NullPointerException("tag may not be null"); // } // if (tag.trim().length() == 0) { // throw new IllegalStateException("tag may not be empty"); // } // setting = Setting.getInstance(); // setting.setTag(tag); // return setting; // } // // // public static void i(String message){ // log(Log.INFO, setting.getDefTag(), message); // } // // public static void e(String message){ // log(Log.ERROR, setting.getDefTag(), message); // } // // public static void i(String tag,String message){ // log(Log.INFO,tag, message); // } // // public static void e(String tag,String message){ // log(Log.ERROR,tag, message); // } // // public static void d(String tag,String message){ // log(Log.DEBUG,tag, message); // } // // public static void w(String tag,String message){ // log(Log.WARN,tag, message); // } // // private static synchronized void log(int logType, String tag,String msg) { // if(setting == null){ // throw new NullPointerException("before use Logger ,please init Logger in Application and set param"); // } // if (setting.getLevel() == LogLevel.NONE) { // return; // } // String finalTag = formatTag(tag); // switch (logType){ // case Log.INFO: // Log.i(finalTag,msg); // break; // case Log.ERROR: // Log.e(finalTag,msg); // break; // case Log.WARN: // Log.w(finalTag,msg); // break; // case Log.DEBUG: // Log.d(finalTag,msg); // break; // } // } // private static String formatTag(String tag) { // if (!TextUtils.isEmpty(tag) && !TextUtils.equals(setting.getDefTag(), tag)) { // return setting.getTag() + "-" + tag; // } // return setting.getTag(); // } // } // Path: app/src/main/java/com/gudong/appkit/App.java import android.app.Application; import android.content.Context; import com.gudong.appkit.utils.logger.LogLevel; import com.gudong.appkit.utils.logger.Logger; import com.litesuits.orm.LiteOrm; import jonathanfinerty.once.Once; /* * Copyright (c) 2015 GuDong * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.gudong.appkit; /** * 应用程序入口 * Created by mao on 7/16/15. */ public class App extends Application { private static final String DB_NAME = "appplus.db"; public static LiteOrm sDb; public static Context sContext; @Override public void onCreate() { super.onCreate(); sDb = LiteOrm.newSingleInstance(this, DB_NAME); sContext = this; Once.initialise(this);
Logger.init("AppPlusLog").setLogLevel(BuildConfig.IS_DEBUG?LogLevel.FULL:LogLevel.NONE);
maoruibin/AppPlus
app/src/main/java/com/gudong/appkit/App.java
// Path: app/src/main/java/com/gudong/appkit/utils/logger/LogLevel.java // public enum LogLevel { // /** // * Prints all logs // */ // FULL, // // /** // * No log will be printed // */ // NONE // } // // Path: app/src/main/java/com/gudong/appkit/utils/logger/Logger.java // public class Logger { // private static Setting setting; // public static Setting init(String tag){ // if (tag == null) { // throw new NullPointerException("tag may not be null"); // } // if (tag.trim().length() == 0) { // throw new IllegalStateException("tag may not be empty"); // } // setting = Setting.getInstance(); // setting.setTag(tag); // return setting; // } // // // public static void i(String message){ // log(Log.INFO, setting.getDefTag(), message); // } // // public static void e(String message){ // log(Log.ERROR, setting.getDefTag(), message); // } // // public static void i(String tag,String message){ // log(Log.INFO,tag, message); // } // // public static void e(String tag,String message){ // log(Log.ERROR,tag, message); // } // // public static void d(String tag,String message){ // log(Log.DEBUG,tag, message); // } // // public static void w(String tag,String message){ // log(Log.WARN,tag, message); // } // // private static synchronized void log(int logType, String tag,String msg) { // if(setting == null){ // throw new NullPointerException("before use Logger ,please init Logger in Application and set param"); // } // if (setting.getLevel() == LogLevel.NONE) { // return; // } // String finalTag = formatTag(tag); // switch (logType){ // case Log.INFO: // Log.i(finalTag,msg); // break; // case Log.ERROR: // Log.e(finalTag,msg); // break; // case Log.WARN: // Log.w(finalTag,msg); // break; // case Log.DEBUG: // Log.d(finalTag,msg); // break; // } // } // private static String formatTag(String tag) { // if (!TextUtils.isEmpty(tag) && !TextUtils.equals(setting.getDefTag(), tag)) { // return setting.getTag() + "-" + tag; // } // return setting.getTag(); // } // }
import android.app.Application; import android.content.Context; import com.gudong.appkit.utils.logger.LogLevel; import com.gudong.appkit.utils.logger.Logger; import com.litesuits.orm.LiteOrm; import jonathanfinerty.once.Once;
/* * Copyright (c) 2015 GuDong * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.gudong.appkit; /** * 应用程序入口 * Created by mao on 7/16/15. */ public class App extends Application { private static final String DB_NAME = "appplus.db"; public static LiteOrm sDb; public static Context sContext; @Override public void onCreate() { super.onCreate(); sDb = LiteOrm.newSingleInstance(this, DB_NAME); sContext = this; Once.initialise(this);
// Path: app/src/main/java/com/gudong/appkit/utils/logger/LogLevel.java // public enum LogLevel { // /** // * Prints all logs // */ // FULL, // // /** // * No log will be printed // */ // NONE // } // // Path: app/src/main/java/com/gudong/appkit/utils/logger/Logger.java // public class Logger { // private static Setting setting; // public static Setting init(String tag){ // if (tag == null) { // throw new NullPointerException("tag may not be null"); // } // if (tag.trim().length() == 0) { // throw new IllegalStateException("tag may not be empty"); // } // setting = Setting.getInstance(); // setting.setTag(tag); // return setting; // } // // // public static void i(String message){ // log(Log.INFO, setting.getDefTag(), message); // } // // public static void e(String message){ // log(Log.ERROR, setting.getDefTag(), message); // } // // public static void i(String tag,String message){ // log(Log.INFO,tag, message); // } // // public static void e(String tag,String message){ // log(Log.ERROR,tag, message); // } // // public static void d(String tag,String message){ // log(Log.DEBUG,tag, message); // } // // public static void w(String tag,String message){ // log(Log.WARN,tag, message); // } // // private static synchronized void log(int logType, String tag,String msg) { // if(setting == null){ // throw new NullPointerException("before use Logger ,please init Logger in Application and set param"); // } // if (setting.getLevel() == LogLevel.NONE) { // return; // } // String finalTag = formatTag(tag); // switch (logType){ // case Log.INFO: // Log.i(finalTag,msg); // break; // case Log.ERROR: // Log.e(finalTag,msg); // break; // case Log.WARN: // Log.w(finalTag,msg); // break; // case Log.DEBUG: // Log.d(finalTag,msg); // break; // } // } // private static String formatTag(String tag) { // if (!TextUtils.isEmpty(tag) && !TextUtils.equals(setting.getDefTag(), tag)) { // return setting.getTag() + "-" + tag; // } // return setting.getTag(); // } // } // Path: app/src/main/java/com/gudong/appkit/App.java import android.app.Application; import android.content.Context; import com.gudong.appkit.utils.logger.LogLevel; import com.gudong.appkit.utils.logger.Logger; import com.litesuits.orm.LiteOrm; import jonathanfinerty.once.Once; /* * Copyright (c) 2015 GuDong * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.gudong.appkit; /** * 应用程序入口 * Created by mao on 7/16/15. */ public class App extends Application { private static final String DB_NAME = "appplus.db"; public static LiteOrm sDb; public static Context sContext; @Override public void onCreate() { super.onCreate(); sDb = LiteOrm.newSingleInstance(this, DB_NAME); sContext = this; Once.initialise(this);
Logger.init("AppPlusLog").setLogLevel(BuildConfig.IS_DEBUG?LogLevel.FULL:LogLevel.NONE);
maoruibin/AppPlus
library/src/main/java/hotchemi/android/rate/DialogManager.java
// Path: library/src/main/java/hotchemi/android/rate/Utils.java // @SuppressLint("NewApi") // static AlertDialog.Builder getDialogBuilder(Context context) { // if (underHoneyComb()) { // return new AlertDialog.Builder(context); // } else { // return new AlertDialog.Builder(context, getDialogTheme()); // } // }
import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.view.View; import static hotchemi.android.rate.IntentHelper.createIntentForAmazonAppstore; import static hotchemi.android.rate.IntentHelper.createIntentForGooglePlay; import static hotchemi.android.rate.PreferenceHelper.setAgreeShowDialog; import static hotchemi.android.rate.PreferenceHelper.setRemindInterval; import static hotchemi.android.rate.Utils.getDialogBuilder;
package hotchemi.android.rate; final class DialogManager { private DialogManager() { } static Dialog create(final Context context, final DialogOptions options) {
// Path: library/src/main/java/hotchemi/android/rate/Utils.java // @SuppressLint("NewApi") // static AlertDialog.Builder getDialogBuilder(Context context) { // if (underHoneyComb()) { // return new AlertDialog.Builder(context); // } else { // return new AlertDialog.Builder(context, getDialogTheme()); // } // } // Path: library/src/main/java/hotchemi/android/rate/DialogManager.java import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.view.View; import static hotchemi.android.rate.IntentHelper.createIntentForAmazonAppstore; import static hotchemi.android.rate.IntentHelper.createIntentForGooglePlay; import static hotchemi.android.rate.PreferenceHelper.setAgreeShowDialog; import static hotchemi.android.rate.PreferenceHelper.setRemindInterval; import static hotchemi.android.rate.Utils.getDialogBuilder; package hotchemi.android.rate; final class DialogManager { private DialogManager() { } static Dialog create(final Context context, final DialogOptions options) {
AlertDialog.Builder builder = getDialogBuilder(context);
maoruibin/AppPlus
app/src/main/java/com/gudong/appkit/event/EventCenter.java
// Path: app/src/main/java/com/gudong/appkit/utils/logger/Logger.java // public class Logger { // private static Setting setting; // public static Setting init(String tag){ // if (tag == null) { // throw new NullPointerException("tag may not be null"); // } // if (tag.trim().length() == 0) { // throw new IllegalStateException("tag may not be empty"); // } // setting = Setting.getInstance(); // setting.setTag(tag); // return setting; // } // // // public static void i(String message){ // log(Log.INFO, setting.getDefTag(), message); // } // // public static void e(String message){ // log(Log.ERROR, setting.getDefTag(), message); // } // // public static void i(String tag,String message){ // log(Log.INFO,tag, message); // } // // public static void e(String tag,String message){ // log(Log.ERROR,tag, message); // } // // public static void d(String tag,String message){ // log(Log.DEBUG,tag, message); // } // // public static void w(String tag,String message){ // log(Log.WARN,tag, message); // } // // private static synchronized void log(int logType, String tag,String msg) { // if(setting == null){ // throw new NullPointerException("before use Logger ,please init Logger in Application and set param"); // } // if (setting.getLevel() == LogLevel.NONE) { // return; // } // String finalTag = formatTag(tag); // switch (logType){ // case Log.INFO: // Log.i(finalTag,msg); // break; // case Log.ERROR: // Log.e(finalTag,msg); // break; // case Log.WARN: // Log.w(finalTag,msg); // break; // case Log.DEBUG: // Log.d(finalTag,msg); // break; // } // } // private static String formatTag(String tag) { // if (!TextUtils.isEmpty(tag) && !TextUtils.equals(setting.getDefTag(), tag)) { // return setting.getTag() + "-" + tag; // } // return setting.getTag(); // } // }
import java.util.Set; import android.os.Bundle; import com.gudong.appkit.utils.logger.Logger; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map;
* @param event */ public void triggerEvent(EEvent event, Bundle data) { Set<Subscribe>registerList = mEvents.get(event); if(registerList == null){ return; } if(!registerList.isEmpty()){ for (Iterator<Subscribe>it = registerList.iterator();it.hasNext();) { Subscribe subscribe = it.next(); subscribe.update(event,data); } } } public void registerEvent(EEvent event,Subscribe subscribe) { Set<Subscribe> registerList = mEvents.get(event); if(registerList == null){ registerList = new HashSet<Subscribe>(); } if(registerList.isEmpty()){ mEvents.put(event,registerList); } registerList.add(subscribe); } public void unregisterEvent(EEvent event,Subscribe subscribe){ Set<Subscribe> registerList = mEvents.get(event); if(registerList!=null && !registerList.isEmpty()){ registerList.remove(subscribe);
// Path: app/src/main/java/com/gudong/appkit/utils/logger/Logger.java // public class Logger { // private static Setting setting; // public static Setting init(String tag){ // if (tag == null) { // throw new NullPointerException("tag may not be null"); // } // if (tag.trim().length() == 0) { // throw new IllegalStateException("tag may not be empty"); // } // setting = Setting.getInstance(); // setting.setTag(tag); // return setting; // } // // // public static void i(String message){ // log(Log.INFO, setting.getDefTag(), message); // } // // public static void e(String message){ // log(Log.ERROR, setting.getDefTag(), message); // } // // public static void i(String tag,String message){ // log(Log.INFO,tag, message); // } // // public static void e(String tag,String message){ // log(Log.ERROR,tag, message); // } // // public static void d(String tag,String message){ // log(Log.DEBUG,tag, message); // } // // public static void w(String tag,String message){ // log(Log.WARN,tag, message); // } // // private static synchronized void log(int logType, String tag,String msg) { // if(setting == null){ // throw new NullPointerException("before use Logger ,please init Logger in Application and set param"); // } // if (setting.getLevel() == LogLevel.NONE) { // return; // } // String finalTag = formatTag(tag); // switch (logType){ // case Log.INFO: // Log.i(finalTag,msg); // break; // case Log.ERROR: // Log.e(finalTag,msg); // break; // case Log.WARN: // Log.w(finalTag,msg); // break; // case Log.DEBUG: // Log.d(finalTag,msg); // break; // } // } // private static String formatTag(String tag) { // if (!TextUtils.isEmpty(tag) && !TextUtils.equals(setting.getDefTag(), tag)) { // return setting.getTag() + "-" + tag; // } // return setting.getTag(); // } // } // Path: app/src/main/java/com/gudong/appkit/event/EventCenter.java import java.util.Set; import android.os.Bundle; import com.gudong.appkit.utils.logger.Logger; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; * @param event */ public void triggerEvent(EEvent event, Bundle data) { Set<Subscribe>registerList = mEvents.get(event); if(registerList == null){ return; } if(!registerList.isEmpty()){ for (Iterator<Subscribe>it = registerList.iterator();it.hasNext();) { Subscribe subscribe = it.next(); subscribe.update(event,data); } } } public void registerEvent(EEvent event,Subscribe subscribe) { Set<Subscribe> registerList = mEvents.get(event); if(registerList == null){ registerList = new HashSet<Subscribe>(); } if(registerList.isEmpty()){ mEvents.put(event,registerList); } registerList.add(subscribe); } public void unregisterEvent(EEvent event,Subscribe subscribe){ Set<Subscribe> registerList = mEvents.get(event); if(registerList!=null && !registerList.isEmpty()){ registerList.remove(subscribe);
Logger.i("unregister "+event.name());
maoruibin/AppPlus
app/src/main/java/com/gudong/appkit/utils/Utils.java
// Path: app/src/main/java/com/gudong/appkit/App.java // public class App extends Application { // private static final String DB_NAME = "appplus.db"; // public static LiteOrm sDb; // public static Context sContext; // @Override // public void onCreate() { // super.onCreate(); // sDb = LiteOrm.newSingleInstance(this, DB_NAME); // sContext = this; // Once.initialise(this); // Logger.init("AppPlusLog").setLogLevel(BuildConfig.IS_DEBUG?LogLevel.FULL:LogLevel.NONE); // sDb.setDebugged(BuildConfig.IS_DEBUG); // } // } // // Path: app/src/main/java/com/gudong/appkit/ui/control/ThemeControl.java // public class ThemeControl { // private Context mContext; // private int mCurrentTheme; // public ThemeControl(Context context){ // this.mContext = context; // isChanged(); // invalidate stored booleans // // } // // public int getTheme(Context context){ // return Utils.getIntPreference(context, "theme", R.style.Theme_AppPlus); // } // // public void setTheme(int theme){ // Utils.putIntPreference(mContext, "theme", theme); // } // // /** // * 记住用户选择的主题颜色对应的position // * @param position 用户已选择position // */ // public void setThemePosition(int position){ // Utils.putIntPreference(mContext, "themePosition", position); // } // // public int getThemePosition(){ // return Utils.getIntPreference(mContext,"themePosition",4); // } // // public boolean isChanged() { // int currentTheme = getTheme(mContext); // boolean isChange = mCurrentTheme != currentTheme; // mCurrentTheme = currentTheme; // return isChange; // } // // /** // * 自定义的主题数组,每一种颜色对应了夜间模式和日间模式 // * 目前夜间模式已经不做了,所以对应的主题在目前项目中是用不到的 // * @return // */ // public static int[]themeArr(){ // return new int[]{ // R.style.LightRed, // R.style.LightPink, // R.style.LightPurple, // R.style.LightDeepPurple, // R.style.LightIndigo, // R.style.LightBlue, // R.style.LightLightBlue, // R.style.LightCyan, // R.style.LightTeal, // R.style.LightGreen, // R.style.LightLightGreen, // R.style.LightLime, // R.style.LightYellow, // R.style.LightAmber, // R.style.LightOrange, // R.style.LightDeepOrange, // R.style.LightBrown, // R.style.LightGrey, // R.style.LightBlueGrey, // }; // } // // }
import android.support.v4.content.ContextCompat; import android.util.TypedValue; import com.gudong.appkit.App; import com.gudong.appkit.R; import com.gudong.appkit.ui.control.ThemeControl; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import android.support.annotation.ColorRes;
* @return */ public static int getThemePrimaryDarkColor(Context context) { TypedValue typedValue = new TypedValue(); Resources.Theme theme = context.getTheme(); theme.resolveAttribute(R.attr.theme_color_dark, typedValue, true); return typedValue.data; } /** * 获取当前主题色对应色值 * * @param context * @return */ public static int getThemePrimaryColor(Context context) { TypedValue typedValue = new TypedValue(); Resources.Theme theme = context.getTheme(); theme.resolveAttribute(R.attr.theme_color, typedValue, true); return typedValue.data; } /** * 获取当前设置的主题 * * @param context * @return */ public static int getCurrentTheme(Context context) { int position = Utils.getIntPreference(context, "themePosition", 4);
// Path: app/src/main/java/com/gudong/appkit/App.java // public class App extends Application { // private static final String DB_NAME = "appplus.db"; // public static LiteOrm sDb; // public static Context sContext; // @Override // public void onCreate() { // super.onCreate(); // sDb = LiteOrm.newSingleInstance(this, DB_NAME); // sContext = this; // Once.initialise(this); // Logger.init("AppPlusLog").setLogLevel(BuildConfig.IS_DEBUG?LogLevel.FULL:LogLevel.NONE); // sDb.setDebugged(BuildConfig.IS_DEBUG); // } // } // // Path: app/src/main/java/com/gudong/appkit/ui/control/ThemeControl.java // public class ThemeControl { // private Context mContext; // private int mCurrentTheme; // public ThemeControl(Context context){ // this.mContext = context; // isChanged(); // invalidate stored booleans // // } // // public int getTheme(Context context){ // return Utils.getIntPreference(context, "theme", R.style.Theme_AppPlus); // } // // public void setTheme(int theme){ // Utils.putIntPreference(mContext, "theme", theme); // } // // /** // * 记住用户选择的主题颜色对应的position // * @param position 用户已选择position // */ // public void setThemePosition(int position){ // Utils.putIntPreference(mContext, "themePosition", position); // } // // public int getThemePosition(){ // return Utils.getIntPreference(mContext,"themePosition",4); // } // // public boolean isChanged() { // int currentTheme = getTheme(mContext); // boolean isChange = mCurrentTheme != currentTheme; // mCurrentTheme = currentTheme; // return isChange; // } // // /** // * 自定义的主题数组,每一种颜色对应了夜间模式和日间模式 // * 目前夜间模式已经不做了,所以对应的主题在目前项目中是用不到的 // * @return // */ // public static int[]themeArr(){ // return new int[]{ // R.style.LightRed, // R.style.LightPink, // R.style.LightPurple, // R.style.LightDeepPurple, // R.style.LightIndigo, // R.style.LightBlue, // R.style.LightLightBlue, // R.style.LightCyan, // R.style.LightTeal, // R.style.LightGreen, // R.style.LightLightGreen, // R.style.LightLime, // R.style.LightYellow, // R.style.LightAmber, // R.style.LightOrange, // R.style.LightDeepOrange, // R.style.LightBrown, // R.style.LightGrey, // R.style.LightBlueGrey, // }; // } // // } // Path: app/src/main/java/com/gudong/appkit/utils/Utils.java import android.support.v4.content.ContextCompat; import android.util.TypedValue; import com.gudong.appkit.App; import com.gudong.appkit.R; import com.gudong.appkit.ui.control.ThemeControl; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import android.support.annotation.ColorRes; * @return */ public static int getThemePrimaryDarkColor(Context context) { TypedValue typedValue = new TypedValue(); Resources.Theme theme = context.getTheme(); theme.resolveAttribute(R.attr.theme_color_dark, typedValue, true); return typedValue.data; } /** * 获取当前主题色对应色值 * * @param context * @return */ public static int getThemePrimaryColor(Context context) { TypedValue typedValue = new TypedValue(); Resources.Theme theme = context.getTheme(); theme.resolveAttribute(R.attr.theme_color, typedValue, true); return typedValue.data; } /** * 获取当前设置的主题 * * @param context * @return */ public static int getCurrentTheme(Context context) { int position = Utils.getIntPreference(context, "themePosition", 4);
return ThemeControl.themeArr()[position];
maoruibin/AppPlus
app/src/main/java/com/gudong/appkit/utils/Utils.java
// Path: app/src/main/java/com/gudong/appkit/App.java // public class App extends Application { // private static final String DB_NAME = "appplus.db"; // public static LiteOrm sDb; // public static Context sContext; // @Override // public void onCreate() { // super.onCreate(); // sDb = LiteOrm.newSingleInstance(this, DB_NAME); // sContext = this; // Once.initialise(this); // Logger.init("AppPlusLog").setLogLevel(BuildConfig.IS_DEBUG?LogLevel.FULL:LogLevel.NONE); // sDb.setDebugged(BuildConfig.IS_DEBUG); // } // } // // Path: app/src/main/java/com/gudong/appkit/ui/control/ThemeControl.java // public class ThemeControl { // private Context mContext; // private int mCurrentTheme; // public ThemeControl(Context context){ // this.mContext = context; // isChanged(); // invalidate stored booleans // // } // // public int getTheme(Context context){ // return Utils.getIntPreference(context, "theme", R.style.Theme_AppPlus); // } // // public void setTheme(int theme){ // Utils.putIntPreference(mContext, "theme", theme); // } // // /** // * 记住用户选择的主题颜色对应的position // * @param position 用户已选择position // */ // public void setThemePosition(int position){ // Utils.putIntPreference(mContext, "themePosition", position); // } // // public int getThemePosition(){ // return Utils.getIntPreference(mContext,"themePosition",4); // } // // public boolean isChanged() { // int currentTheme = getTheme(mContext); // boolean isChange = mCurrentTheme != currentTheme; // mCurrentTheme = currentTheme; // return isChange; // } // // /** // * 自定义的主题数组,每一种颜色对应了夜间模式和日间模式 // * 目前夜间模式已经不做了,所以对应的主题在目前项目中是用不到的 // * @return // */ // public static int[]themeArr(){ // return new int[]{ // R.style.LightRed, // R.style.LightPink, // R.style.LightPurple, // R.style.LightDeepPurple, // R.style.LightIndigo, // R.style.LightBlue, // R.style.LightLightBlue, // R.style.LightCyan, // R.style.LightTeal, // R.style.LightGreen, // R.style.LightLightGreen, // R.style.LightLime, // R.style.LightYellow, // R.style.LightAmber, // R.style.LightOrange, // R.style.LightDeepOrange, // R.style.LightBrown, // R.style.LightGrey, // R.style.LightBlueGrey, // }; // } // // }
import android.support.v4.content.ContextCompat; import android.util.TypedValue; import com.gudong.appkit.App; import com.gudong.appkit.R; import com.gudong.appkit.ui.control.ThemeControl; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import android.support.annotation.ColorRes;
return typedValue.data; } /** * 获取当前设置的主题 * * @param context * @return */ public static int getCurrentTheme(Context context) { int position = Utils.getIntPreference(context, "themePosition", 4); return ThemeControl.themeArr()[position]; } /** * 获取color对应的int值 * * @param context Activity * @param color 资源颜色id * @return 对应的int value */ public static int getColorWarp(Activity context, @ColorRes int color) { return ContextCompat.getColor(context, color); } /** * running list is show AppPlus or not * @return return true if recent list view need show appplus */ public static boolean isShowSelf() {
// Path: app/src/main/java/com/gudong/appkit/App.java // public class App extends Application { // private static final String DB_NAME = "appplus.db"; // public static LiteOrm sDb; // public static Context sContext; // @Override // public void onCreate() { // super.onCreate(); // sDb = LiteOrm.newSingleInstance(this, DB_NAME); // sContext = this; // Once.initialise(this); // Logger.init("AppPlusLog").setLogLevel(BuildConfig.IS_DEBUG?LogLevel.FULL:LogLevel.NONE); // sDb.setDebugged(BuildConfig.IS_DEBUG); // } // } // // Path: app/src/main/java/com/gudong/appkit/ui/control/ThemeControl.java // public class ThemeControl { // private Context mContext; // private int mCurrentTheme; // public ThemeControl(Context context){ // this.mContext = context; // isChanged(); // invalidate stored booleans // // } // // public int getTheme(Context context){ // return Utils.getIntPreference(context, "theme", R.style.Theme_AppPlus); // } // // public void setTheme(int theme){ // Utils.putIntPreference(mContext, "theme", theme); // } // // /** // * 记住用户选择的主题颜色对应的position // * @param position 用户已选择position // */ // public void setThemePosition(int position){ // Utils.putIntPreference(mContext, "themePosition", position); // } // // public int getThemePosition(){ // return Utils.getIntPreference(mContext,"themePosition",4); // } // // public boolean isChanged() { // int currentTheme = getTheme(mContext); // boolean isChange = mCurrentTheme != currentTheme; // mCurrentTheme = currentTheme; // return isChange; // } // // /** // * 自定义的主题数组,每一种颜色对应了夜间模式和日间模式 // * 目前夜间模式已经不做了,所以对应的主题在目前项目中是用不到的 // * @return // */ // public static int[]themeArr(){ // return new int[]{ // R.style.LightRed, // R.style.LightPink, // R.style.LightPurple, // R.style.LightDeepPurple, // R.style.LightIndigo, // R.style.LightBlue, // R.style.LightLightBlue, // R.style.LightCyan, // R.style.LightTeal, // R.style.LightGreen, // R.style.LightLightGreen, // R.style.LightLime, // R.style.LightYellow, // R.style.LightAmber, // R.style.LightOrange, // R.style.LightDeepOrange, // R.style.LightBrown, // R.style.LightGrey, // R.style.LightBlueGrey, // }; // } // // } // Path: app/src/main/java/com/gudong/appkit/utils/Utils.java import android.support.v4.content.ContextCompat; import android.util.TypedValue; import com.gudong.appkit.App; import com.gudong.appkit.R; import com.gudong.appkit.ui.control.ThemeControl; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import android.support.annotation.ColorRes; return typedValue.data; } /** * 获取当前设置的主题 * * @param context * @return */ public static int getCurrentTheme(Context context) { int position = Utils.getIntPreference(context, "themePosition", 4); return ThemeControl.themeArr()[position]; } /** * 获取color对应的int值 * * @param context Activity * @param color 资源颜色id * @return 对应的int value */ public static int getColorWarp(Activity context, @ColorRes int color) { return ContextCompat.getColor(context, color); } /** * running list is show AppPlus or not * @return return true if recent list view need show appplus */ public static boolean isShowSelf() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(App.sContext);
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/ui/fragment/MyFragment.java
// Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public class App extends Application { // // // 微信自动登录的flag // public static int WeChatAutoLoginTimes; // // // launch页停留时间 // public static final int LaunchDelayTime = 500; // // // 会员手机号 // public static String phone = ""; // public static boolean isLoggedin = false; // // // public static String addedMessage = ""; // // // 用于配置列表颜色 // public static final int THEME_RED = 1; // public static final int THEME_GREEN = 2; // public static final int THEME_BLUE = 3; // // public static final String pkgTim = "com.tencent.tim"; // public static final String pkgQQ = "com.tencent.mobileqq"; // public static final String pkgWX = "com.tencent.mm"; // public static final String pkgThis = "com.qsboy.antirecall"; // // // 有的机型可以针对性的过滤非CONTENT_CHANGE_TYPE_TEXT的事件 // public static boolean isTypeText = false; // // // 设置 // public static boolean isShowAllQQMessages = true; // public static boolean isWeChatAutoLogin = true; // public static boolean isSwipeRemoveOn = true; // public static boolean isCheckUpdateOnlyOnWiFi = false; // // // 检查权限按钮的点击时间 // public static long timeCheckAccessibilityServiceIsWorking = 0; // public static long timeCheckNotificationListenerServiceIsWorking = 0; // // // 用于调整两个RecyclerView高度 // public static int layoutHeight = -1; // public static int deviceHeight; // public static int recyclerViewAllHeight; // public static int recyclerViewRecalledHeight; // public static float adjusterY; // public static float adjusterOriginalY; // // public static int activityPageIndex = 2; // // public static class User { // public static String phone; // // public static Integer userType = 1; // // public static Date subscribeTime = new Date(); // // } // // public static int dip2px(Context context, float dipValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dipValue * scale); // } // // }
import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.qsboy.antirecall.R; import com.qsboy.antirecall.ui.activity.App; import java.text.SimpleDateFormat; import java.util.Locale;
/* * Copyright © 2016 - 2018 by GitHub.com/JasonQS * anti-recall.qsboy.com * All Rights Reserved */ package com.qsboy.antirecall.ui.fragment; public class MyFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); View view = inflater.inflate(R.layout.fragment_my, container, false); TextView userType = view.findViewById(R.id.userType);
// Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public class App extends Application { // // // 微信自动登录的flag // public static int WeChatAutoLoginTimes; // // // launch页停留时间 // public static final int LaunchDelayTime = 500; // // // 会员手机号 // public static String phone = ""; // public static boolean isLoggedin = false; // // // public static String addedMessage = ""; // // // 用于配置列表颜色 // public static final int THEME_RED = 1; // public static final int THEME_GREEN = 2; // public static final int THEME_BLUE = 3; // // public static final String pkgTim = "com.tencent.tim"; // public static final String pkgQQ = "com.tencent.mobileqq"; // public static final String pkgWX = "com.tencent.mm"; // public static final String pkgThis = "com.qsboy.antirecall"; // // // 有的机型可以针对性的过滤非CONTENT_CHANGE_TYPE_TEXT的事件 // public static boolean isTypeText = false; // // // 设置 // public static boolean isShowAllQQMessages = true; // public static boolean isWeChatAutoLogin = true; // public static boolean isSwipeRemoveOn = true; // public static boolean isCheckUpdateOnlyOnWiFi = false; // // // 检查权限按钮的点击时间 // public static long timeCheckAccessibilityServiceIsWorking = 0; // public static long timeCheckNotificationListenerServiceIsWorking = 0; // // // 用于调整两个RecyclerView高度 // public static int layoutHeight = -1; // public static int deviceHeight; // public static int recyclerViewAllHeight; // public static int recyclerViewRecalledHeight; // public static float adjusterY; // public static float adjusterOriginalY; // // public static int activityPageIndex = 2; // // public static class User { // public static String phone; // // public static Integer userType = 1; // // public static Date subscribeTime = new Date(); // // } // // public static int dip2px(Context context, float dipValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dipValue * scale); // } // // } // Path: app/src/main/java/com/qsboy/antirecall/ui/fragment/MyFragment.java import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.qsboy.antirecall.R; import com.qsboy.antirecall.ui.activity.App; import java.text.SimpleDateFormat; import java.util.Locale; /* * Copyright © 2016 - 2018 by GitHub.com/JasonQS * anti-recall.qsboy.com * All Rights Reserved */ package com.qsboy.antirecall.ui.fragment; public class MyFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); View view = inflater.inflate(R.layout.fragment_my, container, false); TextView userType = view.findViewById(R.id.userType);
switch (App.User.userType) {
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/access/NotificationListener.java
// Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public class App extends Application { // // // 微信自动登录的flag // public static int WeChatAutoLoginTimes; // // // launch页停留时间 // public static final int LaunchDelayTime = 500; // // // 会员手机号 // public static String phone = ""; // public static boolean isLoggedin = false; // // // public static String addedMessage = ""; // // // 用于配置列表颜色 // public static final int THEME_RED = 1; // public static final int THEME_GREEN = 2; // public static final int THEME_BLUE = 3; // // public static final String pkgTim = "com.tencent.tim"; // public static final String pkgQQ = "com.tencent.mobileqq"; // public static final String pkgWX = "com.tencent.mm"; // public static final String pkgThis = "com.qsboy.antirecall"; // // // 有的机型可以针对性的过滤非CONTENT_CHANGE_TYPE_TEXT的事件 // public static boolean isTypeText = false; // // // 设置 // public static boolean isShowAllQQMessages = true; // public static boolean isWeChatAutoLogin = true; // public static boolean isSwipeRemoveOn = true; // public static boolean isCheckUpdateOnlyOnWiFi = false; // // // 检查权限按钮的点击时间 // public static long timeCheckAccessibilityServiceIsWorking = 0; // public static long timeCheckNotificationListenerServiceIsWorking = 0; // // // 用于调整两个RecyclerView高度 // public static int layoutHeight = -1; // public static int deviceHeight; // public static int recyclerViewAllHeight; // public static int recyclerViewRecalledHeight; // public static float adjusterY; // public static float adjusterOriginalY; // // public static int activityPageIndex = 2; // // public static class User { // public static String phone; // // public static Integer userType = 1; // // public static Date subscribeTime = new Date(); // // } // // public static int dip2px(Context context, float dipValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dipValue * scale); // } // // } // // Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public static final String pkgThis = "com.qsboy.antirecall"; // // Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public static final String pkgWX = "com.tencent.mm";
import android.app.Notification; import android.os.Bundle; import android.os.PowerManager; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; import android.util.Log; import com.qsboy.antirecall.ui.activity.App; import java.util.Date; import static com.qsboy.antirecall.ui.activity.App.pkgThis; import static com.qsboy.antirecall.ui.activity.App.pkgWX;
/* * Copyright © 2016 - 2018 by GitHub.com/JasonQS * anti-recall.qsboy.com * All Rights Reserved */ package com.qsboy.antirecall.access; public class NotificationListener extends NotificationListenerService { String TAG = "NotificationListener"; private String packageName; private String title; private String text; private PowerManager pm; private PowerManager.WakeLock wl = null; @Override public void onNotificationPosted(StatusBarNotification sbn) { Bundle extras = sbn.getNotification().extras; packageName = sbn.getPackageName(); Object oTitle = extras.get(Notification.EXTRA_TITLE); Object oText = extras.get(Notification.EXTRA_TEXT); if (oTitle == null || oText == null) return; title = oTitle.toString(); text = oText.toString(); Log.d(TAG, "Notification - : " + " \npackageName: " + packageName + " \nTitle : " + title + " \nText : " + text); switch (packageName) {
// Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public class App extends Application { // // // 微信自动登录的flag // public static int WeChatAutoLoginTimes; // // // launch页停留时间 // public static final int LaunchDelayTime = 500; // // // 会员手机号 // public static String phone = ""; // public static boolean isLoggedin = false; // // // public static String addedMessage = ""; // // // 用于配置列表颜色 // public static final int THEME_RED = 1; // public static final int THEME_GREEN = 2; // public static final int THEME_BLUE = 3; // // public static final String pkgTim = "com.tencent.tim"; // public static final String pkgQQ = "com.tencent.mobileqq"; // public static final String pkgWX = "com.tencent.mm"; // public static final String pkgThis = "com.qsboy.antirecall"; // // // 有的机型可以针对性的过滤非CONTENT_CHANGE_TYPE_TEXT的事件 // public static boolean isTypeText = false; // // // 设置 // public static boolean isShowAllQQMessages = true; // public static boolean isWeChatAutoLogin = true; // public static boolean isSwipeRemoveOn = true; // public static boolean isCheckUpdateOnlyOnWiFi = false; // // // 检查权限按钮的点击时间 // public static long timeCheckAccessibilityServiceIsWorking = 0; // public static long timeCheckNotificationListenerServiceIsWorking = 0; // // // 用于调整两个RecyclerView高度 // public static int layoutHeight = -1; // public static int deviceHeight; // public static int recyclerViewAllHeight; // public static int recyclerViewRecalledHeight; // public static float adjusterY; // public static float adjusterOriginalY; // // public static int activityPageIndex = 2; // // public static class User { // public static String phone; // // public static Integer userType = 1; // // public static Date subscribeTime = new Date(); // // } // // public static int dip2px(Context context, float dipValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dipValue * scale); // } // // } // // Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public static final String pkgThis = "com.qsboy.antirecall"; // // Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public static final String pkgWX = "com.tencent.mm"; // Path: app/src/main/java/com/qsboy/antirecall/access/NotificationListener.java import android.app.Notification; import android.os.Bundle; import android.os.PowerManager; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; import android.util.Log; import com.qsboy.antirecall.ui.activity.App; import java.util.Date; import static com.qsboy.antirecall.ui.activity.App.pkgThis; import static com.qsboy.antirecall.ui.activity.App.pkgWX; /* * Copyright © 2016 - 2018 by GitHub.com/JasonQS * anti-recall.qsboy.com * All Rights Reserved */ package com.qsboy.antirecall.access; public class NotificationListener extends NotificationListenerService { String TAG = "NotificationListener"; private String packageName; private String title; private String text; private PowerManager pm; private PowerManager.WakeLock wl = null; @Override public void onNotificationPosted(StatusBarNotification sbn) { Bundle extras = sbn.getNotification().extras; packageName = sbn.getPackageName(); Object oTitle = extras.get(Notification.EXTRA_TITLE); Object oText = extras.get(Notification.EXTRA_TEXT); if (oTitle == null || oText == null) return; title = oTitle.toString(); text = oText.toString(); Log.d(TAG, "Notification - : " + " \npackageName: " + packageName + " \nTitle : " + title + " \nText : " + text); switch (packageName) {
case pkgWX:
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/access/NotificationListener.java
// Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public class App extends Application { // // // 微信自动登录的flag // public static int WeChatAutoLoginTimes; // // // launch页停留时间 // public static final int LaunchDelayTime = 500; // // // 会员手机号 // public static String phone = ""; // public static boolean isLoggedin = false; // // // public static String addedMessage = ""; // // // 用于配置列表颜色 // public static final int THEME_RED = 1; // public static final int THEME_GREEN = 2; // public static final int THEME_BLUE = 3; // // public static final String pkgTim = "com.tencent.tim"; // public static final String pkgQQ = "com.tencent.mobileqq"; // public static final String pkgWX = "com.tencent.mm"; // public static final String pkgThis = "com.qsboy.antirecall"; // // // 有的机型可以针对性的过滤非CONTENT_CHANGE_TYPE_TEXT的事件 // public static boolean isTypeText = false; // // // 设置 // public static boolean isShowAllQQMessages = true; // public static boolean isWeChatAutoLogin = true; // public static boolean isSwipeRemoveOn = true; // public static boolean isCheckUpdateOnlyOnWiFi = false; // // // 检查权限按钮的点击时间 // public static long timeCheckAccessibilityServiceIsWorking = 0; // public static long timeCheckNotificationListenerServiceIsWorking = 0; // // // 用于调整两个RecyclerView高度 // public static int layoutHeight = -1; // public static int deviceHeight; // public static int recyclerViewAllHeight; // public static int recyclerViewRecalledHeight; // public static float adjusterY; // public static float adjusterOriginalY; // // public static int activityPageIndex = 2; // // public static class User { // public static String phone; // // public static Integer userType = 1; // // public static Date subscribeTime = new Date(); // // } // // public static int dip2px(Context context, float dipValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dipValue * scale); // } // // } // // Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public static final String pkgThis = "com.qsboy.antirecall"; // // Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public static final String pkgWX = "com.tencent.mm";
import android.app.Notification; import android.os.Bundle; import android.os.PowerManager; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; import android.util.Log; import com.qsboy.antirecall.ui.activity.App; import java.util.Date; import static com.qsboy.antirecall.ui.activity.App.pkgThis; import static com.qsboy.antirecall.ui.activity.App.pkgWX;
/* * Copyright © 2016 - 2018 by GitHub.com/JasonQS * anti-recall.qsboy.com * All Rights Reserved */ package com.qsboy.antirecall.access; public class NotificationListener extends NotificationListenerService { String TAG = "NotificationListener"; private String packageName; private String title; private String text; private PowerManager pm; private PowerManager.WakeLock wl = null; @Override public void onNotificationPosted(StatusBarNotification sbn) { Bundle extras = sbn.getNotification().extras; packageName = sbn.getPackageName(); Object oTitle = extras.get(Notification.EXTRA_TITLE); Object oText = extras.get(Notification.EXTRA_TEXT); if (oTitle == null || oText == null) return; title = oTitle.toString(); text = oText.toString(); Log.d(TAG, "Notification - : " + " \npackageName: " + packageName + " \nTitle : " + title + " \nText : " + text); switch (packageName) { case pkgWX: new WXClient(getApplicationContext()).onNotification(title, text); break;
// Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public class App extends Application { // // // 微信自动登录的flag // public static int WeChatAutoLoginTimes; // // // launch页停留时间 // public static final int LaunchDelayTime = 500; // // // 会员手机号 // public static String phone = ""; // public static boolean isLoggedin = false; // // // public static String addedMessage = ""; // // // 用于配置列表颜色 // public static final int THEME_RED = 1; // public static final int THEME_GREEN = 2; // public static final int THEME_BLUE = 3; // // public static final String pkgTim = "com.tencent.tim"; // public static final String pkgQQ = "com.tencent.mobileqq"; // public static final String pkgWX = "com.tencent.mm"; // public static final String pkgThis = "com.qsboy.antirecall"; // // // 有的机型可以针对性的过滤非CONTENT_CHANGE_TYPE_TEXT的事件 // public static boolean isTypeText = false; // // // 设置 // public static boolean isShowAllQQMessages = true; // public static boolean isWeChatAutoLogin = true; // public static boolean isSwipeRemoveOn = true; // public static boolean isCheckUpdateOnlyOnWiFi = false; // // // 检查权限按钮的点击时间 // public static long timeCheckAccessibilityServiceIsWorking = 0; // public static long timeCheckNotificationListenerServiceIsWorking = 0; // // // 用于调整两个RecyclerView高度 // public static int layoutHeight = -1; // public static int deviceHeight; // public static int recyclerViewAllHeight; // public static int recyclerViewRecalledHeight; // public static float adjusterY; // public static float adjusterOriginalY; // // public static int activityPageIndex = 2; // // public static class User { // public static String phone; // // public static Integer userType = 1; // // public static Date subscribeTime = new Date(); // // } // // public static int dip2px(Context context, float dipValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dipValue * scale); // } // // } // // Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public static final String pkgThis = "com.qsboy.antirecall"; // // Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public static final String pkgWX = "com.tencent.mm"; // Path: app/src/main/java/com/qsboy/antirecall/access/NotificationListener.java import android.app.Notification; import android.os.Bundle; import android.os.PowerManager; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; import android.util.Log; import com.qsboy.antirecall.ui.activity.App; import java.util.Date; import static com.qsboy.antirecall.ui.activity.App.pkgThis; import static com.qsboy.antirecall.ui.activity.App.pkgWX; /* * Copyright © 2016 - 2018 by GitHub.com/JasonQS * anti-recall.qsboy.com * All Rights Reserved */ package com.qsboy.antirecall.access; public class NotificationListener extends NotificationListenerService { String TAG = "NotificationListener"; private String packageName; private String title; private String text; private PowerManager pm; private PowerManager.WakeLock wl = null; @Override public void onNotificationPosted(StatusBarNotification sbn) { Bundle extras = sbn.getNotification().extras; packageName = sbn.getPackageName(); Object oTitle = extras.get(Notification.EXTRA_TITLE); Object oText = extras.get(Notification.EXTRA_TEXT); if (oTitle == null || oText == null) return; title = oTitle.toString(); text = oText.toString(); Log.d(TAG, "Notification - : " + " \npackageName: " + packageName + " \nTitle : " + title + " \nText : " + text); switch (packageName) { case pkgWX: new WXClient(getApplicationContext()).onNotification(title, text); break;
case pkgThis:
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/access/NotificationListener.java
// Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public class App extends Application { // // // 微信自动登录的flag // public static int WeChatAutoLoginTimes; // // // launch页停留时间 // public static final int LaunchDelayTime = 500; // // // 会员手机号 // public static String phone = ""; // public static boolean isLoggedin = false; // // // public static String addedMessage = ""; // // // 用于配置列表颜色 // public static final int THEME_RED = 1; // public static final int THEME_GREEN = 2; // public static final int THEME_BLUE = 3; // // public static final String pkgTim = "com.tencent.tim"; // public static final String pkgQQ = "com.tencent.mobileqq"; // public static final String pkgWX = "com.tencent.mm"; // public static final String pkgThis = "com.qsboy.antirecall"; // // // 有的机型可以针对性的过滤非CONTENT_CHANGE_TYPE_TEXT的事件 // public static boolean isTypeText = false; // // // 设置 // public static boolean isShowAllQQMessages = true; // public static boolean isWeChatAutoLogin = true; // public static boolean isSwipeRemoveOn = true; // public static boolean isCheckUpdateOnlyOnWiFi = false; // // // 检查权限按钮的点击时间 // public static long timeCheckAccessibilityServiceIsWorking = 0; // public static long timeCheckNotificationListenerServiceIsWorking = 0; // // // 用于调整两个RecyclerView高度 // public static int layoutHeight = -1; // public static int deviceHeight; // public static int recyclerViewAllHeight; // public static int recyclerViewRecalledHeight; // public static float adjusterY; // public static float adjusterOriginalY; // // public static int activityPageIndex = 2; // // public static class User { // public static String phone; // // public static Integer userType = 1; // // public static Date subscribeTime = new Date(); // // } // // public static int dip2px(Context context, float dipValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dipValue * scale); // } // // } // // Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public static final String pkgThis = "com.qsboy.antirecall"; // // Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public static final String pkgWX = "com.tencent.mm";
import android.app.Notification; import android.os.Bundle; import android.os.PowerManager; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; import android.util.Log; import com.qsboy.antirecall.ui.activity.App; import java.util.Date; import static com.qsboy.antirecall.ui.activity.App.pkgThis; import static com.qsboy.antirecall.ui.activity.App.pkgWX;
/* * Copyright © 2016 - 2018 by GitHub.com/JasonQS * anti-recall.qsboy.com * All Rights Reserved */ package com.qsboy.antirecall.access; public class NotificationListener extends NotificationListenerService { String TAG = "NotificationListener"; private String packageName; private String title; private String text; private PowerManager pm; private PowerManager.WakeLock wl = null; @Override public void onNotificationPosted(StatusBarNotification sbn) { Bundle extras = sbn.getNotification().extras; packageName = sbn.getPackageName(); Object oTitle = extras.get(Notification.EXTRA_TITLE); Object oText = extras.get(Notification.EXTRA_TEXT); if (oTitle == null || oText == null) return; title = oTitle.toString(); text = oText.toString(); Log.d(TAG, "Notification - : " + " \npackageName: " + packageName + " \nTitle : " + title + " \nText : " + text); switch (packageName) { case pkgWX: new WXClient(getApplicationContext()).onNotification(title, text); break; case pkgThis:
// Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public class App extends Application { // // // 微信自动登录的flag // public static int WeChatAutoLoginTimes; // // // launch页停留时间 // public static final int LaunchDelayTime = 500; // // // 会员手机号 // public static String phone = ""; // public static boolean isLoggedin = false; // // // public static String addedMessage = ""; // // // 用于配置列表颜色 // public static final int THEME_RED = 1; // public static final int THEME_GREEN = 2; // public static final int THEME_BLUE = 3; // // public static final String pkgTim = "com.tencent.tim"; // public static final String pkgQQ = "com.tencent.mobileqq"; // public static final String pkgWX = "com.tencent.mm"; // public static final String pkgThis = "com.qsboy.antirecall"; // // // 有的机型可以针对性的过滤非CONTENT_CHANGE_TYPE_TEXT的事件 // public static boolean isTypeText = false; // // // 设置 // public static boolean isShowAllQQMessages = true; // public static boolean isWeChatAutoLogin = true; // public static boolean isSwipeRemoveOn = true; // public static boolean isCheckUpdateOnlyOnWiFi = false; // // // 检查权限按钮的点击时间 // public static long timeCheckAccessibilityServiceIsWorking = 0; // public static long timeCheckNotificationListenerServiceIsWorking = 0; // // // 用于调整两个RecyclerView高度 // public static int layoutHeight = -1; // public static int deviceHeight; // public static int recyclerViewAllHeight; // public static int recyclerViewRecalledHeight; // public static float adjusterY; // public static float adjusterOriginalY; // // public static int activityPageIndex = 2; // // public static class User { // public static String phone; // // public static Integer userType = 1; // // public static Date subscribeTime = new Date(); // // } // // public static int dip2px(Context context, float dipValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dipValue * scale); // } // // } // // Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public static final String pkgThis = "com.qsboy.antirecall"; // // Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public static final String pkgWX = "com.tencent.mm"; // Path: app/src/main/java/com/qsboy/antirecall/access/NotificationListener.java import android.app.Notification; import android.os.Bundle; import android.os.PowerManager; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; import android.util.Log; import com.qsboy.antirecall.ui.activity.App; import java.util.Date; import static com.qsboy.antirecall.ui.activity.App.pkgThis; import static com.qsboy.antirecall.ui.activity.App.pkgWX; /* * Copyright © 2016 - 2018 by GitHub.com/JasonQS * anti-recall.qsboy.com * All Rights Reserved */ package com.qsboy.antirecall.access; public class NotificationListener extends NotificationListenerService { String TAG = "NotificationListener"; private String packageName; private String title; private String text; private PowerManager pm; private PowerManager.WakeLock wl = null; @Override public void onNotificationPosted(StatusBarNotification sbn) { Bundle extras = sbn.getNotification().extras; packageName = sbn.getPackageName(); Object oTitle = extras.get(Notification.EXTRA_TITLE); Object oText = extras.get(Notification.EXTRA_TEXT); if (oTitle == null || oText == null) return; title = oTitle.toString(); text = oText.toString(); Log.d(TAG, "Notification - : " + " \npackageName: " + packageName + " \nTitle : " + title + " \nText : " + text); switch (packageName) { case pkgWX: new WXClient(getApplicationContext()).onNotification(title, text); break; case pkgThis:
App.timeCheckNotificationListenerServiceIsWorking = new Date().getTime();
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/utils/XToastPro.java
// Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public class App extends Application { // // // 微信自动登录的flag // public static int WeChatAutoLoginTimes; // // // launch页停留时间 // public static final int LaunchDelayTime = 500; // // // 会员手机号 // public static String phone = ""; // public static boolean isLoggedin = false; // // // public static String addedMessage = ""; // // // 用于配置列表颜色 // public static final int THEME_RED = 1; // public static final int THEME_GREEN = 2; // public static final int THEME_BLUE = 3; // // public static final String pkgTim = "com.tencent.tim"; // public static final String pkgQQ = "com.tencent.mobileqq"; // public static final String pkgWX = "com.tencent.mm"; // public static final String pkgThis = "com.qsboy.antirecall"; // // // 有的机型可以针对性的过滤非CONTENT_CHANGE_TYPE_TEXT的事件 // public static boolean isTypeText = false; // // // 设置 // public static boolean isShowAllQQMessages = true; // public static boolean isWeChatAutoLogin = true; // public static boolean isSwipeRemoveOn = true; // public static boolean isCheckUpdateOnlyOnWiFi = false; // // // 检查权限按钮的点击时间 // public static long timeCheckAccessibilityServiceIsWorking = 0; // public static long timeCheckNotificationListenerServiceIsWorking = 0; // // // 用于调整两个RecyclerView高度 // public static int layoutHeight = -1; // public static int deviceHeight; // public static int recyclerViewAllHeight; // public static int recyclerViewRecalledHeight; // public static float adjusterY; // public static float adjusterOriginalY; // // public static int activityPageIndex = 2; // // public static class User { // public static String phone; // // public static Integer userType = 1; // // public static Date subscribeTime = new Date(); // // } // // public static int dip2px(Context context, float dipValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dipValue * scale); // } // // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.PixelFormat; import android.os.Build; import android.os.Handler; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.qsboy.antirecall.R; import com.qsboy.antirecall.ui.activity.App;
/* * Copyright © 2016 - 2018 by GitHub.com/JasonQS * anti-recall.qsboy.com * All Rights Reserved */ package com.qsboy.antirecall.utils; public class XToastPro { private static String TAG = "X-Toast-Pro"; private static LinearLayout ll; private WindowManager.LayoutParams params; private Context context; private WindowManager wm; private int duration = 2500; private int top; private int bottom; private FrameLayout item; private XToastPro(Context context) { this.context = context.getApplicationContext();
// Path: app/src/main/java/com/qsboy/antirecall/ui/activity/App.java // public class App extends Application { // // // 微信自动登录的flag // public static int WeChatAutoLoginTimes; // // // launch页停留时间 // public static final int LaunchDelayTime = 500; // // // 会员手机号 // public static String phone = ""; // public static boolean isLoggedin = false; // // // public static String addedMessage = ""; // // // 用于配置列表颜色 // public static final int THEME_RED = 1; // public static final int THEME_GREEN = 2; // public static final int THEME_BLUE = 3; // // public static final String pkgTim = "com.tencent.tim"; // public static final String pkgQQ = "com.tencent.mobileqq"; // public static final String pkgWX = "com.tencent.mm"; // public static final String pkgThis = "com.qsboy.antirecall"; // // // 有的机型可以针对性的过滤非CONTENT_CHANGE_TYPE_TEXT的事件 // public static boolean isTypeText = false; // // // 设置 // public static boolean isShowAllQQMessages = true; // public static boolean isWeChatAutoLogin = true; // public static boolean isSwipeRemoveOn = true; // public static boolean isCheckUpdateOnlyOnWiFi = false; // // // 检查权限按钮的点击时间 // public static long timeCheckAccessibilityServiceIsWorking = 0; // public static long timeCheckNotificationListenerServiceIsWorking = 0; // // // 用于调整两个RecyclerView高度 // public static int layoutHeight = -1; // public static int deviceHeight; // public static int recyclerViewAllHeight; // public static int recyclerViewRecalledHeight; // public static float adjusterY; // public static float adjusterOriginalY; // // public static int activityPageIndex = 2; // // public static class User { // public static String phone; // // public static Integer userType = 1; // // public static Date subscribeTime = new Date(); // // } // // public static int dip2px(Context context, float dipValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dipValue * scale); // } // // } // Path: app/src/main/java/com/qsboy/antirecall/utils/XToastPro.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.PixelFormat; import android.os.Build; import android.os.Handler; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.qsboy.antirecall.R; import com.qsboy.antirecall.ui.activity.App; /* * Copyright © 2016 - 2018 by GitHub.com/JasonQS * anti-recall.qsboy.com * All Rights Reserved */ package com.qsboy.antirecall.utils; public class XToastPro { private static String TAG = "X-Toast-Pro"; private static LinearLayout ll; private WindowManager.LayoutParams params; private Context context; private WindowManager wm; private int duration = 2500; private int top; private int bottom; private FrameLayout item; private XToastPro(Context context) { this.context = context.getApplicationContext();
top = App.deviceHeight / 2;
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/db/Dao.java
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls";
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages;
private SQLiteDatabase db; private HashMap<String, Boolean> existTables = new HashMap<>(); private Dao(DBHelper dbHelper) { db = dbHelper.getWritableDatabase(); } public static Dao getInstance(Context context, String dbName) { if (DB_NAME_QQ.equals(dbName)) { TAG = "QQ Dao"; if (instanceQQ == null) instanceQQ = new Dao(new DBHelper(context, DB_NAME_QQ, null, 6)); return instanceQQ; } if (DB_NAME_WE_CHAT.equals(dbName)) { TAG = "WeChat Dao"; if (instanceWeChat == null) instanceWeChat = new Dao(new DBHelper(context, DB_NAME_WE_CHAT, null, 6)); return instanceWeChat; } return null; } private void closeCursor() { if (cursor != null) cursor.close(); } private void createTableIfNotExists(String name) { String sqlCreateTable = "CREATE TABLE IF NOT EXISTS " + getSafeName(name) + " (" +
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls"; // Path: app/src/main/java/com/qsboy/antirecall/db/Dao.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages; private SQLiteDatabase db; private HashMap<String, Boolean> existTables = new HashMap<>(); private Dao(DBHelper dbHelper) { db = dbHelper.getWritableDatabase(); } public static Dao getInstance(Context context, String dbName) { if (DB_NAME_QQ.equals(dbName)) { TAG = "QQ Dao"; if (instanceQQ == null) instanceQQ = new Dao(new DBHelper(context, DB_NAME_QQ, null, 6)); return instanceQQ; } if (DB_NAME_WE_CHAT.equals(dbName)) { TAG = "WeChat Dao"; if (instanceWeChat == null) instanceWeChat = new Dao(new DBHelper(context, DB_NAME_WE_CHAT, null, 6)); return instanceWeChat; } return null; } private void closeCursor() { if (cursor != null) cursor.close(); } private void createTableIfNotExists(String name) { String sqlCreateTable = "CREATE TABLE IF NOT EXISTS " + getSafeName(name) + " (" +
Column_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/db/Dao.java
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls";
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages;
private HashMap<String, Boolean> existTables = new HashMap<>(); private Dao(DBHelper dbHelper) { db = dbHelper.getWritableDatabase(); } public static Dao getInstance(Context context, String dbName) { if (DB_NAME_QQ.equals(dbName)) { TAG = "QQ Dao"; if (instanceQQ == null) instanceQQ = new Dao(new DBHelper(context, DB_NAME_QQ, null, 6)); return instanceQQ; } if (DB_NAME_WE_CHAT.equals(dbName)) { TAG = "WeChat Dao"; if (instanceWeChat == null) instanceWeChat = new Dao(new DBHelper(context, DB_NAME_WE_CHAT, null, 6)); return instanceWeChat; } return null; } private void closeCursor() { if (cursor != null) cursor.close(); } private void createTableIfNotExists(String name) { String sqlCreateTable = "CREATE TABLE IF NOT EXISTS " + getSafeName(name) + " (" + Column_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls"; // Path: app/src/main/java/com/qsboy/antirecall/db/Dao.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages; private HashMap<String, Boolean> existTables = new HashMap<>(); private Dao(DBHelper dbHelper) { db = dbHelper.getWritableDatabase(); } public static Dao getInstance(Context context, String dbName) { if (DB_NAME_QQ.equals(dbName)) { TAG = "QQ Dao"; if (instanceQQ == null) instanceQQ = new Dao(new DBHelper(context, DB_NAME_QQ, null, 6)); return instanceQQ; } if (DB_NAME_WE_CHAT.equals(dbName)) { TAG = "WeChat Dao"; if (instanceWeChat == null) instanceWeChat = new Dao(new DBHelper(context, DB_NAME_WE_CHAT, null, 6)); return instanceWeChat; } return null; } private void closeCursor() { if (cursor != null) cursor.close(); } private void createTableIfNotExists(String name) { String sqlCreateTable = "CREATE TABLE IF NOT EXISTS " + getSafeName(name) + " (" + Column_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
Column_SubName + " TEXT, " +
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/db/Dao.java
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls";
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages;
private Dao(DBHelper dbHelper) { db = dbHelper.getWritableDatabase(); } public static Dao getInstance(Context context, String dbName) { if (DB_NAME_QQ.equals(dbName)) { TAG = "QQ Dao"; if (instanceQQ == null) instanceQQ = new Dao(new DBHelper(context, DB_NAME_QQ, null, 6)); return instanceQQ; } if (DB_NAME_WE_CHAT.equals(dbName)) { TAG = "WeChat Dao"; if (instanceWeChat == null) instanceWeChat = new Dao(new DBHelper(context, DB_NAME_WE_CHAT, null, 6)); return instanceWeChat; } return null; } private void closeCursor() { if (cursor != null) cursor.close(); } private void createTableIfNotExists(String name) { String sqlCreateTable = "CREATE TABLE IF NOT EXISTS " + getSafeName(name) + " (" + Column_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Column_SubName + " TEXT, " +
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls"; // Path: app/src/main/java/com/qsboy/antirecall/db/Dao.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages; private Dao(DBHelper dbHelper) { db = dbHelper.getWritableDatabase(); } public static Dao getInstance(Context context, String dbName) { if (DB_NAME_QQ.equals(dbName)) { TAG = "QQ Dao"; if (instanceQQ == null) instanceQQ = new Dao(new DBHelper(context, DB_NAME_QQ, null, 6)); return instanceQQ; } if (DB_NAME_WE_CHAT.equals(dbName)) { TAG = "WeChat Dao"; if (instanceWeChat == null) instanceWeChat = new Dao(new DBHelper(context, DB_NAME_WE_CHAT, null, 6)); return instanceWeChat; } return null; } private void closeCursor() { if (cursor != null) cursor.close(); } private void createTableIfNotExists(String name) { String sqlCreateTable = "CREATE TABLE IF NOT EXISTS " + getSafeName(name) + " (" + Column_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Column_SubName + " TEXT, " +
Column_Message + " TEXT NOT NULL, " +
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/db/Dao.java
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls";
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages;
private Dao(DBHelper dbHelper) { db = dbHelper.getWritableDatabase(); } public static Dao getInstance(Context context, String dbName) { if (DB_NAME_QQ.equals(dbName)) { TAG = "QQ Dao"; if (instanceQQ == null) instanceQQ = new Dao(new DBHelper(context, DB_NAME_QQ, null, 6)); return instanceQQ; } if (DB_NAME_WE_CHAT.equals(dbName)) { TAG = "WeChat Dao"; if (instanceWeChat == null) instanceWeChat = new Dao(new DBHelper(context, DB_NAME_WE_CHAT, null, 6)); return instanceWeChat; } return null; } private void closeCursor() { if (cursor != null) cursor.close(); } private void createTableIfNotExists(String name) { String sqlCreateTable = "CREATE TABLE IF NOT EXISTS " + getSafeName(name) + " (" + Column_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Column_SubName + " TEXT, " + Column_Message + " TEXT NOT NULL, " +
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls"; // Path: app/src/main/java/com/qsboy/antirecall/db/Dao.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages; private Dao(DBHelper dbHelper) { db = dbHelper.getWritableDatabase(); } public static Dao getInstance(Context context, String dbName) { if (DB_NAME_QQ.equals(dbName)) { TAG = "QQ Dao"; if (instanceQQ == null) instanceQQ = new Dao(new DBHelper(context, DB_NAME_QQ, null, 6)); return instanceQQ; } if (DB_NAME_WE_CHAT.equals(dbName)) { TAG = "WeChat Dao"; if (instanceWeChat == null) instanceWeChat = new Dao(new DBHelper(context, DB_NAME_WE_CHAT, null, 6)); return instanceWeChat; } return null; } private void closeCursor() { if (cursor != null) cursor.close(); } private void createTableIfNotExists(String name) { String sqlCreateTable = "CREATE TABLE IF NOT EXISTS " + getSafeName(name) + " (" + Column_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Column_SubName + " TEXT, " + Column_Message + " TEXT NOT NULL, " +
Column_Time + " REAL NOT NULL)";
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/db/Dao.java
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls";
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages;
} /** * @param name 联系人名字 * @param subName 群昵称 * @param message 消息记录 */ public long addMessage(String name, String subName, String message) { return this.addMessage(name, subName, message, new Date().getTime()); } public long addMessage(String name, String subName, String message, long time) { if (subName == null || subName.equals("")) subName = name; createTableIfNotExists(name); ContentValues values = new ContentValues(); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); return db.insert(getSafeName(name), null, values); } public void addRecall(Messages messages) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages()); } public void addRecall(int originalID, String name, String subName, String message, long time, String images) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "]"); ContentValues values = new ContentValues();
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls"; // Path: app/src/main/java/com/qsboy/antirecall/db/Dao.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages; } /** * @param name 联系人名字 * @param subName 群昵称 * @param message 消息记录 */ public long addMessage(String name, String subName, String message) { return this.addMessage(name, subName, message, new Date().getTime()); } public long addMessage(String name, String subName, String message, long time) { if (subName == null || subName.equals("")) subName = name; createTableIfNotExists(name); ContentValues values = new ContentValues(); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); return db.insert(getSafeName(name), null, values); } public void addRecall(Messages messages) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages()); } public void addRecall(int originalID, String name, String subName, String message, long time, String images) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "]"); ContentValues values = new ContentValues();
values.put(Column_Original_ID, originalID);
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/db/Dao.java
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls";
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages;
/** * @param name 联系人名字 * @param subName 群昵称 * @param message 消息记录 */ public long addMessage(String name, String subName, String message) { return this.addMessage(name, subName, message, new Date().getTime()); } public long addMessage(String name, String subName, String message, long time) { if (subName == null || subName.equals("")) subName = name; createTableIfNotExists(name); ContentValues values = new ContentValues(); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); return db.insert(getSafeName(name), null, values); } public void addRecall(Messages messages) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages()); } public void addRecall(int originalID, String name, String subName, String message, long time, String images) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID);
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls"; // Path: app/src/main/java/com/qsboy/antirecall/db/Dao.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages; /** * @param name 联系人名字 * @param subName 群昵称 * @param message 消息记录 */ public long addMessage(String name, String subName, String message) { return this.addMessage(name, subName, message, new Date().getTime()); } public long addMessage(String name, String subName, String message, long time) { if (subName == null || subName.equals("")) subName = name; createTableIfNotExists(name); ContentValues values = new ContentValues(); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); return db.insert(getSafeName(name), null, values); } public void addRecall(Messages messages) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages()); } public void addRecall(int originalID, String name, String subName, String message, long time, String images) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID);
values.put(Column_Name, name);
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/db/Dao.java
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls";
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages;
* @param message 消息记录 */ public long addMessage(String name, String subName, String message) { return this.addMessage(name, subName, message, new Date().getTime()); } public long addMessage(String name, String subName, String message, long time) { if (subName == null || subName.equals("")) subName = name; createTableIfNotExists(name); ContentValues values = new ContentValues(); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); return db.insert(getSafeName(name), null, values); } public void addRecall(Messages messages) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages()); } public void addRecall(int originalID, String name, String subName, String message, long time, String images) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time);
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls"; // Path: app/src/main/java/com/qsboy/antirecall/db/Dao.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages; * @param message 消息记录 */ public long addMessage(String name, String subName, String message) { return this.addMessage(name, subName, message, new Date().getTime()); } public long addMessage(String name, String subName, String message, long time) { if (subName == null || subName.equals("")) subName = name; createTableIfNotExists(name); ContentValues values = new ContentValues(); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); return db.insert(getSafeName(name), null, values); } public void addRecall(Messages messages) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages()); } public void addRecall(int originalID, String name, String subName, String message, long time, String images) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time);
values.put(Column_Image, images);
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/db/Dao.java
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls";
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages;
public long addMessage(String name, String subName, String message) { return this.addMessage(name, subName, message, new Date().getTime()); } public long addMessage(String name, String subName, String message, long time) { if (subName == null || subName.equals("")) subName = name; createTableIfNotExists(name); ContentValues values = new ContentValues(); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); return db.insert(getSafeName(name), null, values); } public void addRecall(Messages messages) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages()); } public void addRecall(int originalID, String name, String subName, String message, long time, String images) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images);
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls"; // Path: app/src/main/java/com/qsboy/antirecall/db/Dao.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages; public long addMessage(String name, String subName, String message) { return this.addMessage(name, subName, message, new Date().getTime()); } public long addMessage(String name, String subName, String message, long time) { if (subName == null || subName.equals("")) subName = name; createTableIfNotExists(name); ContentValues values = new ContentValues(); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); return db.insert(getSafeName(name), null, values); } public void addRecall(Messages messages) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages()); } public void addRecall(int originalID, String name, String subName, String message, long time, String images) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images);
db.insert(Table_Recalled_Messages, null, values);
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/db/Dao.java
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls";
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages;
public void addRecall(int originalID, String name, String subName, String message, long time, String images) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images); db.insert(Table_Recalled_Messages, null, values); } public void addRecall(Messages messages, String nextMessage, String prevMessage, String nextSubName, String prevSubName) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages(), prevSubName, prevMessage, nextSubName, nextMessage); } public void addRecall(int originalID, String name, String subName, String message, long time, String images, String prevSubName, String prevMessage, String nextSubName, String nextMessage) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "], prevSubName = [" + prevSubName + "], prevMessage = [" + prevMessage + "], nextSubName = [" + nextSubName + "], nextMessage = [" + nextMessage + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images);
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls"; // Path: app/src/main/java/com/qsboy/antirecall/db/Dao.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages; public void addRecall(int originalID, String name, String subName, String message, long time, String images) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images); db.insert(Table_Recalled_Messages, null, values); } public void addRecall(Messages messages, String nextMessage, String prevMessage, String nextSubName, String prevSubName) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages(), prevSubName, prevMessage, nextSubName, nextMessage); } public void addRecall(int originalID, String name, String subName, String message, long time, String images, String prevSubName, String prevMessage, String nextSubName, String nextMessage) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "], prevSubName = [" + prevSubName + "], prevMessage = [" + prevMessage + "], nextSubName = [" + nextSubName + "], nextMessage = [" + nextMessage + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images);
values.put(Column_Prev_SubName, prevSubName);
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/db/Dao.java
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls";
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages;
Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images); db.insert(Table_Recalled_Messages, null, values); } public void addRecall(Messages messages, String nextMessage, String prevMessage, String nextSubName, String prevSubName) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages(), prevSubName, prevMessage, nextSubName, nextMessage); } public void addRecall(int originalID, String name, String subName, String message, long time, String images, String prevSubName, String prevMessage, String nextSubName, String nextMessage) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "], prevSubName = [" + prevSubName + "], prevMessage = [" + prevMessage + "], nextSubName = [" + nextSubName + "], nextMessage = [" + nextMessage + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images); values.put(Column_Prev_SubName, prevSubName);
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls"; // Path: app/src/main/java/com/qsboy/antirecall/db/Dao.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages; Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images); db.insert(Table_Recalled_Messages, null, values); } public void addRecall(Messages messages, String nextMessage, String prevMessage, String nextSubName, String prevSubName) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages(), prevSubName, prevMessage, nextSubName, nextMessage); } public void addRecall(int originalID, String name, String subName, String message, long time, String images, String prevSubName, String prevMessage, String nextSubName, String nextMessage) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "], prevSubName = [" + prevSubName + "], prevMessage = [" + prevMessage + "], nextSubName = [" + nextSubName + "], nextMessage = [" + nextMessage + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images); values.put(Column_Prev_SubName, prevSubName);
values.put(Column_Prev_Message, prevMessage);
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/db/Dao.java
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls";
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages;
ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images); db.insert(Table_Recalled_Messages, null, values); } public void addRecall(Messages messages, String nextMessage, String prevMessage, String nextSubName, String prevSubName) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages(), prevSubName, prevMessage, nextSubName, nextMessage); } public void addRecall(int originalID, String name, String subName, String message, long time, String images, String prevSubName, String prevMessage, String nextSubName, String nextMessage) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "], prevSubName = [" + prevSubName + "], prevMessage = [" + prevMessage + "], nextSubName = [" + nextSubName + "], nextMessage = [" + nextMessage + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images); values.put(Column_Prev_SubName, prevSubName); values.put(Column_Prev_Message, prevMessage);
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls"; // Path: app/src/main/java/com/qsboy/antirecall/db/Dao.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages; ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images); db.insert(Table_Recalled_Messages, null, values); } public void addRecall(Messages messages, String nextMessage, String prevMessage, String nextSubName, String prevSubName) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages(), prevSubName, prevMessage, nextSubName, nextMessage); } public void addRecall(int originalID, String name, String subName, String message, long time, String images, String prevSubName, String prevMessage, String nextSubName, String nextMessage) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "], prevSubName = [" + prevSubName + "], prevMessage = [" + prevMessage + "], nextSubName = [" + nextSubName + "], nextMessage = [" + nextMessage + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images); values.put(Column_Prev_SubName, prevSubName); values.put(Column_Prev_Message, prevMessage);
values.put(Column_Next_SubName, nextSubName);
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/db/Dao.java
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls";
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages;
ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images); db.insert(Table_Recalled_Messages, null, values); } public void addRecall(Messages messages, String nextMessage, String prevMessage, String nextSubName, String prevSubName) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages(), prevSubName, prevMessage, nextSubName, nextMessage); } public void addRecall(int originalID, String name, String subName, String message, long time, String images, String prevSubName, String prevMessage, String nextSubName, String nextMessage) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "], prevSubName = [" + prevSubName + "], prevMessage = [" + prevMessage + "], nextSubName = [" + nextSubName + "], nextMessage = [" + nextMessage + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images); values.put(Column_Prev_SubName, prevSubName); values.put(Column_Prev_Message, prevMessage); values.put(Column_Next_SubName, nextSubName);
// Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_ID = "id"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Image = "image"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Message = "message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Name = "name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_Message = "next_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Next_SubName = "next_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Original_ID = "original_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_Message = "prev_message"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Prev_SubName = "prev_sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_SubName = "sub_name"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Column_Time = "time"; // // Path: app/src/main/java/com/qsboy/antirecall/db/DBHelper.java // public static final String Table_Recalled_Messages = "recalls"; // Path: app/src/main/java/com/qsboy/antirecall/db/Dao.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static com.qsboy.antirecall.db.DBHelper.Column_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Image; import static com.qsboy.antirecall.db.DBHelper.Column_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Name; import static com.qsboy.antirecall.db.DBHelper.Column_Next_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Next_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Original_ID; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_Message; import static com.qsboy.antirecall.db.DBHelper.Column_Prev_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_SubName; import static com.qsboy.antirecall.db.DBHelper.Column_Time; import static com.qsboy.antirecall.db.DBHelper.Table_Recalled_Messages; ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images); db.insert(Table_Recalled_Messages, null, values); } public void addRecall(Messages messages, String nextMessage, String prevMessage, String nextSubName, String prevSubName) { this.addRecall(messages.getId(), messages.getName(), messages.getSubName(), messages.getText(), messages.getTime(), messages.getImages(), prevSubName, prevMessage, nextSubName, nextMessage); } public void addRecall(int originalID, String name, String subName, String message, long time, String images, String prevSubName, String prevMessage, String nextSubName, String nextMessage) { Log.d(TAG, "addRecall() called with: originalID = [" + originalID + "], name = [" + name + "], subName = [" + subName + "], message = [" + message + "], time = [" + time + "], prevSubName = [" + prevSubName + "], prevMessage = [" + prevMessage + "], nextSubName = [" + nextSubName + "], nextMessage = [" + nextMessage + "]"); ContentValues values = new ContentValues(); values.put(Column_Original_ID, originalID); values.put(Column_Name, name); values.put(Column_SubName, subName); values.put(Column_Message, message); values.put(Column_Time, time); values.put(Column_Image, images); values.put(Column_Prev_SubName, prevSubName); values.put(Column_Prev_Message, prevMessage); values.put(Column_Next_SubName, nextSubName);
values.put(Column_Next_Message, nextMessage);
JasonQS/Anti-recall
app/src/main/java/com/qsboy/antirecall/utils/XToast.java
// Path: app/src/main/java/com/qsboy/antirecall/utils/ImageHelper.java // public static Bitmap getBitmap(String file) { // Log.d(TAG, "getBitmap: " + file); // try { // FileInputStream fis = new FileInputStream(file); // return BitmapFactory.decodeStream(fis); // } catch (FileNotFoundException e) { // Log.w(TAG, "getBitmap: file not found: " + file); // return null; // } // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.PixelFormat; import android.os.Build; import android.os.Handler; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import com.qsboy.antirecall.R; import static com.qsboy.antirecall.utils.ImageHelper.getBitmap;
wm = (WindowManager) this.context.getSystemService(Context.WINDOW_SERVICE); handler = new Handler(); params = new WindowManager.LayoutParams(); params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM; params.height = WindowManager.LayoutParams.WRAP_CONTENT; params.width = WindowManager.LayoutParams.WRAP_CONTENT; params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; params.format = PixelFormat.TRANSLUCENT; params.windowAnimations = R.style.Animation_Toast; params.y = dip2px(context, y); if (Build.VERSION.SDK_INT >= 26) params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; else params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; } /** * 显示文字,如果传入的是图片,则去本地找到相应的图片显示 */ public static XToast build(Context context, String text) { XToast toast = new XToast(context); View view = LayoutInflater.from(context).inflate(R.layout.toast, null); ImageView iv = view.findViewById(R.id.toast_iv); TextView tv = view.findViewById(R.id.toast_tv); int i = text.indexOf("[图片]"); Log.i(TAG, "build: text: " + text); if (i >= 0 && text.length() > i + 4) { Log.w(TAG, "text : " + text); String imageName = text.substring(i + 4);
// Path: app/src/main/java/com/qsboy/antirecall/utils/ImageHelper.java // public static Bitmap getBitmap(String file) { // Log.d(TAG, "getBitmap: " + file); // try { // FileInputStream fis = new FileInputStream(file); // return BitmapFactory.decodeStream(fis); // } catch (FileNotFoundException e) { // Log.w(TAG, "getBitmap: file not found: " + file); // return null; // } // } // Path: app/src/main/java/com/qsboy/antirecall/utils/XToast.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.PixelFormat; import android.os.Build; import android.os.Handler; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import com.qsboy.antirecall.R; import static com.qsboy.antirecall.utils.ImageHelper.getBitmap; wm = (WindowManager) this.context.getSystemService(Context.WINDOW_SERVICE); handler = new Handler(); params = new WindowManager.LayoutParams(); params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM; params.height = WindowManager.LayoutParams.WRAP_CONTENT; params.width = WindowManager.LayoutParams.WRAP_CONTENT; params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; params.format = PixelFormat.TRANSLUCENT; params.windowAnimations = R.style.Animation_Toast; params.y = dip2px(context, y); if (Build.VERSION.SDK_INT >= 26) params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; else params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; } /** * 显示文字,如果传入的是图片,则去本地找到相应的图片显示 */ public static XToast build(Context context, String text) { XToast toast = new XToast(context); View view = LayoutInflater.from(context).inflate(R.layout.toast, null); ImageView iv = view.findViewById(R.id.toast_iv); TextView tv = view.findViewById(R.id.toast_tv); int i = text.indexOf("[图片]"); Log.i(TAG, "build: text: " + text); if (i >= 0 && text.length() > i + 4) { Log.w(TAG, "text : " + text); String imageName = text.substring(i + 4);
Bitmap bitmap = getBitmap(imageName);
twitter/hraven
hraven-core/src/test/java/com/twitter/hraven/datasource/TestFlowEventService.java
// Path: hraven-core/src/main/java/com/twitter/hraven/FlowKey.java // public class FlowKey extends AppKey implements Comparable<Object> { // // /** // * Identifying one single run of a version of an app. Smaller values indicate // * a later run. We're using an inverted timestamp Long.MAXVALUE - // * timstampMillis (milliseconds since January 1, 1970 UTC) // */ // protected long runId; // // @JsonCreator // public FlowKey(@JsonProperty("cluster") String cluster, // @JsonProperty("userName") String userName, // @JsonProperty("appId") String appId, // @JsonProperty("runId") long runId) { // super(cluster, userName, appId); // this.runId = runId; // } // // public FlowKey(FlowKey toCopy) { // this(toCopy.getCluster(), toCopy.getUserName(), toCopy.getAppId(), toCopy.getRunId()); // } // // /** // * Inverted version of {@link JobKey#getRunId()} // * used in the byte representation for reverse chronological sorting. // * @return // */ // public long getEncodedRunId() { // return encodeRunId(runId); // } // // /** // * Encodes the given timestamp for ordering by run ID // */ // public static long encodeRunId(long timestamp) { // return Long.MAX_VALUE - timestamp; // } // // /** // * @return Identifying one single run of a version of an app. A smaller value // * should indicate a later run. // */ // public long getRunId() { // return runId; // } // // public String toString() { // return super.toString() + Constants.SEP + this.getRunId(); // } // // /** // * Compares two FlowKey objects on the basis of // * their cluster, userName, appId and encodedRunId // * // * @param other // * @return 0 if this cluster, userName, appId and encodedRunId are equal to // * the other's cluster, userName, appId and encodedRunId, // * 1 if this cluster or userName or appId or encodedRunId are less than // * the other's cluster, userName, appId and encodedRunId, // * -1 if this cluster and userName and appId and encodedRunId are greater // * the other's cluster, userName, appId and encodedRunId, // * // */ // @Override // public int compareTo(Object other) { // if (other == null) { // return -1; // } // FlowKey otherKey = (FlowKey)other; // return new CompareToBuilder() // .appendSuper(super.compareTo(other)) // .append(getEncodedRunId(), otherKey.getEncodedRunId()) // .toComparison(); // } // // @Override // public boolean equals(Object other) { // if (other instanceof FlowKey) { // return compareTo((FlowKey)other) == 0; // } // return false; // } // // @Override // public int hashCode(){ // return new HashCodeBuilder() // .appendSuper(super.hashCode()) // .append(getEncodedRunId()) // .toHashCode(); // } // // }
import com.twitter.hraven.FlowKey; import com.twitter.hraven.Framework; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.twitter.hraven.FlowEvent; import com.twitter.hraven.FlowEventKey;
/* Copyright 2016 Twitter, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.twitter.hraven.datasource; /** */ public class TestFlowEventService { private static final String TEST_CLUSTER = "test@test"; private static final String TEST_USER = "testuser"; private static final String TEST_APP = "TestFlowEventService"; private static HBaseTestingUtility UTIL = new HBaseTestingUtility(); private static Connection hbaseConnection = null; @BeforeClass public static void setupBeforeClass() throws Exception { UTIL.startMiniCluster(); HRavenTestUtil.createFlowEventTable(UTIL); hbaseConnection = ConnectionFactory.createConnection(UTIL.getConfiguration()); } @AfterClass public static void tearDownAfterClass() throws Exception { try { if (hbaseConnection != null) { hbaseConnection.close(); } } finally { UTIL.shutdownMiniCluster(); } } @Test public void testFlowEventReadWrite() throws Exception { FlowEventService service = new FlowEventService(hbaseConnection); // setup some test data for a couple flows long flow1Run = System.currentTimeMillis();
// Path: hraven-core/src/main/java/com/twitter/hraven/FlowKey.java // public class FlowKey extends AppKey implements Comparable<Object> { // // /** // * Identifying one single run of a version of an app. Smaller values indicate // * a later run. We're using an inverted timestamp Long.MAXVALUE - // * timstampMillis (milliseconds since January 1, 1970 UTC) // */ // protected long runId; // // @JsonCreator // public FlowKey(@JsonProperty("cluster") String cluster, // @JsonProperty("userName") String userName, // @JsonProperty("appId") String appId, // @JsonProperty("runId") long runId) { // super(cluster, userName, appId); // this.runId = runId; // } // // public FlowKey(FlowKey toCopy) { // this(toCopy.getCluster(), toCopy.getUserName(), toCopy.getAppId(), toCopy.getRunId()); // } // // /** // * Inverted version of {@link JobKey#getRunId()} // * used in the byte representation for reverse chronological sorting. // * @return // */ // public long getEncodedRunId() { // return encodeRunId(runId); // } // // /** // * Encodes the given timestamp for ordering by run ID // */ // public static long encodeRunId(long timestamp) { // return Long.MAX_VALUE - timestamp; // } // // /** // * @return Identifying one single run of a version of an app. A smaller value // * should indicate a later run. // */ // public long getRunId() { // return runId; // } // // public String toString() { // return super.toString() + Constants.SEP + this.getRunId(); // } // // /** // * Compares two FlowKey objects on the basis of // * their cluster, userName, appId and encodedRunId // * // * @param other // * @return 0 if this cluster, userName, appId and encodedRunId are equal to // * the other's cluster, userName, appId and encodedRunId, // * 1 if this cluster or userName or appId or encodedRunId are less than // * the other's cluster, userName, appId and encodedRunId, // * -1 if this cluster and userName and appId and encodedRunId are greater // * the other's cluster, userName, appId and encodedRunId, // * // */ // @Override // public int compareTo(Object other) { // if (other == null) { // return -1; // } // FlowKey otherKey = (FlowKey)other; // return new CompareToBuilder() // .appendSuper(super.compareTo(other)) // .append(getEncodedRunId(), otherKey.getEncodedRunId()) // .toComparison(); // } // // @Override // public boolean equals(Object other) { // if (other instanceof FlowKey) { // return compareTo((FlowKey)other) == 0; // } // return false; // } // // @Override // public int hashCode(){ // return new HashCodeBuilder() // .appendSuper(super.hashCode()) // .append(getEncodedRunId()) // .toHashCode(); // } // // } // Path: hraven-core/src/test/java/com/twitter/hraven/datasource/TestFlowEventService.java import com.twitter.hraven.FlowKey; import com.twitter.hraven.Framework; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.twitter.hraven.FlowEvent; import com.twitter.hraven.FlowEventKey; /* Copyright 2016 Twitter, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.twitter.hraven.datasource; /** */ public class TestFlowEventService { private static final String TEST_CLUSTER = "test@test"; private static final String TEST_USER = "testuser"; private static final String TEST_APP = "TestFlowEventService"; private static HBaseTestingUtility UTIL = new HBaseTestingUtility(); private static Connection hbaseConnection = null; @BeforeClass public static void setupBeforeClass() throws Exception { UTIL.startMiniCluster(); HRavenTestUtil.createFlowEventTable(UTIL); hbaseConnection = ConnectionFactory.createConnection(UTIL.getConfiguration()); } @AfterClass public static void tearDownAfterClass() throws Exception { try { if (hbaseConnection != null) { hbaseConnection.close(); } } finally { UTIL.shutdownMiniCluster(); } } @Test public void testFlowEventReadWrite() throws Exception { FlowEventService service = new FlowEventService(hbaseConnection); // setup some test data for a couple flows long flow1Run = System.currentTimeMillis();
FlowKey flow1Key = new FlowKey(TEST_CLUSTER, TEST_USER, TEST_APP, flow1Run);
twitter/hraven
hraven-core/src/test/java/com/twitter/hraven/GenerateFlowTestData.java
// Path: hraven-core/src/main/java/com/twitter/hraven/datasource/JobHistoryByIdService.java // public class JobHistoryByIdService { // // private JobKeyConverter jobKeyConv = new JobKeyConverter(); // private QualifiedJobIdConverter jobIdConv = new QualifiedJobIdConverter(); // // // private final Configuration conf; // private final Connection hbaseConnection; // // /** // * Opens a new connection to HBase server and opens connections to the tables. // * // * User is responsible for calling {@link #close()} when finished using this // * service. // * @param hbaseConnection TODO // * // * @throws IOException // */ // public JobHistoryByIdService(Connection hbaseConnection) throws IOException { // this.hbaseConnection = hbaseConnection; // } // // /** // * Returns the JobKey for the job_history table, stored for this job ID, or // * {@code null} if not found. // * @param jobId the cluster and job ID combination to look up // * @return the JobKey instance stored, or {@code null} if not found // * @throws IOException if thrown by the HBase client // */ // public JobKey getJobKeyById(QualifiedJobId jobId) throws IOException { // byte[] indexKey = jobIdConv.toBytes(jobId); // // Get g = new Get(indexKey); // g.addColumn(Constants.INFO_FAM_BYTES, Constants.ROWKEY_COL_BYTES); // Table historyByJobIdTable = null; // // try { // historyByJobIdTable = hbaseConnection // .getTable(TableName.valueOf(Constants.HISTORY_BY_JOBID_TABLE)); // Result r = historyByJobIdTable.get(g); // if (r != null && !r.isEmpty()) { // byte[] historyKey = // r.getValue(Constants.INFO_FAM_BYTES, Constants.ROWKEY_COL_BYTES); // if (historyKey != null && historyKey.length > 0) { // return jobKeyConv.fromBytes(historyKey); // } // } // } finally { // if (historyByJobIdTable != null) { // historyByJobIdTable.close(); // } // } // return null; // } // // /** // * Create the secondary indexes records cluster!jobId->jobKey. // * // * @param jobKey // * @throws IOException if the entry cannot be written. // */ // public void writeIndexes(JobKey jobKey) throws IOException { // // Defensive coding // if (jobKey != null) { // Table historyByJobIdTable = null; // // try { // historyByJobIdTable = hbaseConnection // .getTable(TableName.valueOf(Constants.HISTORY_BY_JOBID_TABLE)); // byte[] jobKeyBytes = jobKeyConv.toBytes(jobKey); // byte[] rowKeyBytes = jobIdConv.toBytes( // new QualifiedJobId(jobKey.getCluster(), jobKey.getJobId())); // // // Insert (or update) row with jobid as the key // Put p = new Put(rowKeyBytes); // p.addColumn(Constants.INFO_FAM_BYTES, Constants.ROWKEY_COL_BYTES, // jobKeyBytes); // historyByJobIdTable.put(p); // } finally { // if (historyByJobIdTable != null) { // historyByJobIdTable.close(); // } // } // } // } // // }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.util.Bytes; import com.twitter.hraven.datasource.JobHistoryByIdService; import com.twitter.hraven.datasource.JobKeyConverter;
/* Copyright 2016 Twitter, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.twitter.hraven; /** * Stores data in job_history table * also retrieves flow stats */ public class GenerateFlowTestData { @SuppressWarnings("unused") private static Log LOG = LogFactory.getLog(GenerateFlowTestData.class); /** Default dummy configuration properties */ private static Map<String,String> DEFAULT_CONFIG = new HashMap<String,String>(); static { DEFAULT_CONFIG.put("testproperty1", "value1"); DEFAULT_CONFIG.put("testproperty2", "value2"); } private int jobIdCnt; public static int SUBMIT_LAUCH_DIFF = 500 ; // TODO: change method signature to get rid of table and pass a connection instead public void loadFlow(String cluster, String user, String app, long runId, String version, int jobCount, long baseStats,
// Path: hraven-core/src/main/java/com/twitter/hraven/datasource/JobHistoryByIdService.java // public class JobHistoryByIdService { // // private JobKeyConverter jobKeyConv = new JobKeyConverter(); // private QualifiedJobIdConverter jobIdConv = new QualifiedJobIdConverter(); // // // private final Configuration conf; // private final Connection hbaseConnection; // // /** // * Opens a new connection to HBase server and opens connections to the tables. // * // * User is responsible for calling {@link #close()} when finished using this // * service. // * @param hbaseConnection TODO // * // * @throws IOException // */ // public JobHistoryByIdService(Connection hbaseConnection) throws IOException { // this.hbaseConnection = hbaseConnection; // } // // /** // * Returns the JobKey for the job_history table, stored for this job ID, or // * {@code null} if not found. // * @param jobId the cluster and job ID combination to look up // * @return the JobKey instance stored, or {@code null} if not found // * @throws IOException if thrown by the HBase client // */ // public JobKey getJobKeyById(QualifiedJobId jobId) throws IOException { // byte[] indexKey = jobIdConv.toBytes(jobId); // // Get g = new Get(indexKey); // g.addColumn(Constants.INFO_FAM_BYTES, Constants.ROWKEY_COL_BYTES); // Table historyByJobIdTable = null; // // try { // historyByJobIdTable = hbaseConnection // .getTable(TableName.valueOf(Constants.HISTORY_BY_JOBID_TABLE)); // Result r = historyByJobIdTable.get(g); // if (r != null && !r.isEmpty()) { // byte[] historyKey = // r.getValue(Constants.INFO_FAM_BYTES, Constants.ROWKEY_COL_BYTES); // if (historyKey != null && historyKey.length > 0) { // return jobKeyConv.fromBytes(historyKey); // } // } // } finally { // if (historyByJobIdTable != null) { // historyByJobIdTable.close(); // } // } // return null; // } // // /** // * Create the secondary indexes records cluster!jobId->jobKey. // * // * @param jobKey // * @throws IOException if the entry cannot be written. // */ // public void writeIndexes(JobKey jobKey) throws IOException { // // Defensive coding // if (jobKey != null) { // Table historyByJobIdTable = null; // // try { // historyByJobIdTable = hbaseConnection // .getTable(TableName.valueOf(Constants.HISTORY_BY_JOBID_TABLE)); // byte[] jobKeyBytes = jobKeyConv.toBytes(jobKey); // byte[] rowKeyBytes = jobIdConv.toBytes( // new QualifiedJobId(jobKey.getCluster(), jobKey.getJobId())); // // // Insert (or update) row with jobid as the key // Put p = new Put(rowKeyBytes); // p.addColumn(Constants.INFO_FAM_BYTES, Constants.ROWKEY_COL_BYTES, // jobKeyBytes); // historyByJobIdTable.put(p); // } finally { // if (historyByJobIdTable != null) { // historyByJobIdTable.close(); // } // } // } // } // // } // Path: hraven-core/src/test/java/com/twitter/hraven/GenerateFlowTestData.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.util.Bytes; import com.twitter.hraven.datasource.JobHistoryByIdService; import com.twitter.hraven.datasource.JobKeyConverter; /* Copyright 2016 Twitter, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.twitter.hraven; /** * Stores data in job_history table * also retrieves flow stats */ public class GenerateFlowTestData { @SuppressWarnings("unused") private static Log LOG = LogFactory.getLog(GenerateFlowTestData.class); /** Default dummy configuration properties */ private static Map<String,String> DEFAULT_CONFIG = new HashMap<String,String>(); static { DEFAULT_CONFIG.put("testproperty1", "value1"); DEFAULT_CONFIG.put("testproperty2", "value2"); } private int jobIdCnt; public static int SUBMIT_LAUCH_DIFF = 500 ; // TODO: change method signature to get rid of table and pass a connection instead public void loadFlow(String cluster, String user, String app, long runId, String version, int jobCount, long baseStats,
JobHistoryByIdService idService, Table historyTable)
xiaolongzuo/deerlet-redis-client
src/test/java/com/zuoxiaolong/deerlet/redis/client/DeerletRedisClientStringTest.java
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Bit.java // public enum Bit { // // zero { // @Override // public int value() { // return 0; // } // },one { // @Override // public int value() { // return 1; // } // }; // // public abstract int value(); // // public String toString(){ // return String.valueOf(value()); // } // // public static Bit create(int i) { // if (i == 0) { // return Bit.zero; // } else if (i == 1) { // return Bit.one; // } else { // return null; // } // } // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/BitopOperations.java // public enum BitopOperations { // // and { // @Override // public int operate(int i, int j) { // return i & j; // } // },or { // @Override // public int operate(int i, int j) { // return i | j; // } // },not { // @Override // public int operate(int i, int j) { // return 1 - i; // } // },xor { // @Override // public int operate(int i, int j) { // return i ^ j; // } // }; // // public abstract int operate(int i, int j); // }
import java.io.IOException; import java.util.List; import com.zuoxiaolong.deerlet.redis.client.command.Bit; import com.zuoxiaolong.deerlet.redis.client.command.BitopOperations; import junit.framework.Assert; import org.junit.Test;
package com.zuoxiaolong.deerlet.redis.client; /** * * 测试客户端是否可以正常工作 * * @author zuoxiaolong * @since 2015 2015年3月6日 下午11:45:23 * */ public class DeerletRedisClientStringTest extends AbstractDeerletRedisClientTest { @Test public void testAppend() throws IOException { Assert.assertTrue(deerletRedisClient.set("testKey", "testValue")); int length = deerletRedisClient.append("testKey", "Append"); Assert.assertEquals("testValue".length() + "Append".length(), length); Assert.assertEquals("testValueAppend", deerletRedisClient.get("testKey")); } @Test public void testBitcount() throws IOException {
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Bit.java // public enum Bit { // // zero { // @Override // public int value() { // return 0; // } // },one { // @Override // public int value() { // return 1; // } // }; // // public abstract int value(); // // public String toString(){ // return String.valueOf(value()); // } // // public static Bit create(int i) { // if (i == 0) { // return Bit.zero; // } else if (i == 1) { // return Bit.one; // } else { // return null; // } // } // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/BitopOperations.java // public enum BitopOperations { // // and { // @Override // public int operate(int i, int j) { // return i & j; // } // },or { // @Override // public int operate(int i, int j) { // return i | j; // } // },not { // @Override // public int operate(int i, int j) { // return 1 - i; // } // },xor { // @Override // public int operate(int i, int j) { // return i ^ j; // } // }; // // public abstract int operate(int i, int j); // } // Path: src/test/java/com/zuoxiaolong/deerlet/redis/client/DeerletRedisClientStringTest.java import java.io.IOException; import java.util.List; import com.zuoxiaolong.deerlet.redis.client.command.Bit; import com.zuoxiaolong.deerlet.redis.client.command.BitopOperations; import junit.framework.Assert; import org.junit.Test; package com.zuoxiaolong.deerlet.redis.client; /** * * 测试客户端是否可以正常工作 * * @author zuoxiaolong * @since 2015 2015年3月6日 下午11:45:23 * */ public class DeerletRedisClientStringTest extends AbstractDeerletRedisClientTest { @Test public void testAppend() throws IOException { Assert.assertTrue(deerletRedisClient.set("testKey", "testValue")); int length = deerletRedisClient.append("testKey", "Append"); Assert.assertEquals("testValue".length() + "Append".length(), length); Assert.assertEquals("testValueAppend", deerletRedisClient.get("testKey")); } @Test public void testBitcount() throws IOException {
deerletRedisClient.setbit("testKey", 0, Bit.one);
xiaolongzuo/deerlet-redis-client
src/test/java/com/zuoxiaolong/deerlet/redis/client/DeerletRedisClientStringTest.java
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Bit.java // public enum Bit { // // zero { // @Override // public int value() { // return 0; // } // },one { // @Override // public int value() { // return 1; // } // }; // // public abstract int value(); // // public String toString(){ // return String.valueOf(value()); // } // // public static Bit create(int i) { // if (i == 0) { // return Bit.zero; // } else if (i == 1) { // return Bit.one; // } else { // return null; // } // } // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/BitopOperations.java // public enum BitopOperations { // // and { // @Override // public int operate(int i, int j) { // return i & j; // } // },or { // @Override // public int operate(int i, int j) { // return i | j; // } // },not { // @Override // public int operate(int i, int j) { // return 1 - i; // } // },xor { // @Override // public int operate(int i, int j) { // return i ^ j; // } // }; // // public abstract int operate(int i, int j); // }
import java.io.IOException; import java.util.List; import com.zuoxiaolong.deerlet.redis.client.command.Bit; import com.zuoxiaolong.deerlet.redis.client.command.BitopOperations; import junit.framework.Assert; import org.junit.Test;
package com.zuoxiaolong.deerlet.redis.client; /** * * 测试客户端是否可以正常工作 * * @author zuoxiaolong * @since 2015 2015年3月6日 下午11:45:23 * */ public class DeerletRedisClientStringTest extends AbstractDeerletRedisClientTest { @Test public void testAppend() throws IOException { Assert.assertTrue(deerletRedisClient.set("testKey", "testValue")); int length = deerletRedisClient.append("testKey", "Append"); Assert.assertEquals("testValue".length() + "Append".length(), length); Assert.assertEquals("testValueAppend", deerletRedisClient.get("testKey")); } @Test public void testBitcount() throws IOException { deerletRedisClient.setbit("testKey", 0, Bit.one); Assert.assertEquals(1, deerletRedisClient.bitcount("testKey", 0, 0)); deerletRedisClient.setbit("testKey", 1, Bit.one); deerletRedisClient.setbit("testKey", 2, Bit.zero); deerletRedisClient.setbit("testKey", 3, Bit.one); Assert.assertEquals(3, deerletRedisClient.bitcount("testKey", 0, 4)); } @Test public void testBitop() throws IOException { deerletRedisClient.setbit("testKey1", 0, Bit.one); deerletRedisClient.setbit("testKey1", 1, Bit.one); deerletRedisClient.setbit("testKey1", 2, Bit.zero); deerletRedisClient.setbit("testKey1", 3, Bit.one); deerletRedisClient.setbit("testKey2", 0, Bit.zero); deerletRedisClient.setbit("testKey2", 1, Bit.one); deerletRedisClient.setbit("testKey2", 2, Bit.one); deerletRedisClient.setbit("testKey2", 3, Bit.one);
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Bit.java // public enum Bit { // // zero { // @Override // public int value() { // return 0; // } // },one { // @Override // public int value() { // return 1; // } // }; // // public abstract int value(); // // public String toString(){ // return String.valueOf(value()); // } // // public static Bit create(int i) { // if (i == 0) { // return Bit.zero; // } else if (i == 1) { // return Bit.one; // } else { // return null; // } // } // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/BitopOperations.java // public enum BitopOperations { // // and { // @Override // public int operate(int i, int j) { // return i & j; // } // },or { // @Override // public int operate(int i, int j) { // return i | j; // } // },not { // @Override // public int operate(int i, int j) { // return 1 - i; // } // },xor { // @Override // public int operate(int i, int j) { // return i ^ j; // } // }; // // public abstract int operate(int i, int j); // } // Path: src/test/java/com/zuoxiaolong/deerlet/redis/client/DeerletRedisClientStringTest.java import java.io.IOException; import java.util.List; import com.zuoxiaolong.deerlet.redis.client.command.Bit; import com.zuoxiaolong.deerlet.redis.client.command.BitopOperations; import junit.framework.Assert; import org.junit.Test; package com.zuoxiaolong.deerlet.redis.client; /** * * 测试客户端是否可以正常工作 * * @author zuoxiaolong * @since 2015 2015年3月6日 下午11:45:23 * */ public class DeerletRedisClientStringTest extends AbstractDeerletRedisClientTest { @Test public void testAppend() throws IOException { Assert.assertTrue(deerletRedisClient.set("testKey", "testValue")); int length = deerletRedisClient.append("testKey", "Append"); Assert.assertEquals("testValue".length() + "Append".length(), length); Assert.assertEquals("testValueAppend", deerletRedisClient.get("testKey")); } @Test public void testBitcount() throws IOException { deerletRedisClient.setbit("testKey", 0, Bit.one); Assert.assertEquals(1, deerletRedisClient.bitcount("testKey", 0, 0)); deerletRedisClient.setbit("testKey", 1, Bit.one); deerletRedisClient.setbit("testKey", 2, Bit.zero); deerletRedisClient.setbit("testKey", 3, Bit.one); Assert.assertEquals(3, deerletRedisClient.bitcount("testKey", 0, 4)); } @Test public void testBitop() throws IOException { deerletRedisClient.setbit("testKey1", 0, Bit.one); deerletRedisClient.setbit("testKey1", 1, Bit.one); deerletRedisClient.setbit("testKey1", 2, Bit.zero); deerletRedisClient.setbit("testKey1", 3, Bit.one); deerletRedisClient.setbit("testKey2", 0, Bit.zero); deerletRedisClient.setbit("testKey2", 1, Bit.one); deerletRedisClient.setbit("testKey2", 2, Bit.one); deerletRedisClient.setbit("testKey2", 3, Bit.one);
Assert.assertEquals(1, deerletRedisClient.bitop(BitopOperations.and, "testKey", "testKey1", "testKey2"));
xiaolongzuo/deerlet-redis-client
src/test/java/com/zuoxiaolong/deerlet/redis/client/DeerletRedisClientKeyTest.java
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Cursor.java // public interface Cursor { // // List<Integer> getCursorList(); // // List<String> getResultList(); // // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/ObjectSubcommands.java // public enum ObjectSubcommands { // // refcount,idletime,encoding // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Types.java // public enum Types { // // none,string,list,set,zset,hash // // }
import com.zuoxiaolong.deerlet.redis.client.command.Cursor; import com.zuoxiaolong.deerlet.redis.client.command.ObjectSubcommands; import com.zuoxiaolong.deerlet.redis.client.command.Types; import junit.framework.Assert; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List;
} List<String> list = deerletRedisClient.keys("*"); Assert.assertNotNull(list); Assert.assertEquals(1000, list.size()); for (int i = 0; i < 1000; i++) { Assert.assertEquals(true, list.contains("testKey" + i)); } } @Test public void testMigrate() { Assert.assertTrue(deerletRedisClient.set("testKey", "TestValue")); Assert.assertTrue(deerletRedisClient.migrate("localhost", "6666", "testKey", 0, -1)); Assert.assertEquals("TestValue", otherDeerletRedisClient.get("testKey")); Assert.assertNull(deerletRedisClient.get("testKey")); } @Test public void testMove() { Assert.assertTrue(deerletRedisClient.set("testKey", "TestValue")); Assert.assertTrue(deerletRedisClient.move("testKey", 1)); Assert.assertTrue(deerletRedisClient.select(1)); Assert.assertEquals("TestValue", deerletRedisClient.get("testKey")); Assert.assertTrue(deerletRedisClient.select(0)); Assert.assertNull(deerletRedisClient.get("testKey")); } @Test public void testObject() throws InterruptedException { Assert.assertTrue(deerletRedisClient.set("testKey", "TestValue"));
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Cursor.java // public interface Cursor { // // List<Integer> getCursorList(); // // List<String> getResultList(); // // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/ObjectSubcommands.java // public enum ObjectSubcommands { // // refcount,idletime,encoding // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Types.java // public enum Types { // // none,string,list,set,zset,hash // // } // Path: src/test/java/com/zuoxiaolong/deerlet/redis/client/DeerletRedisClientKeyTest.java import com.zuoxiaolong.deerlet.redis.client.command.Cursor; import com.zuoxiaolong.deerlet.redis.client.command.ObjectSubcommands; import com.zuoxiaolong.deerlet.redis.client.command.Types; import junit.framework.Assert; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List; } List<String> list = deerletRedisClient.keys("*"); Assert.assertNotNull(list); Assert.assertEquals(1000, list.size()); for (int i = 0; i < 1000; i++) { Assert.assertEquals(true, list.contains("testKey" + i)); } } @Test public void testMigrate() { Assert.assertTrue(deerletRedisClient.set("testKey", "TestValue")); Assert.assertTrue(deerletRedisClient.migrate("localhost", "6666", "testKey", 0, -1)); Assert.assertEquals("TestValue", otherDeerletRedisClient.get("testKey")); Assert.assertNull(deerletRedisClient.get("testKey")); } @Test public void testMove() { Assert.assertTrue(deerletRedisClient.set("testKey", "TestValue")); Assert.assertTrue(deerletRedisClient.move("testKey", 1)); Assert.assertTrue(deerletRedisClient.select(1)); Assert.assertEquals("TestValue", deerletRedisClient.get("testKey")); Assert.assertTrue(deerletRedisClient.select(0)); Assert.assertNull(deerletRedisClient.get("testKey")); } @Test public void testObject() throws InterruptedException { Assert.assertTrue(deerletRedisClient.set("testKey", "TestValue"));
Assert.assertEquals(1, deerletRedisClient.object(ObjectSubcommands.refcount, "testKey"));
xiaolongzuo/deerlet-redis-client
src/test/java/com/zuoxiaolong/deerlet/redis/client/DeerletRedisClientKeyTest.java
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Cursor.java // public interface Cursor { // // List<Integer> getCursorList(); // // List<String> getResultList(); // // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/ObjectSubcommands.java // public enum ObjectSubcommands { // // refcount,idletime,encoding // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Types.java // public enum Types { // // none,string,list,set,zset,hash // // }
import com.zuoxiaolong.deerlet.redis.client.command.Cursor; import com.zuoxiaolong.deerlet.redis.client.command.ObjectSubcommands; import com.zuoxiaolong.deerlet.redis.client.command.Types; import junit.framework.Assert; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List;
Assert.assertFalse(deerletRedisClient.exists("testKey")); Assert.assertFalse(deerletRedisClient.renamenx("testKey1","testKey2")); } @Test public void testRestore() throws UnsupportedEncodingException { testDump(); } @Test public void testSort() throws UnsupportedEncodingException { Assert.assertEquals(5, deerletRedisClient.lpush("listKey", 4,3,5,1,2)); List<String> list = deerletRedisClient.sort("listKey", new Object[]{}); for (int i = 1; i < list.size() + 1; i++) { Assert.assertEquals(i, Integer.valueOf(list.get(i - 1)).intValue()); } } @Test public void testTtl() throws InterruptedException { Assert.assertTrue(deerletRedisClient.set("testKey", "TestValue")); Assert.assertEquals(-1, deerletRedisClient.ttl("testKey")); Assert.assertEquals(-2, deerletRedisClient.ttl("none")); Assert.assertTrue(deerletRedisClient.expire("testKey", 5)); Assert.assertEquals(true, deerletRedisClient.ttl("testKey") > 2); } @Test public void testType() { Assert.assertTrue(deerletRedisClient.set("testKey", "TestValue"));
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Cursor.java // public interface Cursor { // // List<Integer> getCursorList(); // // List<String> getResultList(); // // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/ObjectSubcommands.java // public enum ObjectSubcommands { // // refcount,idletime,encoding // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Types.java // public enum Types { // // none,string,list,set,zset,hash // // } // Path: src/test/java/com/zuoxiaolong/deerlet/redis/client/DeerletRedisClientKeyTest.java import com.zuoxiaolong.deerlet.redis.client.command.Cursor; import com.zuoxiaolong.deerlet.redis.client.command.ObjectSubcommands; import com.zuoxiaolong.deerlet.redis.client.command.Types; import junit.framework.Assert; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List; Assert.assertFalse(deerletRedisClient.exists("testKey")); Assert.assertFalse(deerletRedisClient.renamenx("testKey1","testKey2")); } @Test public void testRestore() throws UnsupportedEncodingException { testDump(); } @Test public void testSort() throws UnsupportedEncodingException { Assert.assertEquals(5, deerletRedisClient.lpush("listKey", 4,3,5,1,2)); List<String> list = deerletRedisClient.sort("listKey", new Object[]{}); for (int i = 1; i < list.size() + 1; i++) { Assert.assertEquals(i, Integer.valueOf(list.get(i - 1)).intValue()); } } @Test public void testTtl() throws InterruptedException { Assert.assertTrue(deerletRedisClient.set("testKey", "TestValue")); Assert.assertEquals(-1, deerletRedisClient.ttl("testKey")); Assert.assertEquals(-2, deerletRedisClient.ttl("none")); Assert.assertTrue(deerletRedisClient.expire("testKey", 5)); Assert.assertEquals(true, deerletRedisClient.ttl("testKey") > 2); } @Test public void testType() { Assert.assertTrue(deerletRedisClient.set("testKey", "TestValue"));
Assert.assertEquals(Types.string, deerletRedisClient.type("testKey"));
xiaolongzuo/deerlet-redis-client
src/test/java/com/zuoxiaolong/deerlet/redis/client/DeerletRedisClientKeyTest.java
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Cursor.java // public interface Cursor { // // List<Integer> getCursorList(); // // List<String> getResultList(); // // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/ObjectSubcommands.java // public enum ObjectSubcommands { // // refcount,idletime,encoding // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Types.java // public enum Types { // // none,string,list,set,zset,hash // // }
import com.zuoxiaolong.deerlet.redis.client.command.Cursor; import com.zuoxiaolong.deerlet.redis.client.command.ObjectSubcommands; import com.zuoxiaolong.deerlet.redis.client.command.Types; import junit.framework.Assert; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List;
for (int i = 1; i < list.size() + 1; i++) { Assert.assertEquals(i, Integer.valueOf(list.get(i - 1)).intValue()); } } @Test public void testTtl() throws InterruptedException { Assert.assertTrue(deerletRedisClient.set("testKey", "TestValue")); Assert.assertEquals(-1, deerletRedisClient.ttl("testKey")); Assert.assertEquals(-2, deerletRedisClient.ttl("none")); Assert.assertTrue(deerletRedisClient.expire("testKey", 5)); Assert.assertEquals(true, deerletRedisClient.ttl("testKey") > 2); } @Test public void testType() { Assert.assertTrue(deerletRedisClient.set("testKey", "TestValue")); Assert.assertEquals(Types.string, deerletRedisClient.type("testKey")); Assert.assertTrue(deerletRedisClient.set("testKey", 1)); Assert.assertEquals(Types.string, deerletRedisClient.type("testKey")); Assert.assertTrue(deerletRedisClient.lpush("listKey", 1,1,1) > 0); Assert.assertEquals(Types.list, deerletRedisClient.type("listKey")); } @Test public void testScan() { for (int i = 0; i < 1000; i++) { Assert.assertTrue(deerletRedisClient.set("testKey" + i, "TestValue")); } Assert.assertEquals(1000, deerletRedisClient.dbsize());
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Cursor.java // public interface Cursor { // // List<Integer> getCursorList(); // // List<String> getResultList(); // // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/ObjectSubcommands.java // public enum ObjectSubcommands { // // refcount,idletime,encoding // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/command/Types.java // public enum Types { // // none,string,list,set,zset,hash // // } // Path: src/test/java/com/zuoxiaolong/deerlet/redis/client/DeerletRedisClientKeyTest.java import com.zuoxiaolong.deerlet.redis.client.command.Cursor; import com.zuoxiaolong.deerlet.redis.client.command.ObjectSubcommands; import com.zuoxiaolong.deerlet.redis.client.command.Types; import junit.framework.Assert; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List; for (int i = 1; i < list.size() + 1; i++) { Assert.assertEquals(i, Integer.valueOf(list.get(i - 1)).intValue()); } } @Test public void testTtl() throws InterruptedException { Assert.assertTrue(deerletRedisClient.set("testKey", "TestValue")); Assert.assertEquals(-1, deerletRedisClient.ttl("testKey")); Assert.assertEquals(-2, deerletRedisClient.ttl("none")); Assert.assertTrue(deerletRedisClient.expire("testKey", 5)); Assert.assertEquals(true, deerletRedisClient.ttl("testKey") > 2); } @Test public void testType() { Assert.assertTrue(deerletRedisClient.set("testKey", "TestValue")); Assert.assertEquals(Types.string, deerletRedisClient.type("testKey")); Assert.assertTrue(deerletRedisClient.set("testKey", 1)); Assert.assertEquals(Types.string, deerletRedisClient.type("testKey")); Assert.assertTrue(deerletRedisClient.lpush("listKey", 1,1,1) > 0); Assert.assertEquals(Types.list, deerletRedisClient.type("listKey")); } @Test public void testScan() { for (int i = 0; i < 1000; i++) { Assert.assertTrue(deerletRedisClient.set("testKey" + i, "TestValue")); } Assert.assertEquals(1000, deerletRedisClient.dbsize());
Cursor cursor = deerletRedisClient.scan(null, null, 100);
xiaolongzuo/deerlet-redis-client
src/test/java/com/zuoxiaolong/deerlet/redis/client/strategy/ConsistencyHashTest.java
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/ConnectionPool.java // public interface ConnectionPool { // // public Connection obtainConnection(); // // public void releaseConnection(Connection connection); // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/impl/ConnectionPoolImpl.java // public class ConnectionPoolImpl implements ConnectionPool { // // private LinkedList<Connection> connectionPool; // // private ReentrantLock lock = new ReentrantLock(); // // private Condition notEmpty = lock.newCondition(); // // private int maxSize; // // private int minIdleSize; // // private int maxIdleSize; // // private int totalSize; // // private Server server; // // public ConnectionPoolImpl(Server server,int initSize, int maxSize, int minIdleSize, int maxIdleSize) { // if (initSize < minIdleSize || maxSize < initSize || maxSize < minIdleSize || maxIdleSize < minIdleSize || maxSize < maxIdleSize) { // throw new IllegalArgumentException("must (initSize < minIdleSize) && (maxSize < initSize) && (maxSize < minIdleSize) && (maxIdleSize < minIdleSize) && (maxSize < maxIdleSize)"); // } // if (server == null) { // throw new IllegalArgumentException("server can't be null!"); // } // this.server = server; // connectionPool = new LinkedList<Connection>(); // incrementPool(initSize); // this.maxSize = maxSize; // this.minIdleSize = minIdleSize; // this.maxIdleSize = maxIdleSize; // } // // @Override // public Connection obtainConnection() { // extend(); // Connection connection = null; // if (connectionPool.size() > 0) { // lock.lock(); // try { // if (connectionPool.size() > 0) { // connection = connectionPool.removeLast(); // } // } finally { // lock.unlock(); // } // } // while (connection == null) { // lock.lock(); // try { // notEmpty.await(); // if (connectionPool.size() > 0) { // connection = connectionPool.removeLast(); // } // } catch (InterruptedException e) { // throw new RuntimeException(e); // }finally { // lock.unlock(); // } // } // return connection; // } // // private void extend() { // if (connectionPool.size() < minIdleSize) { // lock.lock(); // try { // if (connectionPool.size() < minIdleSize) { // incrementPool(minIdleSize - connectionPool.size() + 1); // } // } finally { // lock.unlock(); // } // } // } // // @Override // public void releaseConnection(Connection connection) { // if (!(connection instanceof ConnectionProxy)) { // throw new RuntimeException("released connection must be proxied!"); // } // lock.lock(); // try { // connectionPool.add(connection); // notEmpty.signal(); // } finally { // lock.unlock(); // } // if (connectionPool.size() > maxIdleSize) { // lock.lock(); // try { // if (connectionPool.size() > maxIdleSize) { // decrementPool(connectionPool.size() - maxIdleSize); // } // } finally { // lock.unlock(); // } // } // } // // private void incrementPool(int number) { // if (totalSize >= maxSize) { // return; // } // if (maxSize - totalSize < number) { // number = maxSize - totalSize; // } // lock.lock(); // try { // for (int i = 0; i < number; i++) { // connectionPool.add(newConnection()); // totalSize++; // } // } catch (IOException e) { // throw new RuntimeException(e); // } finally { // lock.unlock(); // } // } // // private void decrementPool(int number) { // lock.lock(); // try { // for (int i = 0; i < number; i++) { // try { // ((ConnectionProxy) connectionPool.removeLast()).realClose(); // } catch (NoSuchElementException e) { // break; // } // totalSize--; // } // } finally { // lock.unlock(); // } // } // // private Connection newConnection() throws IOException { // return new ConnectionProxy(new ConnectionImpl(server), this); // } // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/config/Servers.java // public abstract class Servers { // // public static Server newServer(String host,int port) { // return new DefaultServer(host, port); // } // // }
import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.zuoxiaolong.deerlet.redis.client.connection.ConnectionPool; import com.zuoxiaolong.deerlet.redis.client.connection.impl.ConnectionPoolImpl; import org.junit.Assert; import org.junit.Test; import com.zuoxiaolong.deerlet.redis.client.config.Servers;
package com.zuoxiaolong.deerlet.redis.client.strategy; /** * <p> * <p/> * </p> * * @author 左潇龙 * @since 4/27/2015 5:30 PM */ public class ConsistencyHashTest { @Test public void testConsistencyHash() {
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/ConnectionPool.java // public interface ConnectionPool { // // public Connection obtainConnection(); // // public void releaseConnection(Connection connection); // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/impl/ConnectionPoolImpl.java // public class ConnectionPoolImpl implements ConnectionPool { // // private LinkedList<Connection> connectionPool; // // private ReentrantLock lock = new ReentrantLock(); // // private Condition notEmpty = lock.newCondition(); // // private int maxSize; // // private int minIdleSize; // // private int maxIdleSize; // // private int totalSize; // // private Server server; // // public ConnectionPoolImpl(Server server,int initSize, int maxSize, int minIdleSize, int maxIdleSize) { // if (initSize < minIdleSize || maxSize < initSize || maxSize < minIdleSize || maxIdleSize < minIdleSize || maxSize < maxIdleSize) { // throw new IllegalArgumentException("must (initSize < minIdleSize) && (maxSize < initSize) && (maxSize < minIdleSize) && (maxIdleSize < minIdleSize) && (maxSize < maxIdleSize)"); // } // if (server == null) { // throw new IllegalArgumentException("server can't be null!"); // } // this.server = server; // connectionPool = new LinkedList<Connection>(); // incrementPool(initSize); // this.maxSize = maxSize; // this.minIdleSize = minIdleSize; // this.maxIdleSize = maxIdleSize; // } // // @Override // public Connection obtainConnection() { // extend(); // Connection connection = null; // if (connectionPool.size() > 0) { // lock.lock(); // try { // if (connectionPool.size() > 0) { // connection = connectionPool.removeLast(); // } // } finally { // lock.unlock(); // } // } // while (connection == null) { // lock.lock(); // try { // notEmpty.await(); // if (connectionPool.size() > 0) { // connection = connectionPool.removeLast(); // } // } catch (InterruptedException e) { // throw new RuntimeException(e); // }finally { // lock.unlock(); // } // } // return connection; // } // // private void extend() { // if (connectionPool.size() < minIdleSize) { // lock.lock(); // try { // if (connectionPool.size() < minIdleSize) { // incrementPool(minIdleSize - connectionPool.size() + 1); // } // } finally { // lock.unlock(); // } // } // } // // @Override // public void releaseConnection(Connection connection) { // if (!(connection instanceof ConnectionProxy)) { // throw new RuntimeException("released connection must be proxied!"); // } // lock.lock(); // try { // connectionPool.add(connection); // notEmpty.signal(); // } finally { // lock.unlock(); // } // if (connectionPool.size() > maxIdleSize) { // lock.lock(); // try { // if (connectionPool.size() > maxIdleSize) { // decrementPool(connectionPool.size() - maxIdleSize); // } // } finally { // lock.unlock(); // } // } // } // // private void incrementPool(int number) { // if (totalSize >= maxSize) { // return; // } // if (maxSize - totalSize < number) { // number = maxSize - totalSize; // } // lock.lock(); // try { // for (int i = 0; i < number; i++) { // connectionPool.add(newConnection()); // totalSize++; // } // } catch (IOException e) { // throw new RuntimeException(e); // } finally { // lock.unlock(); // } // } // // private void decrementPool(int number) { // lock.lock(); // try { // for (int i = 0; i < number; i++) { // try { // ((ConnectionProxy) connectionPool.removeLast()).realClose(); // } catch (NoSuchElementException e) { // break; // } // totalSize--; // } // } finally { // lock.unlock(); // } // } // // private Connection newConnection() throws IOException { // return new ConnectionProxy(new ConnectionImpl(server), this); // } // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/config/Servers.java // public abstract class Servers { // // public static Server newServer(String host,int port) { // return new DefaultServer(host, port); // } // // } // Path: src/test/java/com/zuoxiaolong/deerlet/redis/client/strategy/ConsistencyHashTest.java import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.zuoxiaolong.deerlet.redis.client.connection.ConnectionPool; import com.zuoxiaolong.deerlet.redis.client.connection.impl.ConnectionPoolImpl; import org.junit.Assert; import org.junit.Test; import com.zuoxiaolong.deerlet.redis.client.config.Servers; package com.zuoxiaolong.deerlet.redis.client.strategy; /** * <p> * <p/> * </p> * * @author 左潇龙 * @since 4/27/2015 5:30 PM */ public class ConsistencyHashTest { @Test public void testConsistencyHash() {
List<ConnectionPool> nodes = new ArrayList<ConnectionPool>();
xiaolongzuo/deerlet-redis-client
src/test/java/com/zuoxiaolong/deerlet/redis/client/strategy/ConsistencyHashTest.java
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/ConnectionPool.java // public interface ConnectionPool { // // public Connection obtainConnection(); // // public void releaseConnection(Connection connection); // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/impl/ConnectionPoolImpl.java // public class ConnectionPoolImpl implements ConnectionPool { // // private LinkedList<Connection> connectionPool; // // private ReentrantLock lock = new ReentrantLock(); // // private Condition notEmpty = lock.newCondition(); // // private int maxSize; // // private int minIdleSize; // // private int maxIdleSize; // // private int totalSize; // // private Server server; // // public ConnectionPoolImpl(Server server,int initSize, int maxSize, int minIdleSize, int maxIdleSize) { // if (initSize < minIdleSize || maxSize < initSize || maxSize < minIdleSize || maxIdleSize < minIdleSize || maxSize < maxIdleSize) { // throw new IllegalArgumentException("must (initSize < minIdleSize) && (maxSize < initSize) && (maxSize < minIdleSize) && (maxIdleSize < minIdleSize) && (maxSize < maxIdleSize)"); // } // if (server == null) { // throw new IllegalArgumentException("server can't be null!"); // } // this.server = server; // connectionPool = new LinkedList<Connection>(); // incrementPool(initSize); // this.maxSize = maxSize; // this.minIdleSize = minIdleSize; // this.maxIdleSize = maxIdleSize; // } // // @Override // public Connection obtainConnection() { // extend(); // Connection connection = null; // if (connectionPool.size() > 0) { // lock.lock(); // try { // if (connectionPool.size() > 0) { // connection = connectionPool.removeLast(); // } // } finally { // lock.unlock(); // } // } // while (connection == null) { // lock.lock(); // try { // notEmpty.await(); // if (connectionPool.size() > 0) { // connection = connectionPool.removeLast(); // } // } catch (InterruptedException e) { // throw new RuntimeException(e); // }finally { // lock.unlock(); // } // } // return connection; // } // // private void extend() { // if (connectionPool.size() < minIdleSize) { // lock.lock(); // try { // if (connectionPool.size() < minIdleSize) { // incrementPool(minIdleSize - connectionPool.size() + 1); // } // } finally { // lock.unlock(); // } // } // } // // @Override // public void releaseConnection(Connection connection) { // if (!(connection instanceof ConnectionProxy)) { // throw new RuntimeException("released connection must be proxied!"); // } // lock.lock(); // try { // connectionPool.add(connection); // notEmpty.signal(); // } finally { // lock.unlock(); // } // if (connectionPool.size() > maxIdleSize) { // lock.lock(); // try { // if (connectionPool.size() > maxIdleSize) { // decrementPool(connectionPool.size() - maxIdleSize); // } // } finally { // lock.unlock(); // } // } // } // // private void incrementPool(int number) { // if (totalSize >= maxSize) { // return; // } // if (maxSize - totalSize < number) { // number = maxSize - totalSize; // } // lock.lock(); // try { // for (int i = 0; i < number; i++) { // connectionPool.add(newConnection()); // totalSize++; // } // } catch (IOException e) { // throw new RuntimeException(e); // } finally { // lock.unlock(); // } // } // // private void decrementPool(int number) { // lock.lock(); // try { // for (int i = 0; i < number; i++) { // try { // ((ConnectionProxy) connectionPool.removeLast()).realClose(); // } catch (NoSuchElementException e) { // break; // } // totalSize--; // } // } finally { // lock.unlock(); // } // } // // private Connection newConnection() throws IOException { // return new ConnectionProxy(new ConnectionImpl(server), this); // } // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/config/Servers.java // public abstract class Servers { // // public static Server newServer(String host,int port) { // return new DefaultServer(host, port); // } // // }
import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.zuoxiaolong.deerlet.redis.client.connection.ConnectionPool; import com.zuoxiaolong.deerlet.redis.client.connection.impl.ConnectionPoolImpl; import org.junit.Assert; import org.junit.Test; import com.zuoxiaolong.deerlet.redis.client.config.Servers;
package com.zuoxiaolong.deerlet.redis.client.strategy; /** * <p> * <p/> * </p> * * @author 左潇龙 * @since 4/27/2015 5:30 PM */ public class ConsistencyHashTest { @Test public void testConsistencyHash() { List<ConnectionPool> nodes = new ArrayList<ConnectionPool>();
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/ConnectionPool.java // public interface ConnectionPool { // // public Connection obtainConnection(); // // public void releaseConnection(Connection connection); // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/impl/ConnectionPoolImpl.java // public class ConnectionPoolImpl implements ConnectionPool { // // private LinkedList<Connection> connectionPool; // // private ReentrantLock lock = new ReentrantLock(); // // private Condition notEmpty = lock.newCondition(); // // private int maxSize; // // private int minIdleSize; // // private int maxIdleSize; // // private int totalSize; // // private Server server; // // public ConnectionPoolImpl(Server server,int initSize, int maxSize, int minIdleSize, int maxIdleSize) { // if (initSize < minIdleSize || maxSize < initSize || maxSize < minIdleSize || maxIdleSize < minIdleSize || maxSize < maxIdleSize) { // throw new IllegalArgumentException("must (initSize < minIdleSize) && (maxSize < initSize) && (maxSize < minIdleSize) && (maxIdleSize < minIdleSize) && (maxSize < maxIdleSize)"); // } // if (server == null) { // throw new IllegalArgumentException("server can't be null!"); // } // this.server = server; // connectionPool = new LinkedList<Connection>(); // incrementPool(initSize); // this.maxSize = maxSize; // this.minIdleSize = minIdleSize; // this.maxIdleSize = maxIdleSize; // } // // @Override // public Connection obtainConnection() { // extend(); // Connection connection = null; // if (connectionPool.size() > 0) { // lock.lock(); // try { // if (connectionPool.size() > 0) { // connection = connectionPool.removeLast(); // } // } finally { // lock.unlock(); // } // } // while (connection == null) { // lock.lock(); // try { // notEmpty.await(); // if (connectionPool.size() > 0) { // connection = connectionPool.removeLast(); // } // } catch (InterruptedException e) { // throw new RuntimeException(e); // }finally { // lock.unlock(); // } // } // return connection; // } // // private void extend() { // if (connectionPool.size() < minIdleSize) { // lock.lock(); // try { // if (connectionPool.size() < minIdleSize) { // incrementPool(minIdleSize - connectionPool.size() + 1); // } // } finally { // lock.unlock(); // } // } // } // // @Override // public void releaseConnection(Connection connection) { // if (!(connection instanceof ConnectionProxy)) { // throw new RuntimeException("released connection must be proxied!"); // } // lock.lock(); // try { // connectionPool.add(connection); // notEmpty.signal(); // } finally { // lock.unlock(); // } // if (connectionPool.size() > maxIdleSize) { // lock.lock(); // try { // if (connectionPool.size() > maxIdleSize) { // decrementPool(connectionPool.size() - maxIdleSize); // } // } finally { // lock.unlock(); // } // } // } // // private void incrementPool(int number) { // if (totalSize >= maxSize) { // return; // } // if (maxSize - totalSize < number) { // number = maxSize - totalSize; // } // lock.lock(); // try { // for (int i = 0; i < number; i++) { // connectionPool.add(newConnection()); // totalSize++; // } // } catch (IOException e) { // throw new RuntimeException(e); // } finally { // lock.unlock(); // } // } // // private void decrementPool(int number) { // lock.lock(); // try { // for (int i = 0; i < number; i++) { // try { // ((ConnectionProxy) connectionPool.removeLast()).realClose(); // } catch (NoSuchElementException e) { // break; // } // totalSize--; // } // } finally { // lock.unlock(); // } // } // // private Connection newConnection() throws IOException { // return new ConnectionProxy(new ConnectionImpl(server), this); // } // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/config/Servers.java // public abstract class Servers { // // public static Server newServer(String host,int port) { // return new DefaultServer(host, port); // } // // } // Path: src/test/java/com/zuoxiaolong/deerlet/redis/client/strategy/ConsistencyHashTest.java import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.zuoxiaolong.deerlet.redis.client.connection.ConnectionPool; import com.zuoxiaolong.deerlet.redis.client.connection.impl.ConnectionPoolImpl; import org.junit.Assert; import org.junit.Test; import com.zuoxiaolong.deerlet.redis.client.config.Servers; package com.zuoxiaolong.deerlet.redis.client.strategy; /** * <p> * <p/> * </p> * * @author 左潇龙 * @since 4/27/2015 5:30 PM */ public class ConsistencyHashTest { @Test public void testConsistencyHash() { List<ConnectionPool> nodes = new ArrayList<ConnectionPool>();
nodes.add(new ConnectionPoolImpl(Servers.newServer("localhost", 6379),10,20,10,20));
xiaolongzuo/deerlet-redis-client
src/test/java/com/zuoxiaolong/deerlet/redis/client/strategy/ConsistencyHashTest.java
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/ConnectionPool.java // public interface ConnectionPool { // // public Connection obtainConnection(); // // public void releaseConnection(Connection connection); // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/impl/ConnectionPoolImpl.java // public class ConnectionPoolImpl implements ConnectionPool { // // private LinkedList<Connection> connectionPool; // // private ReentrantLock lock = new ReentrantLock(); // // private Condition notEmpty = lock.newCondition(); // // private int maxSize; // // private int minIdleSize; // // private int maxIdleSize; // // private int totalSize; // // private Server server; // // public ConnectionPoolImpl(Server server,int initSize, int maxSize, int minIdleSize, int maxIdleSize) { // if (initSize < minIdleSize || maxSize < initSize || maxSize < minIdleSize || maxIdleSize < minIdleSize || maxSize < maxIdleSize) { // throw new IllegalArgumentException("must (initSize < minIdleSize) && (maxSize < initSize) && (maxSize < minIdleSize) && (maxIdleSize < minIdleSize) && (maxSize < maxIdleSize)"); // } // if (server == null) { // throw new IllegalArgumentException("server can't be null!"); // } // this.server = server; // connectionPool = new LinkedList<Connection>(); // incrementPool(initSize); // this.maxSize = maxSize; // this.minIdleSize = minIdleSize; // this.maxIdleSize = maxIdleSize; // } // // @Override // public Connection obtainConnection() { // extend(); // Connection connection = null; // if (connectionPool.size() > 0) { // lock.lock(); // try { // if (connectionPool.size() > 0) { // connection = connectionPool.removeLast(); // } // } finally { // lock.unlock(); // } // } // while (connection == null) { // lock.lock(); // try { // notEmpty.await(); // if (connectionPool.size() > 0) { // connection = connectionPool.removeLast(); // } // } catch (InterruptedException e) { // throw new RuntimeException(e); // }finally { // lock.unlock(); // } // } // return connection; // } // // private void extend() { // if (connectionPool.size() < minIdleSize) { // lock.lock(); // try { // if (connectionPool.size() < minIdleSize) { // incrementPool(minIdleSize - connectionPool.size() + 1); // } // } finally { // lock.unlock(); // } // } // } // // @Override // public void releaseConnection(Connection connection) { // if (!(connection instanceof ConnectionProxy)) { // throw new RuntimeException("released connection must be proxied!"); // } // lock.lock(); // try { // connectionPool.add(connection); // notEmpty.signal(); // } finally { // lock.unlock(); // } // if (connectionPool.size() > maxIdleSize) { // lock.lock(); // try { // if (connectionPool.size() > maxIdleSize) { // decrementPool(connectionPool.size() - maxIdleSize); // } // } finally { // lock.unlock(); // } // } // } // // private void incrementPool(int number) { // if (totalSize >= maxSize) { // return; // } // if (maxSize - totalSize < number) { // number = maxSize - totalSize; // } // lock.lock(); // try { // for (int i = 0; i < number; i++) { // connectionPool.add(newConnection()); // totalSize++; // } // } catch (IOException e) { // throw new RuntimeException(e); // } finally { // lock.unlock(); // } // } // // private void decrementPool(int number) { // lock.lock(); // try { // for (int i = 0; i < number; i++) { // try { // ((ConnectionProxy) connectionPool.removeLast()).realClose(); // } catch (NoSuchElementException e) { // break; // } // totalSize--; // } // } finally { // lock.unlock(); // } // } // // private Connection newConnection() throws IOException { // return new ConnectionProxy(new ConnectionImpl(server), this); // } // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/config/Servers.java // public abstract class Servers { // // public static Server newServer(String host,int port) { // return new DefaultServer(host, port); // } // // }
import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.zuoxiaolong.deerlet.redis.client.connection.ConnectionPool; import com.zuoxiaolong.deerlet.redis.client.connection.impl.ConnectionPoolImpl; import org.junit.Assert; import org.junit.Test; import com.zuoxiaolong.deerlet.redis.client.config.Servers;
package com.zuoxiaolong.deerlet.redis.client.strategy; /** * <p> * <p/> * </p> * * @author 左潇龙 * @since 4/27/2015 5:30 PM */ public class ConsistencyHashTest { @Test public void testConsistencyHash() { List<ConnectionPool> nodes = new ArrayList<ConnectionPool>();
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/ConnectionPool.java // public interface ConnectionPool { // // public Connection obtainConnection(); // // public void releaseConnection(Connection connection); // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/impl/ConnectionPoolImpl.java // public class ConnectionPoolImpl implements ConnectionPool { // // private LinkedList<Connection> connectionPool; // // private ReentrantLock lock = new ReentrantLock(); // // private Condition notEmpty = lock.newCondition(); // // private int maxSize; // // private int minIdleSize; // // private int maxIdleSize; // // private int totalSize; // // private Server server; // // public ConnectionPoolImpl(Server server,int initSize, int maxSize, int minIdleSize, int maxIdleSize) { // if (initSize < minIdleSize || maxSize < initSize || maxSize < minIdleSize || maxIdleSize < minIdleSize || maxSize < maxIdleSize) { // throw new IllegalArgumentException("must (initSize < minIdleSize) && (maxSize < initSize) && (maxSize < minIdleSize) && (maxIdleSize < minIdleSize) && (maxSize < maxIdleSize)"); // } // if (server == null) { // throw new IllegalArgumentException("server can't be null!"); // } // this.server = server; // connectionPool = new LinkedList<Connection>(); // incrementPool(initSize); // this.maxSize = maxSize; // this.minIdleSize = minIdleSize; // this.maxIdleSize = maxIdleSize; // } // // @Override // public Connection obtainConnection() { // extend(); // Connection connection = null; // if (connectionPool.size() > 0) { // lock.lock(); // try { // if (connectionPool.size() > 0) { // connection = connectionPool.removeLast(); // } // } finally { // lock.unlock(); // } // } // while (connection == null) { // lock.lock(); // try { // notEmpty.await(); // if (connectionPool.size() > 0) { // connection = connectionPool.removeLast(); // } // } catch (InterruptedException e) { // throw new RuntimeException(e); // }finally { // lock.unlock(); // } // } // return connection; // } // // private void extend() { // if (connectionPool.size() < minIdleSize) { // lock.lock(); // try { // if (connectionPool.size() < minIdleSize) { // incrementPool(minIdleSize - connectionPool.size() + 1); // } // } finally { // lock.unlock(); // } // } // } // // @Override // public void releaseConnection(Connection connection) { // if (!(connection instanceof ConnectionProxy)) { // throw new RuntimeException("released connection must be proxied!"); // } // lock.lock(); // try { // connectionPool.add(connection); // notEmpty.signal(); // } finally { // lock.unlock(); // } // if (connectionPool.size() > maxIdleSize) { // lock.lock(); // try { // if (connectionPool.size() > maxIdleSize) { // decrementPool(connectionPool.size() - maxIdleSize); // } // } finally { // lock.unlock(); // } // } // } // // private void incrementPool(int number) { // if (totalSize >= maxSize) { // return; // } // if (maxSize - totalSize < number) { // number = maxSize - totalSize; // } // lock.lock(); // try { // for (int i = 0; i < number; i++) { // connectionPool.add(newConnection()); // totalSize++; // } // } catch (IOException e) { // throw new RuntimeException(e); // } finally { // lock.unlock(); // } // } // // private void decrementPool(int number) { // lock.lock(); // try { // for (int i = 0; i < number; i++) { // try { // ((ConnectionProxy) connectionPool.removeLast()).realClose(); // } catch (NoSuchElementException e) { // break; // } // totalSize--; // } // } finally { // lock.unlock(); // } // } // // private Connection newConnection() throws IOException { // return new ConnectionProxy(new ConnectionImpl(server), this); // } // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/config/Servers.java // public abstract class Servers { // // public static Server newServer(String host,int port) { // return new DefaultServer(host, port); // } // // } // Path: src/test/java/com/zuoxiaolong/deerlet/redis/client/strategy/ConsistencyHashTest.java import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.zuoxiaolong.deerlet.redis.client.connection.ConnectionPool; import com.zuoxiaolong.deerlet.redis.client.connection.impl.ConnectionPoolImpl; import org.junit.Assert; import org.junit.Test; import com.zuoxiaolong.deerlet.redis.client.config.Servers; package com.zuoxiaolong.deerlet.redis.client.strategy; /** * <p> * <p/> * </p> * * @author 左潇龙 * @since 4/27/2015 5:30 PM */ public class ConsistencyHashTest { @Test public void testConsistencyHash() { List<ConnectionPool> nodes = new ArrayList<ConnectionPool>();
nodes.add(new ConnectionPoolImpl(Servers.newServer("localhost", 6379),10,20,10,20));
xiaolongzuo/deerlet-redis-client
src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/impl/ConnectionPoolImpl.java
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/config/Server.java // public interface Server { // // String getHost(); // // int getPort(); // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/Connection.java // public interface Connection { // // public MultibulkOutputStream getOutputStream(); // // public MultibulkInputStream getInputStream(); // // public boolean isClosed(); // // public void close(); // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/ConnectionPool.java // public interface ConnectionPool { // // public Connection obtainConnection(); // // public void releaseConnection(Connection connection); // // }
import com.zuoxiaolong.deerlet.redis.client.config.Server; import com.zuoxiaolong.deerlet.redis.client.connection.Connection; import com.zuoxiaolong.deerlet.redis.client.connection.ConnectionPool; import java.io.IOException; import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock;
package com.zuoxiaolong.deerlet.redis.client.connection.impl; /** * * deerlet的连接池。该类是线程安全的。 * * @author zuoxiaolong * @since 2015 2015年3月6日 下午11:41:21 * */ public class ConnectionPoolImpl implements ConnectionPool { private LinkedList<Connection> connectionPool; private ReentrantLock lock = new ReentrantLock(); private Condition notEmpty = lock.newCondition(); private int maxSize; private int minIdleSize; private int maxIdleSize; private int totalSize;
// Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/config/Server.java // public interface Server { // // String getHost(); // // int getPort(); // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/Connection.java // public interface Connection { // // public MultibulkOutputStream getOutputStream(); // // public MultibulkInputStream getInputStream(); // // public boolean isClosed(); // // public void close(); // // } // // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/ConnectionPool.java // public interface ConnectionPool { // // public Connection obtainConnection(); // // public void releaseConnection(Connection connection); // // } // Path: src/main/java/com/zuoxiaolong/deerlet/redis/client/connection/impl/ConnectionPoolImpl.java import com.zuoxiaolong.deerlet.redis.client.config.Server; import com.zuoxiaolong.deerlet.redis.client.connection.Connection; import com.zuoxiaolong.deerlet.redis.client.connection.ConnectionPool; import java.io.IOException; import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; package com.zuoxiaolong.deerlet.redis.client.connection.impl; /** * * deerlet的连接池。该类是线程安全的。 * * @author zuoxiaolong * @since 2015 2015年3月6日 下午11:41:21 * */ public class ConnectionPoolImpl implements ConnectionPool { private LinkedList<Connection> connectionPool; private ReentrantLock lock = new ReentrantLock(); private Condition notEmpty = lock.newCondition(); private int maxSize; private int minIdleSize; private int maxIdleSize; private int totalSize;
private Server server;
isaiah/jubilee
src/main/java/org/jruby/jubilee/RubyPlatformManager.java
// Path: src/main/java/org/jruby/jubilee/vertx/JubileeVertx.java // public class JubileeVertx { // public static Vertx vertx; // // private JubileeVertx() { // } // // public static void init(Vertx vertx) { // JubileeVertx.vertx = vertx; // } // // public synchronized static Vertx vertx() { // if (JubileeVertx.vertx == null) // throw new RuntimeException("vertx is not initialized, do you run in jubilee server?"); // return JubileeVertx.vertx; // } // }
import io.vertx.core.*; import io.vertx.core.json.JsonObject; import org.jruby.*; import org.jruby.anno.JRubyMethod; import org.jruby.jubilee.vertx.JubileeVertx; import org.jruby.runtime.Block; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration;
} }; public RubyPlatformManager(Ruby ruby, RubyClass rubyClass) { super(ruby, rubyClass); } @JRubyMethod public IRubyObject initialize(ThreadContext context, IRubyObject config) { this.options = config.convertToHash(); Ruby runtime = context.runtime; RubySymbol clustered_k = runtime.newSymbol("clustered"); RubySymbol cluster_host_k = runtime.newSymbol("cluster_host"); RubySymbol cluster_port_k = runtime.newSymbol("cluster_port"); VertxOptions vertxOptions = new VertxOptions(); long maxEventLoopExecuteTime = 6000000000L; vertxOptions.setMaxEventLoopExecuteTime(maxEventLoopExecuteTime); if (options.containsKey(clustered_k) && options.op_aref(context, clustered_k).isTrue()) { int clusterPort = 0; String clusterHost = null; if (options.containsKey(cluster_port_k)) clusterPort = RubyNumeric.num2int(options.op_aref(context, cluster_port_k)); if (options.containsKey(cluster_host_k)) clusterHost = options.op_aref(context, cluster_host_k).asJavaString(); if (clusterHost == null) clusterHost = getDefaultAddress(); vertxOptions.setClustered(true).setClusterHost(clusterHost).setClusterPort(clusterPort); Vertx.clusteredVertx(vertxOptions, result -> { System.out.println("VERTX DEBUG: Clustered Vertx Instance Creation Completed."); this.vertx = result.result();
// Path: src/main/java/org/jruby/jubilee/vertx/JubileeVertx.java // public class JubileeVertx { // public static Vertx vertx; // // private JubileeVertx() { // } // // public static void init(Vertx vertx) { // JubileeVertx.vertx = vertx; // } // // public synchronized static Vertx vertx() { // if (JubileeVertx.vertx == null) // throw new RuntimeException("vertx is not initialized, do you run in jubilee server?"); // return JubileeVertx.vertx; // } // } // Path: src/main/java/org/jruby/jubilee/RubyPlatformManager.java import io.vertx.core.*; import io.vertx.core.json.JsonObject; import org.jruby.*; import org.jruby.anno.JRubyMethod; import org.jruby.jubilee.vertx.JubileeVertx; import org.jruby.runtime.Block; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; } }; public RubyPlatformManager(Ruby ruby, RubyClass rubyClass) { super(ruby, rubyClass); } @JRubyMethod public IRubyObject initialize(ThreadContext context, IRubyObject config) { this.options = config.convertToHash(); Ruby runtime = context.runtime; RubySymbol clustered_k = runtime.newSymbol("clustered"); RubySymbol cluster_host_k = runtime.newSymbol("cluster_host"); RubySymbol cluster_port_k = runtime.newSymbol("cluster_port"); VertxOptions vertxOptions = new VertxOptions(); long maxEventLoopExecuteTime = 6000000000L; vertxOptions.setMaxEventLoopExecuteTime(maxEventLoopExecuteTime); if (options.containsKey(clustered_k) && options.op_aref(context, clustered_k).isTrue()) { int clusterPort = 0; String clusterHost = null; if (options.containsKey(cluster_port_k)) clusterPort = RubyNumeric.num2int(options.op_aref(context, cluster_port_k)); if (options.containsKey(cluster_host_k)) clusterHost = options.op_aref(context, cluster_host_k).asJavaString(); if (clusterHost == null) clusterHost = getDefaultAddress(); vertxOptions.setClustered(true).setClusterHost(clusterHost).setClusterPort(clusterPort); Vertx.clusteredVertx(vertxOptions, result -> { System.out.println("VERTX DEBUG: Clustered Vertx Instance Creation Completed."); this.vertx = result.result();
JubileeVertx.init(this.vertx);
isaiah/jubilee
src/main/java/org/jruby/jubilee/impl/RubyIORackInput.java
// Path: src/main/java/org/jruby/jubilee/Const.java // public final class Const { // // public static final String JUBILEE_VERSION = "Jubilee(3.0.0)"; // // public static final String LOCALHOST = "localhost"; // public static final String PORT_80 = "80"; // public static final String MULTI_THREADED = "rack.multithread"; // public static class Vertx { // public static final String CONTENT_LENGTH = "Content-Length"; // } // // public static final String HTTP = "http"; // public static final String HTTPS = "https"; // public static final String HOST = "Host"; // // private Const() { // } // // // Internal // public static final byte EOL = '\n'; // }
import io.netty.buffer.ByteBuf; import org.jcodings.Encoding; import org.jcodings.specific.ASCIIEncoding; import org.jruby.*; import org.jruby.anno.JRubyMethod; import org.jruby.jubilee.Const; import org.jruby.jubilee.RackInput; import org.jruby.runtime.Block; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.util.ByteList; import org.jruby.util.StringSupport; import java.util.concurrent.atomic.AtomicBoolean; import io.vertx.core.http.HttpServerRequest;
package org.jruby.jubilee.impl; /** * Created with IntelliJ IDEA. * User: isaiah * Date: 11/26/12 * Time: 10:12 PM */ public class RubyIORackInput extends RubyObject implements RackInput { private Encoding BINARY = ASCIIEncoding.INSTANCE; private int len; private boolean chunked; private ByteBuf buf; private AtomicBoolean eof; public static ObjectAllocator ALLOCATOR = new ObjectAllocator() { @Override public IRubyObject allocate(Ruby ruby, RubyClass rubyClass) { return new RubyIORackInput(ruby, rubyClass); } }; public static RubyClass createIORackInputClass(Ruby runtime) { RubyModule jModule = runtime.getOrCreateModule("Jubilee"); RubyClass rackIOInputClass = jModule.defineClassUnder("IORackInput", runtime.getObject(), ALLOCATOR); rackIOInputClass.defineAnnotatedMethods(RubyIORackInput.class); return rackIOInputClass; } public RubyIORackInput(Ruby runtime, RubyClass metaClass) { super(runtime, metaClass); } public RubyIORackInput(Ruby runtime, RubyClass rubyClass, HttpServerRequest request, ByteBuf buf, AtomicBoolean eof) { this(runtime, rubyClass);
// Path: src/main/java/org/jruby/jubilee/Const.java // public final class Const { // // public static final String JUBILEE_VERSION = "Jubilee(3.0.0)"; // // public static final String LOCALHOST = "localhost"; // public static final String PORT_80 = "80"; // public static final String MULTI_THREADED = "rack.multithread"; // public static class Vertx { // public static final String CONTENT_LENGTH = "Content-Length"; // } // // public static final String HTTP = "http"; // public static final String HTTPS = "https"; // public static final String HOST = "Host"; // // private Const() { // } // // // Internal // public static final byte EOL = '\n'; // } // Path: src/main/java/org/jruby/jubilee/impl/RubyIORackInput.java import io.netty.buffer.ByteBuf; import org.jcodings.Encoding; import org.jcodings.specific.ASCIIEncoding; import org.jruby.*; import org.jruby.anno.JRubyMethod; import org.jruby.jubilee.Const; import org.jruby.jubilee.RackInput; import org.jruby.runtime.Block; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.util.ByteList; import org.jruby.util.StringSupport; import java.util.concurrent.atomic.AtomicBoolean; import io.vertx.core.http.HttpServerRequest; package org.jruby.jubilee.impl; /** * Created with IntelliJ IDEA. * User: isaiah * Date: 11/26/12 * Time: 10:12 PM */ public class RubyIORackInput extends RubyObject implements RackInput { private Encoding BINARY = ASCIIEncoding.INSTANCE; private int len; private boolean chunked; private ByteBuf buf; private AtomicBoolean eof; public static ObjectAllocator ALLOCATOR = new ObjectAllocator() { @Override public IRubyObject allocate(Ruby ruby, RubyClass rubyClass) { return new RubyIORackInput(ruby, rubyClass); } }; public static RubyClass createIORackInputClass(Ruby runtime) { RubyModule jModule = runtime.getOrCreateModule("Jubilee"); RubyClass rackIOInputClass = jModule.defineClassUnder("IORackInput", runtime.getObject(), ALLOCATOR); rackIOInputClass.defineAnnotatedMethods(RubyIORackInput.class); return rackIOInputClass; } public RubyIORackInput(Ruby runtime, RubyClass metaClass) { super(runtime, metaClass); } public RubyIORackInput(Ruby runtime, RubyClass rubyClass, HttpServerRequest request, ByteBuf buf, AtomicBoolean eof) { this(runtime, rubyClass);
String hdr = request.headers().get(Const.Vertx.CONTENT_LENGTH);
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/LocalMemoryCache.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/ICache.java // public interface ICache { // // public void put (String key, JsonObject data); // // default void putArray (String key, JsonArray array) { // if (array == null) { // throw new NullPointerException("array cannot be null."); // } // // JsonObject obj = new JsonObject(); // obj.put("array", array); // // put(key, obj); // } // // public void remove (String key); // // public void removeAll (); // // public boolean contains (String key); // // public JsonObject get (String key); // // default JsonArray getArray (String key) { // JsonObject obj = get(key); // // if (obj == null) { // return null; // } // // if (!obj.containsKey("array")) { // throw new IllegalStateException("cached object isnt an array."); // } // // return obj.getJsonArray("array"); // } // // public void cleanUp (); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // }
import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.json.JsonObject; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
package com.jukusoft.erp.lib.cache.impl; public class LocalMemoryCache implements ICache { //map with all cache entries protected Map<String,JsonObject> cacheMap = new ConcurrentHashMap<>(); //map with last access date (unix timestamp) protected Map<String,Long> accessMap = new ConcurrentHashMap<>(); //time to live for cache objects (30 seconds) protected long TTL = 30 * 1000;
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/ICache.java // public interface ICache { // // public void put (String key, JsonObject data); // // default void putArray (String key, JsonArray array) { // if (array == null) { // throw new NullPointerException("array cannot be null."); // } // // JsonObject obj = new JsonObject(); // obj.put("array", array); // // put(key, obj); // } // // public void remove (String key); // // public void removeAll (); // // public boolean contains (String key); // // public JsonObject get (String key); // // default JsonArray getArray (String key) { // JsonObject obj = get(key); // // if (obj == null) { // return null; // } // // if (!obj.containsKey("array")) { // throw new IllegalStateException("cached object isnt an array."); // } // // return obj.getJsonArray("array"); // } // // public void cleanUp (); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/LocalMemoryCache.java import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.json.JsonObject; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; package com.jukusoft.erp.lib.cache.impl; public class LocalMemoryCache implements ICache { //map with all cache entries protected Map<String,JsonObject> cacheMap = new ConcurrentHashMap<>(); //map with last access date (unix timestamp) protected Map<String,Long> accessMap = new ConcurrentHashMap<>(); //time to live for cache objects (30 seconds) protected long TTL = 30 * 1000;
public LocalMemoryCache (ILogging logger) {
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/message/response/ApiResponse.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/message/StatusCode.java // public enum StatusCode { // // NOT_FOUND(404), // // OK(200), // // BAD_REQUEST(400), // // WRONG_SESSION(400), // // FORBIDDEN(403), // // WRONG_PERMISSIONS(403), // // INTERNAL_SERVER_ERROR(500), // // SERVICE_UNAVAILABLE(503), // // UNKNOWN(500); // // private final int value; // // private StatusCode(int value) { // this.value = value; // } // // public int getValue () { // return this.value; // } // // public static StatusCode getByString (String str) { // switch (str.trim().toUpperCase()) { // case "NOT_FOUND": // return NOT_FOUND; // // case "OK": // // return OK; // // case "BAD_REQUEST": // // return BAD_REQUEST; // // case "FORBIDDEN": // // return FORBIDDEN; // // case "WRONG_PERMISSIONS": // // return WRONG_PERMISSIONS; // // case "SERVICE_UNAVAILABLE": // // return SERVICE_UNAVAILABLE; // // default: // // return UNKNOWN; // } // } // // }
import com.jukusoft.erp.lib.message.StatusCode; import io.vertx.core.json.JsonObject;
package com.jukusoft.erp.lib.message.response; public class ApiResponse { //name of event protected String eventName = ""; //json data protected JsonObject data = new JsonObject(); protected String ackID = "";
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/message/StatusCode.java // public enum StatusCode { // // NOT_FOUND(404), // // OK(200), // // BAD_REQUEST(400), // // WRONG_SESSION(400), // // FORBIDDEN(403), // // WRONG_PERMISSIONS(403), // // INTERNAL_SERVER_ERROR(500), // // SERVICE_UNAVAILABLE(503), // // UNKNOWN(500); // // private final int value; // // private StatusCode(int value) { // this.value = value; // } // // public int getValue () { // return this.value; // } // // public static StatusCode getByString (String str) { // switch (str.trim().toUpperCase()) { // case "NOT_FOUND": // return NOT_FOUND; // // case "OK": // // return OK; // // case "BAD_REQUEST": // // return BAD_REQUEST; // // case "FORBIDDEN": // // return FORBIDDEN; // // case "WRONG_PERMISSIONS": // // return WRONG_PERMISSIONS; // // case "SERVICE_UNAVAILABLE": // // return SERVICE_UNAVAILABLE; // // default: // // return UNKNOWN; // } // } // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/message/response/ApiResponse.java import com.jukusoft.erp.lib.message.StatusCode; import io.vertx.core.json.JsonObject; package com.jukusoft.erp.lib.message.response; public class ApiResponse { //name of event protected String eventName = ""; //json data protected JsonObject data = new JsonObject(); protected String ackID = "";
protected StatusCode statusCode = StatusCode.OK;
open-erp-systems/erp-backend
app-server/src/main/java/com/jukusoft/erp/app/server/AppServer.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/module/IModule.java // public interface IModule { // // /** // * get a reference to the Vert.x instance that deployed this verticle // * // * @return reference to the Vert.x instance // */ // public Vertx getVertx (); // // /** // * get instance of logger // */ // public ILogging getLogger (); // // /** // * get instance of event bus // * // * @return instance of event bus // */ // public EventBus getEventBus (); // // /** // * initialize module // */ // public void init (Vertx vertx, AppContext context, ILogging logger); // // /** // * start module // */ // public void start (Handler<Future<IModule>> handler) throws Exception; // // /** // * stop module // */ // public void stop (Handler<Future<Void>> handler) throws Exception; // // }
import com.jukusoft.erp.lib.module.IModule;
package com.jukusoft.erp.app.server; public interface AppServer { /** * start microservice application server */ public void start (AppStartListener listener); /** * set number of threads for event loop pool * * @param nOfThreads number of threads for event loop pool */ public void setEventLoopPoolSize (int nOfThreads); /** * set number of threads for worker pool * * @param nOfThreads number of threads for worker pool */ public void setWorkerPoolSize (int nOfThreads); /** * add and start module * * @param module instance of module * @param cls class name of module */
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/module/IModule.java // public interface IModule { // // /** // * get a reference to the Vert.x instance that deployed this verticle // * // * @return reference to the Vert.x instance // */ // public Vertx getVertx (); // // /** // * get instance of logger // */ // public ILogging getLogger (); // // /** // * get instance of event bus // * // * @return instance of event bus // */ // public EventBus getEventBus (); // // /** // * initialize module // */ // public void init (Vertx vertx, AppContext context, ILogging logger); // // /** // * start module // */ // public void start (Handler<Future<IModule>> handler) throws Exception; // // /** // * stop module // */ // public void stop (Handler<Future<Void>> handler) throws Exception; // // } // Path: app-server/src/main/java/com/jukusoft/erp/app/server/AppServer.java import com.jukusoft.erp.lib.module.IModule; package com.jukusoft.erp.app.server; public interface AppServer { /** * start microservice application server */ public void start (AppStartListener listener); /** * set number of threads for event loop pool * * @param nOfThreads number of threads for event loop pool */ public void setEventLoopPoolSize (int nOfThreads); /** * set number of threads for worker pool * * @param nOfThreads number of threads for worker pool */ public void setWorkerPoolSize (int nOfThreads); /** * add and start module * * @param module instance of module * @param cls class name of module */
public <T extends IModule> void deployModule (T module, Class<T> cls);
open-erp-systems/erp-backend
erp-data/src/main/java/com/jukusoft/data/repository/MenuRepository.java
// Path: erp-data/src/main/java/com/jukusoft/data/entity/Group.java // public class Group implements JsonSerializable { // // //database row // protected JsonObject row = null; // // /** // * default constructor // * // * @param row database row of user // */ // public Group (JsonObject row) { // if (row == null) { // throw new NullPointerException("row cannot be null."); // } // // if (!row.containsKey("groupID")) { // for (String colName : row.fieldNames()) { // System.out.println("row coloum: " + colName); // } // // throw new IllegalArgumentException("row is invalide, no column groupID exists."); // } // // this.row = row; // } // // public long getGroupID () { // return this.row.getLong("groupID"); // } // // public String getName () { // return this.row.getString("name"); // } // // public String getDescription () { // return this.row.getString("description"); // } // // public String getColorHex () { // return this.row.getString("color"); // } // // public boolean isAutoJoin () { // return this.row.getInteger("auto_join") == 1; // } // // public boolean isActivated () { // return this.row.getInteger("activated") == 1; // } // // @Override // public JsonObject toJSON() { // return this.row; // } // // @Override // public String toString () { // return toJSON().encode(); // } // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheTypes.java // public enum CacheTypes { // // /** // * cache entries on filesystem // */ // FILE_CACHE, // // /** // * cache values on local memory cache // */ // LOCAL_MEMORY_CACHE, // // /** // * cache values in distributed hazelcast cache // */ // HAZELCAST_CACHE // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/ICache.java // public interface ICache { // // public void put (String key, JsonObject data); // // default void putArray (String key, JsonArray array) { // if (array == null) { // throw new NullPointerException("array cannot be null."); // } // // JsonObject obj = new JsonObject(); // obj.put("array", array); // // put(key, obj); // } // // public void remove (String key); // // public void removeAll (); // // public boolean contains (String key); // // public JsonObject get (String key); // // default JsonArray getArray (String key) { // JsonObject obj = get(key); // // if (obj == null) { // return null; // } // // if (!obj.containsKey("array")) { // throw new IllegalStateException("cached object isnt an array."); // } // // return obj.getJsonArray("array"); // } // // public void cleanUp (); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/database/AbstractMySQLRepository.java // public class AbstractMySQLRepository implements MySQLRepository { // // //instance of mysql database // private MySQLDatabase mySQLDatabase = null; // // @Override // public void init(Vertx vertx, MySQLDatabase database) { // this.mySQLDatabase = database; // } // // protected MySQLDatabase getMySQLDatabase () { // return this.mySQLDatabase; // } // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/utils/JsonUtils.java // public class JsonUtils { // // public static JsonArray convertJsonObjectListToArray (List<JsonObject> rows) { // //create new json array // JsonArray array = new JsonArray(); // // for (JsonObject row : rows) { // array.add(row); // } // // return array; // } // // }
import com.jukusoft.data.entity.Group; import com.jukusoft.erp.lib.cache.CacheTypes; import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.cache.InjectCache; import com.jukusoft.erp.lib.database.AbstractMySQLRepository; import com.jukusoft.erp.lib.utils.JsonUtils; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import java.util.List;
package com.jukusoft.data.repository; public class MenuRepository extends AbstractMySQLRepository { @InjectCache(name = "menu-cache", type = CacheTypes.HAZELCAST_CACHE)
// Path: erp-data/src/main/java/com/jukusoft/data/entity/Group.java // public class Group implements JsonSerializable { // // //database row // protected JsonObject row = null; // // /** // * default constructor // * // * @param row database row of user // */ // public Group (JsonObject row) { // if (row == null) { // throw new NullPointerException("row cannot be null."); // } // // if (!row.containsKey("groupID")) { // for (String colName : row.fieldNames()) { // System.out.println("row coloum: " + colName); // } // // throw new IllegalArgumentException("row is invalide, no column groupID exists."); // } // // this.row = row; // } // // public long getGroupID () { // return this.row.getLong("groupID"); // } // // public String getName () { // return this.row.getString("name"); // } // // public String getDescription () { // return this.row.getString("description"); // } // // public String getColorHex () { // return this.row.getString("color"); // } // // public boolean isAutoJoin () { // return this.row.getInteger("auto_join") == 1; // } // // public boolean isActivated () { // return this.row.getInteger("activated") == 1; // } // // @Override // public JsonObject toJSON() { // return this.row; // } // // @Override // public String toString () { // return toJSON().encode(); // } // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheTypes.java // public enum CacheTypes { // // /** // * cache entries on filesystem // */ // FILE_CACHE, // // /** // * cache values on local memory cache // */ // LOCAL_MEMORY_CACHE, // // /** // * cache values in distributed hazelcast cache // */ // HAZELCAST_CACHE // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/ICache.java // public interface ICache { // // public void put (String key, JsonObject data); // // default void putArray (String key, JsonArray array) { // if (array == null) { // throw new NullPointerException("array cannot be null."); // } // // JsonObject obj = new JsonObject(); // obj.put("array", array); // // put(key, obj); // } // // public void remove (String key); // // public void removeAll (); // // public boolean contains (String key); // // public JsonObject get (String key); // // default JsonArray getArray (String key) { // JsonObject obj = get(key); // // if (obj == null) { // return null; // } // // if (!obj.containsKey("array")) { // throw new IllegalStateException("cached object isnt an array."); // } // // return obj.getJsonArray("array"); // } // // public void cleanUp (); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/database/AbstractMySQLRepository.java // public class AbstractMySQLRepository implements MySQLRepository { // // //instance of mysql database // private MySQLDatabase mySQLDatabase = null; // // @Override // public void init(Vertx vertx, MySQLDatabase database) { // this.mySQLDatabase = database; // } // // protected MySQLDatabase getMySQLDatabase () { // return this.mySQLDatabase; // } // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/utils/JsonUtils.java // public class JsonUtils { // // public static JsonArray convertJsonObjectListToArray (List<JsonObject> rows) { // //create new json array // JsonArray array = new JsonArray(); // // for (JsonObject row : rows) { // array.add(row); // } // // return array; // } // // } // Path: erp-data/src/main/java/com/jukusoft/data/repository/MenuRepository.java import com.jukusoft.data.entity.Group; import com.jukusoft.erp.lib.cache.CacheTypes; import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.cache.InjectCache; import com.jukusoft.erp.lib.database.AbstractMySQLRepository; import com.jukusoft.erp.lib.utils.JsonUtils; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import java.util.List; package com.jukusoft.data.repository; public class MenuRepository extends AbstractMySQLRepository { @InjectCache(name = "menu-cache", type = CacheTypes.HAZELCAST_CACHE)
protected ICache menuCache;
open-erp-systems/erp-backend
erp-data/src/main/java/com/jukusoft/data/repository/MenuRepository.java
// Path: erp-data/src/main/java/com/jukusoft/data/entity/Group.java // public class Group implements JsonSerializable { // // //database row // protected JsonObject row = null; // // /** // * default constructor // * // * @param row database row of user // */ // public Group (JsonObject row) { // if (row == null) { // throw new NullPointerException("row cannot be null."); // } // // if (!row.containsKey("groupID")) { // for (String colName : row.fieldNames()) { // System.out.println("row coloum: " + colName); // } // // throw new IllegalArgumentException("row is invalide, no column groupID exists."); // } // // this.row = row; // } // // public long getGroupID () { // return this.row.getLong("groupID"); // } // // public String getName () { // return this.row.getString("name"); // } // // public String getDescription () { // return this.row.getString("description"); // } // // public String getColorHex () { // return this.row.getString("color"); // } // // public boolean isAutoJoin () { // return this.row.getInteger("auto_join") == 1; // } // // public boolean isActivated () { // return this.row.getInteger("activated") == 1; // } // // @Override // public JsonObject toJSON() { // return this.row; // } // // @Override // public String toString () { // return toJSON().encode(); // } // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheTypes.java // public enum CacheTypes { // // /** // * cache entries on filesystem // */ // FILE_CACHE, // // /** // * cache values on local memory cache // */ // LOCAL_MEMORY_CACHE, // // /** // * cache values in distributed hazelcast cache // */ // HAZELCAST_CACHE // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/ICache.java // public interface ICache { // // public void put (String key, JsonObject data); // // default void putArray (String key, JsonArray array) { // if (array == null) { // throw new NullPointerException("array cannot be null."); // } // // JsonObject obj = new JsonObject(); // obj.put("array", array); // // put(key, obj); // } // // public void remove (String key); // // public void removeAll (); // // public boolean contains (String key); // // public JsonObject get (String key); // // default JsonArray getArray (String key) { // JsonObject obj = get(key); // // if (obj == null) { // return null; // } // // if (!obj.containsKey("array")) { // throw new IllegalStateException("cached object isnt an array."); // } // // return obj.getJsonArray("array"); // } // // public void cleanUp (); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/database/AbstractMySQLRepository.java // public class AbstractMySQLRepository implements MySQLRepository { // // //instance of mysql database // private MySQLDatabase mySQLDatabase = null; // // @Override // public void init(Vertx vertx, MySQLDatabase database) { // this.mySQLDatabase = database; // } // // protected MySQLDatabase getMySQLDatabase () { // return this.mySQLDatabase; // } // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/utils/JsonUtils.java // public class JsonUtils { // // public static JsonArray convertJsonObjectListToArray (List<JsonObject> rows) { // //create new json array // JsonArray array = new JsonArray(); // // for (JsonObject row : rows) { // array.add(row); // } // // return array; // } // // }
import com.jukusoft.data.entity.Group; import com.jukusoft.erp.lib.cache.CacheTypes; import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.cache.InjectCache; import com.jukusoft.erp.lib.database.AbstractMySQLRepository; import com.jukusoft.erp.lib.utils.JsonUtils; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import java.util.List;
package com.jukusoft.data.repository; public class MenuRepository extends AbstractMySQLRepository { @InjectCache(name = "menu-cache", type = CacheTypes.HAZELCAST_CACHE) protected ICache menuCache; public void listMenusByMenuID (int menuID, Handler<AsyncResult<JsonArray>> handler) { //check, if cache is available if (this.menuCache == null) { throw new NullPointerException("menu cache cannot be null."); } if (menuID <= 0) { throw new IllegalArgumentException("menuID has to be greater than 0. Current value: " + menuID); } //check, if menu entries are in cache if (this.menuCache.contains("menu-" + menuID)) { handler.handle(Future.succeededFuture(this.menuCache.getArray("menu-" + menuID))); return; } //read menus from database getMySQLDatabase().listRows("SELECT * FROM `{prefix}menu` WHERE `menuID` = '" + menuID + "' ORDER BY `order`; ", res -> { if (!res.succeeded()) { handler.handle(Future.failedFuture(res.cause())); return; } //get rows List<JsonObject> rows = res.result(); //convert list to json array
// Path: erp-data/src/main/java/com/jukusoft/data/entity/Group.java // public class Group implements JsonSerializable { // // //database row // protected JsonObject row = null; // // /** // * default constructor // * // * @param row database row of user // */ // public Group (JsonObject row) { // if (row == null) { // throw new NullPointerException("row cannot be null."); // } // // if (!row.containsKey("groupID")) { // for (String colName : row.fieldNames()) { // System.out.println("row coloum: " + colName); // } // // throw new IllegalArgumentException("row is invalide, no column groupID exists."); // } // // this.row = row; // } // // public long getGroupID () { // return this.row.getLong("groupID"); // } // // public String getName () { // return this.row.getString("name"); // } // // public String getDescription () { // return this.row.getString("description"); // } // // public String getColorHex () { // return this.row.getString("color"); // } // // public boolean isAutoJoin () { // return this.row.getInteger("auto_join") == 1; // } // // public boolean isActivated () { // return this.row.getInteger("activated") == 1; // } // // @Override // public JsonObject toJSON() { // return this.row; // } // // @Override // public String toString () { // return toJSON().encode(); // } // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheTypes.java // public enum CacheTypes { // // /** // * cache entries on filesystem // */ // FILE_CACHE, // // /** // * cache values on local memory cache // */ // LOCAL_MEMORY_CACHE, // // /** // * cache values in distributed hazelcast cache // */ // HAZELCAST_CACHE // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/ICache.java // public interface ICache { // // public void put (String key, JsonObject data); // // default void putArray (String key, JsonArray array) { // if (array == null) { // throw new NullPointerException("array cannot be null."); // } // // JsonObject obj = new JsonObject(); // obj.put("array", array); // // put(key, obj); // } // // public void remove (String key); // // public void removeAll (); // // public boolean contains (String key); // // public JsonObject get (String key); // // default JsonArray getArray (String key) { // JsonObject obj = get(key); // // if (obj == null) { // return null; // } // // if (!obj.containsKey("array")) { // throw new IllegalStateException("cached object isnt an array."); // } // // return obj.getJsonArray("array"); // } // // public void cleanUp (); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/database/AbstractMySQLRepository.java // public class AbstractMySQLRepository implements MySQLRepository { // // //instance of mysql database // private MySQLDatabase mySQLDatabase = null; // // @Override // public void init(Vertx vertx, MySQLDatabase database) { // this.mySQLDatabase = database; // } // // protected MySQLDatabase getMySQLDatabase () { // return this.mySQLDatabase; // } // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/utils/JsonUtils.java // public class JsonUtils { // // public static JsonArray convertJsonObjectListToArray (List<JsonObject> rows) { // //create new json array // JsonArray array = new JsonArray(); // // for (JsonObject row : rows) { // array.add(row); // } // // return array; // } // // } // Path: erp-data/src/main/java/com/jukusoft/data/repository/MenuRepository.java import com.jukusoft.data.entity.Group; import com.jukusoft.erp.lib.cache.CacheTypes; import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.cache.InjectCache; import com.jukusoft.erp.lib.database.AbstractMySQLRepository; import com.jukusoft.erp.lib.utils.JsonUtils; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import java.util.List; package com.jukusoft.data.repository; public class MenuRepository extends AbstractMySQLRepository { @InjectCache(name = "menu-cache", type = CacheTypes.HAZELCAST_CACHE) protected ICache menuCache; public void listMenusByMenuID (int menuID, Handler<AsyncResult<JsonArray>> handler) { //check, if cache is available if (this.menuCache == null) { throw new NullPointerException("menu cache cannot be null."); } if (menuID <= 0) { throw new IllegalArgumentException("menuID has to be greater than 0. Current value: " + menuID); } //check, if menu entries are in cache if (this.menuCache.contains("menu-" + menuID)) { handler.handle(Future.succeededFuture(this.menuCache.getArray("menu-" + menuID))); return; } //read menus from database getMySQLDatabase().listRows("SELECT * FROM `{prefix}menu` WHERE `menuID` = '" + menuID + "' ORDER BY `order`; ", res -> { if (!res.succeeded()) { handler.handle(Future.failedFuture(res.cause())); return; } //get rows List<JsonObject> rows = res.result(); //convert list to json array
JsonArray rowsArray = JsonUtils.convertJsonObjectListToArray(rows);
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/message/response/ApiResponseCodec.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/message/StatusCode.java // public enum StatusCode { // // NOT_FOUND(404), // // OK(200), // // BAD_REQUEST(400), // // WRONG_SESSION(400), // // FORBIDDEN(403), // // WRONG_PERMISSIONS(403), // // INTERNAL_SERVER_ERROR(500), // // SERVICE_UNAVAILABLE(503), // // UNKNOWN(500); // // private final int value; // // private StatusCode(int value) { // this.value = value; // } // // public int getValue () { // return this.value; // } // // public static StatusCode getByString (String str) { // switch (str.trim().toUpperCase()) { // case "NOT_FOUND": // return NOT_FOUND; // // case "OK": // // return OK; // // case "BAD_REQUEST": // // return BAD_REQUEST; // // case "FORBIDDEN": // // return FORBIDDEN; // // case "WRONG_PERMISSIONS": // // return WRONG_PERMISSIONS; // // case "SERVICE_UNAVAILABLE": // // return SERVICE_UNAVAILABLE; // // default: // // return UNKNOWN; // } // } // // }
import com.jukusoft.erp.lib.message.StatusCode; import io.vertx.core.buffer.Buffer; import io.vertx.core.eventbus.MessageCodec; import io.vertx.core.json.JsonObject;
//encode json object to string String jsonToStr = json.toString(); // Length of JSON: is NOT characters count int length = jsonToStr.getBytes().length; // Write data into given buffer buffer.appendInt(length); buffer.appendString(jsonToStr); } @Override public ApiResponse decodeFromWire(int position, Buffer buffer) { // My custom message starting from this *position* of buffer int _pos = position; // Length of JSON int length = buffer.getInt(_pos); // Get JSON string by it`s length // Jump 4 because getInt() == 4 bytes String jsonStr = buffer.getString(_pos+=4, _pos+=length); JsonObject json = new JsonObject(jsonStr); ApiResponse res = new ApiResponse(json.getLong("cluster-message-id"), json.getString("external-id"), json.getString("session-id"), json.getString("event")); res.eventName = json.getString("event"); res.data = json.getJsonObject("data"); res.ackID = json.getString("ackID");
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/message/StatusCode.java // public enum StatusCode { // // NOT_FOUND(404), // // OK(200), // // BAD_REQUEST(400), // // WRONG_SESSION(400), // // FORBIDDEN(403), // // WRONG_PERMISSIONS(403), // // INTERNAL_SERVER_ERROR(500), // // SERVICE_UNAVAILABLE(503), // // UNKNOWN(500); // // private final int value; // // private StatusCode(int value) { // this.value = value; // } // // public int getValue () { // return this.value; // } // // public static StatusCode getByString (String str) { // switch (str.trim().toUpperCase()) { // case "NOT_FOUND": // return NOT_FOUND; // // case "OK": // // return OK; // // case "BAD_REQUEST": // // return BAD_REQUEST; // // case "FORBIDDEN": // // return FORBIDDEN; // // case "WRONG_PERMISSIONS": // // return WRONG_PERMISSIONS; // // case "SERVICE_UNAVAILABLE": // // return SERVICE_UNAVAILABLE; // // default: // // return UNKNOWN; // } // } // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/message/response/ApiResponseCodec.java import com.jukusoft.erp.lib.message.StatusCode; import io.vertx.core.buffer.Buffer; import io.vertx.core.eventbus.MessageCodec; import io.vertx.core.json.JsonObject; //encode json object to string String jsonToStr = json.toString(); // Length of JSON: is NOT characters count int length = jsonToStr.getBytes().length; // Write data into given buffer buffer.appendInt(length); buffer.appendString(jsonToStr); } @Override public ApiResponse decodeFromWire(int position, Buffer buffer) { // My custom message starting from this *position* of buffer int _pos = position; // Length of JSON int length = buffer.getInt(_pos); // Get JSON string by it`s length // Jump 4 because getInt() == 4 bytes String jsonStr = buffer.getString(_pos+=4, _pos+=length); JsonObject json = new JsonObject(jsonStr); ApiResponse res = new ApiResponse(json.getLong("cluster-message-id"), json.getString("external-id"), json.getString("session-id"), json.getString("event")); res.eventName = json.getString("event"); res.data = json.getJsonObject("data"); res.ackID = json.getString("ackID");
res.statusCode = StatusCode.getByString(json.getString("statusCode"));
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/session/SessionManager.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/session/impl/HzJCacheSessionManager.java // public class HzJCacheSessionManager implements ChangeableSessionManager { // // //session cache // private ICache<String,String> sessionCache = null; // // public HzJCacheSessionManager(HazelcastInstance hazelcastInstance) { // //initialize cache // this.initCache(hazelcastInstance); // } // // /** // * initialize JCache // * // * @param hazelcastInstance instance of hazelcast // */ // protected void initCache (HazelcastInstance hazelcastInstance) { // //get name of hazelcast instance // String instanceName = hazelcastInstance.getName(); // // /* // * use new JSR107 standard caching api for java with hazelcast connector, // * so the JCache is distributed in the hazelcast cluster // */ // CachingProvider cachingProvider = Caching.getCachingProvider(); // // // Create Properties instance pointing to a named HazelcastInstance // Properties properties = new Properties(); // properties.setProperty( HazelcastCachingProvider.HAZELCAST_INSTANCE_NAME, // instanceName ); // // URI cacheManagerName = null; // // try { // cacheManagerName = new URI( "com.hazelcast.cache.HazelcastCachingProvider" );//com.hazelcast.cache.HazelcastCachingProvider my-cache-manager // } catch (URISyntaxException e) { // e.printStackTrace(); // } // // /* // * JCache Configuration // */ // CacheManager cacheManager = cachingProvider // .getCacheManager(cacheManagerName, null, properties); // // MutableConfiguration<Long,String> configuration = new MutableConfiguration<Long,String>(); // // //enable jcache management and statistics, so jcache is shown in hazelcast mancenter // configuration.setManagementEnabled(true); // configuration.setStatisticsEnabled(true); // // //remove entries after 60 minutes without access // configuration.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 60l))); // // Cache<Long,String> cache = null; // // try { // cache = cacheManager.createCache("session-cache", configuration); // } catch (Exception e) { // e.printStackTrace(); // // cache = cacheManager.getCache("session-cache"); // // //enable jcache management and statistics, so jcache is shown in hazelcast mancenter // cache.getConfiguration(MutableConfiguration.class).setManagementEnabled(true); // cache.getConfiguration(MutableConfiguration.class).setStatisticsEnabled(true); // } // // //CacheManager extends Cache interface, provides more functionality // this.sessionCache = cache.unwrap(ICache.class); // } // // @Override // public Session getSession(String ssid) { // if (!this.exists(ssid)) { // return null; // } // // //create session instance from cache // String jsonStr = this.sessionCache.get(ssid); // Session session = Session.createFromJSON(new JsonObject(jsonStr), this); // // return session; // } // // @Override // public boolean exists(String ssid) { // return this.sessionCache.containsKey(ssid); // } // // @Override // public Session generateNewSession() { // //generate new sessionID // String sessionID = this.generateNewSessionID(); // // //create new session // Session session = new Session(sessionID); // // //save session // this.sessionCache.put(sessionID, session.toJSON().toString()); // // return session; // } // // protected String generateNewSessionID () { // return SessionIDGenerator.generateSessionID(); // } // // @Override // public void putSession(String ssid, Session session) { // this.sessionCache.put(ssid, session.toJSON().toString()); // } // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/session/impl/HzMapSessionManager.java // public class HzMapSessionManager implements ChangeableSessionManager { // // //map with all sessions // protected IMap<String,String> sessionMap = null; // // /** // * default constructor // * // * @param hazelcastInstance instance of hazelcast // */ // public HzMapSessionManager (HazelcastInstance hazelcastInstance) { // //get map // this.sessionMap = hazelcastInstance.getMap("session-cache"); // } // // @Override // public Session getSession(String ssid) { // if (!this.exists(ssid)) { // return null; // } // // //create session instance from cache // String jsonStr = this.sessionMap.get(ssid); // Session session = Session.createFromJSON(new JsonObject(jsonStr), this); // // return session; // } // // @Override // public boolean exists(String ssid) { // return this.sessionMap.containsKey(ssid); // } // // @Override // public Session generateNewSession() { // //generate new sessionID // String sessionID = this.generateNewSessionID(); // // //create new session // Session session = new Session(sessionID); // // //save session // this.sessionMap.put(sessionID, session.toJSON().toString()); // // return session; // } // // protected String generateNewSessionID () { // return SessionIDGenerator.generateSessionID(); // } // // @Override // public void putSession(String ssid, Session session) { // this.sessionMap.put(ssid, session.toJSON().toString()); // } // // }
import com.hazelcast.core.HazelcastInstance; import com.jukusoft.erp.lib.session.impl.HzJCacheSessionManager; import com.jukusoft.erp.lib.session.impl.HzMapSessionManager;
package com.jukusoft.erp.lib.session; public interface SessionManager { /** * get session by session id * * @return instance of session or null, if session doesnt exists */ public Session getSession (String ssid); /** * check, if session exists * * @return true, if session exists */ public boolean exists (String ssid); /** * generate an new session * * @return instance of new session */ public Session generateNewSession (); public static SessionManager createHzJCacheSessionManager (HazelcastInstance hazelcastInstance) {
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/session/impl/HzJCacheSessionManager.java // public class HzJCacheSessionManager implements ChangeableSessionManager { // // //session cache // private ICache<String,String> sessionCache = null; // // public HzJCacheSessionManager(HazelcastInstance hazelcastInstance) { // //initialize cache // this.initCache(hazelcastInstance); // } // // /** // * initialize JCache // * // * @param hazelcastInstance instance of hazelcast // */ // protected void initCache (HazelcastInstance hazelcastInstance) { // //get name of hazelcast instance // String instanceName = hazelcastInstance.getName(); // // /* // * use new JSR107 standard caching api for java with hazelcast connector, // * so the JCache is distributed in the hazelcast cluster // */ // CachingProvider cachingProvider = Caching.getCachingProvider(); // // // Create Properties instance pointing to a named HazelcastInstance // Properties properties = new Properties(); // properties.setProperty( HazelcastCachingProvider.HAZELCAST_INSTANCE_NAME, // instanceName ); // // URI cacheManagerName = null; // // try { // cacheManagerName = new URI( "com.hazelcast.cache.HazelcastCachingProvider" );//com.hazelcast.cache.HazelcastCachingProvider my-cache-manager // } catch (URISyntaxException e) { // e.printStackTrace(); // } // // /* // * JCache Configuration // */ // CacheManager cacheManager = cachingProvider // .getCacheManager(cacheManagerName, null, properties); // // MutableConfiguration<Long,String> configuration = new MutableConfiguration<Long,String>(); // // //enable jcache management and statistics, so jcache is shown in hazelcast mancenter // configuration.setManagementEnabled(true); // configuration.setStatisticsEnabled(true); // // //remove entries after 60 minutes without access // configuration.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 60l))); // // Cache<Long,String> cache = null; // // try { // cache = cacheManager.createCache("session-cache", configuration); // } catch (Exception e) { // e.printStackTrace(); // // cache = cacheManager.getCache("session-cache"); // // //enable jcache management and statistics, so jcache is shown in hazelcast mancenter // cache.getConfiguration(MutableConfiguration.class).setManagementEnabled(true); // cache.getConfiguration(MutableConfiguration.class).setStatisticsEnabled(true); // } // // //CacheManager extends Cache interface, provides more functionality // this.sessionCache = cache.unwrap(ICache.class); // } // // @Override // public Session getSession(String ssid) { // if (!this.exists(ssid)) { // return null; // } // // //create session instance from cache // String jsonStr = this.sessionCache.get(ssid); // Session session = Session.createFromJSON(new JsonObject(jsonStr), this); // // return session; // } // // @Override // public boolean exists(String ssid) { // return this.sessionCache.containsKey(ssid); // } // // @Override // public Session generateNewSession() { // //generate new sessionID // String sessionID = this.generateNewSessionID(); // // //create new session // Session session = new Session(sessionID); // // //save session // this.sessionCache.put(sessionID, session.toJSON().toString()); // // return session; // } // // protected String generateNewSessionID () { // return SessionIDGenerator.generateSessionID(); // } // // @Override // public void putSession(String ssid, Session session) { // this.sessionCache.put(ssid, session.toJSON().toString()); // } // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/session/impl/HzMapSessionManager.java // public class HzMapSessionManager implements ChangeableSessionManager { // // //map with all sessions // protected IMap<String,String> sessionMap = null; // // /** // * default constructor // * // * @param hazelcastInstance instance of hazelcast // */ // public HzMapSessionManager (HazelcastInstance hazelcastInstance) { // //get map // this.sessionMap = hazelcastInstance.getMap("session-cache"); // } // // @Override // public Session getSession(String ssid) { // if (!this.exists(ssid)) { // return null; // } // // //create session instance from cache // String jsonStr = this.sessionMap.get(ssid); // Session session = Session.createFromJSON(new JsonObject(jsonStr), this); // // return session; // } // // @Override // public boolean exists(String ssid) { // return this.sessionMap.containsKey(ssid); // } // // @Override // public Session generateNewSession() { // //generate new sessionID // String sessionID = this.generateNewSessionID(); // // //create new session // Session session = new Session(sessionID); // // //save session // this.sessionMap.put(sessionID, session.toJSON().toString()); // // return session; // } // // protected String generateNewSessionID () { // return SessionIDGenerator.generateSessionID(); // } // // @Override // public void putSession(String ssid, Session session) { // this.sessionMap.put(ssid, session.toJSON().toString()); // } // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/session/SessionManager.java import com.hazelcast.core.HazelcastInstance; import com.jukusoft.erp.lib.session.impl.HzJCacheSessionManager; import com.jukusoft.erp.lib.session.impl.HzMapSessionManager; package com.jukusoft.erp.lib.session; public interface SessionManager { /** * get session by session id * * @return instance of session or null, if session doesnt exists */ public Session getSession (String ssid); /** * check, if session exists * * @return true, if session exists */ public boolean exists (String ssid); /** * generate an new session * * @return instance of new session */ public Session generateNewSession (); public static SessionManager createHzJCacheSessionManager (HazelcastInstance hazelcastInstance) {
return new HzJCacheSessionManager(hazelcastInstance);
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/module/IModule.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/context/AppContext.java // public interface AppContext { // // public Vertx getVertx (); // // public ILogging getLogger (); // // /** // * get hazelcast instance // * // * @return instance of hazelcast // */ // public HazelcastInstance getHazelcast (); // // /** // * get instance of session manager // * // * @return instance of session manager // */ // public SessionManager getSessionManager (); // // /** // * get instance of database manager // * // * @return instance of database manager // */ // public DatabaseManager getDatabaseManager (); // // /** // * get instance of cache manager // * // * @return instance of cache manager // */ // public CacheManager getCacheManager (); // // /** // * get instance of permission manager // * // * @return instance of permission manager // */ // @Deprecated // public PermissionManager getPermissionManager (); // // /** // * set instance of permission manager // * // * @param permissionManager instance of permission manager // */ // @Deprecated // public void setPermissionManager (PermissionManager permissionManager); // // /** // * get permission service // * // * @return permission service // */ // public PermissionService getPermissionService (); // // /** // * set permission service // * // * @param service instance of permission service // */ // public void setPermissionService (PermissionService service); // // /** // * check, if user has permission // * // * @param request api request // * @param permission permission token // * // * @return true, if user has permission // */ // public boolean checkPermission (ApiRequest request, String permission); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // }
import com.jukusoft.erp.lib.context.AppContext; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus;
package com.jukusoft.erp.lib.module; public interface IModule { /** * get a reference to the Vert.x instance that deployed this verticle * * @return reference to the Vert.x instance */ public Vertx getVertx (); /** * get instance of logger */
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/context/AppContext.java // public interface AppContext { // // public Vertx getVertx (); // // public ILogging getLogger (); // // /** // * get hazelcast instance // * // * @return instance of hazelcast // */ // public HazelcastInstance getHazelcast (); // // /** // * get instance of session manager // * // * @return instance of session manager // */ // public SessionManager getSessionManager (); // // /** // * get instance of database manager // * // * @return instance of database manager // */ // public DatabaseManager getDatabaseManager (); // // /** // * get instance of cache manager // * // * @return instance of cache manager // */ // public CacheManager getCacheManager (); // // /** // * get instance of permission manager // * // * @return instance of permission manager // */ // @Deprecated // public PermissionManager getPermissionManager (); // // /** // * set instance of permission manager // * // * @param permissionManager instance of permission manager // */ // @Deprecated // public void setPermissionManager (PermissionManager permissionManager); // // /** // * get permission service // * // * @return permission service // */ // public PermissionService getPermissionService (); // // /** // * set permission service // * // * @param service instance of permission service // */ // public void setPermissionService (PermissionService service); // // /** // * check, if user has permission // * // * @param request api request // * @param permission permission token // * // * @return true, if user has permission // */ // public boolean checkPermission (ApiRequest request, String permission); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/module/IModule.java import com.jukusoft.erp.lib.context.AppContext; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus; package com.jukusoft.erp.lib.module; public interface IModule { /** * get a reference to the Vert.x instance that deployed this verticle * * @return reference to the Vert.x instance */ public Vertx getVertx (); /** * get instance of logger */
public ILogging getLogger ();
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/module/IModule.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/context/AppContext.java // public interface AppContext { // // public Vertx getVertx (); // // public ILogging getLogger (); // // /** // * get hazelcast instance // * // * @return instance of hazelcast // */ // public HazelcastInstance getHazelcast (); // // /** // * get instance of session manager // * // * @return instance of session manager // */ // public SessionManager getSessionManager (); // // /** // * get instance of database manager // * // * @return instance of database manager // */ // public DatabaseManager getDatabaseManager (); // // /** // * get instance of cache manager // * // * @return instance of cache manager // */ // public CacheManager getCacheManager (); // // /** // * get instance of permission manager // * // * @return instance of permission manager // */ // @Deprecated // public PermissionManager getPermissionManager (); // // /** // * set instance of permission manager // * // * @param permissionManager instance of permission manager // */ // @Deprecated // public void setPermissionManager (PermissionManager permissionManager); // // /** // * get permission service // * // * @return permission service // */ // public PermissionService getPermissionService (); // // /** // * set permission service // * // * @param service instance of permission service // */ // public void setPermissionService (PermissionService service); // // /** // * check, if user has permission // * // * @param request api request // * @param permission permission token // * // * @return true, if user has permission // */ // public boolean checkPermission (ApiRequest request, String permission); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // }
import com.jukusoft.erp.lib.context.AppContext; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus;
package com.jukusoft.erp.lib.module; public interface IModule { /** * get a reference to the Vert.x instance that deployed this verticle * * @return reference to the Vert.x instance */ public Vertx getVertx (); /** * get instance of logger */ public ILogging getLogger (); /** * get instance of event bus * * @return instance of event bus */ public EventBus getEventBus (); /** * initialize module */
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/context/AppContext.java // public interface AppContext { // // public Vertx getVertx (); // // public ILogging getLogger (); // // /** // * get hazelcast instance // * // * @return instance of hazelcast // */ // public HazelcastInstance getHazelcast (); // // /** // * get instance of session manager // * // * @return instance of session manager // */ // public SessionManager getSessionManager (); // // /** // * get instance of database manager // * // * @return instance of database manager // */ // public DatabaseManager getDatabaseManager (); // // /** // * get instance of cache manager // * // * @return instance of cache manager // */ // public CacheManager getCacheManager (); // // /** // * get instance of permission manager // * // * @return instance of permission manager // */ // @Deprecated // public PermissionManager getPermissionManager (); // // /** // * set instance of permission manager // * // * @param permissionManager instance of permission manager // */ // @Deprecated // public void setPermissionManager (PermissionManager permissionManager); // // /** // * get permission service // * // * @return permission service // */ // public PermissionService getPermissionService (); // // /** // * set permission service // * // * @param service instance of permission service // */ // public void setPermissionService (PermissionService service); // // /** // * check, if user has permission // * // * @param request api request // * @param permission permission token // * // * @return true, if user has permission // */ // public boolean checkPermission (ApiRequest request, String permission); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/module/IModule.java import com.jukusoft.erp.lib.context.AppContext; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus; package com.jukusoft.erp.lib.module; public interface IModule { /** * get a reference to the Vert.x instance that deployed this verticle * * @return reference to the Vert.x instance */ public Vertx getVertx (); /** * get instance of logger */ public ILogging getLogger (); /** * get instance of event bus * * @return instance of event bus */ public EventBus getEventBus (); /** * initialize module */
public void init (Vertx vertx, AppContext context, ILogging logger);
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/HazelcastCache.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/ICache.java // public interface ICache { // // public void put (String key, JsonObject data); // // default void putArray (String key, JsonArray array) { // if (array == null) { // throw new NullPointerException("array cannot be null."); // } // // JsonObject obj = new JsonObject(); // obj.put("array", array); // // put(key, obj); // } // // public void remove (String key); // // public void removeAll (); // // public boolean contains (String key); // // public JsonObject get (String key); // // default JsonArray getArray (String key) { // JsonObject obj = get(key); // // if (obj == null) { // return null; // } // // if (!obj.containsKey("array")) { // throw new IllegalStateException("cached object isnt an array."); // } // // return obj.getJsonArray("array"); // } // // public void cleanUp (); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // }
import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.json.JsonObject;
package com.jukusoft.erp.lib.cache.impl; public class HazelcastCache implements ICache { protected IMap<String,String> cacheMap = null;
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/ICache.java // public interface ICache { // // public void put (String key, JsonObject data); // // default void putArray (String key, JsonArray array) { // if (array == null) { // throw new NullPointerException("array cannot be null."); // } // // JsonObject obj = new JsonObject(); // obj.put("array", array); // // put(key, obj); // } // // public void remove (String key); // // public void removeAll (); // // public boolean contains (String key); // // public JsonObject get (String key); // // default JsonArray getArray (String key) { // JsonObject obj = get(key); // // if (obj == null) { // return null; // } // // if (!obj.containsKey("array")) { // throw new IllegalStateException("cached object isnt an array."); // } // // return obj.getJsonArray("array"); // } // // public void cleanUp (); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/HazelcastCache.java import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.json.JsonObject; package com.jukusoft.erp.lib.cache.impl; public class HazelcastCache implements ICache { protected IMap<String,String> cacheMap = null;
public HazelcastCache (HazelcastInstance hazelcastInstance, String cacheName, ILogging logger) {
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheManager.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/DefaultCacheManager.java // public class DefaultCacheManager implements CacheManager { // // //local cache directory // protected File localCacheDir = null; // // //instance of hazelcast // protected HazelcastInstance hazelcastInstance = null; // // //instance of logger // protected ILogging logger = null; // // //map with all cache instances // protected Map<String,ICache> cacheMap = new ConcurrentHashMap<>(); // // public DefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) { // this.localCacheDir = localCacheDir; // this.hazelcastInstance = hazelcastInstance; // this.logger = logger; // } // // @Override // public ICache getCache(String cacheName) { // return this.cacheMap.get(cacheName); // } // // @Override // public ICache getOrCreateCache(String cacheName, CacheTypes cacheType) { // //check, if cache is present // if (this.containsCache(cacheName)) { // //get cache // return this.getCache(cacheName); // } else { // //create new cache // return this.createCache(cacheName, cacheType); // } // } // // @Override // public boolean containsCache(String cacheName) { // return this.getCache(cacheName) != null; // } // // @Override // public ICache createCache(String cacheName, CacheTypes type) { // //first check, if cache already exists // if (this.getCache(cacheName) != null) { // throw new IllegalStateException("cache '" + cacheName + "' does already exists."); // } // // ICache cache = null; // // switch (type) { // case FILE_CACHE: // cache = new FileSystemCache(localCacheDir.getAbsolutePath() + "/" + cacheName.toLowerCase() + "/", cacheName, this.logger); // break; // // case LOCAL_MEMORY_CACHE: // cache = new LocalMemoryCache(this.logger); // break; // // case HAZELCAST_CACHE: // cache = new HazelcastCache(this.hazelcastInstance, cacheName, this.logger); // break; // // default: // throw new IllegalArgumentException("Unknown cache type: " + type); // } // // this.cacheMap.put(cacheName, cache); // // return cache; // } // // @Override // public void removeCache(String cacheName) { // ICache cache = this.getCache(cacheName); // // //remove cache from map // this.cacheMap.remove(cacheName); // // //cleanUp cache if neccessary // if (cache != null) { // cache.cleanUp(); // } // } // // @Override // public List<String> listCacheNames() { // List<String> list = new ArrayList<>(); // // for (Map.Entry<String,ICache> entry : this.cacheMap.entrySet()) { // //add cache name to list // list.add(entry.getKey()); // } // // return list; // } // // @Override // public void cleanUp() { // for (Map.Entry<String,ICache> entry : this.cacheMap.entrySet()) { // entry.getValue().cleanUp(); // } // } // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // }
import com.hazelcast.core.HazelcastInstance; import com.jukusoft.erp.lib.cache.impl.DefaultCacheManager; import com.jukusoft.erp.lib.logging.ILogging; import java.io.File; import java.util.List;
package com.jukusoft.erp.lib.cache; public interface CacheManager { /** * get instance of cache * * @param cacheName name of cache * * @return instance of cache or null, if cache doesnt exists */ public ICache getCache (String cacheName); /** * get instance of cache or create an new one, if cache doesnt exists * * @param cacheName name of cache * * @return instance of cache or null, if cache doesnt exists */ public ICache getOrCreateCache (String cacheName, CacheTypes cacheType); /** * check, if cache is present * * @param cacheName name of cache */ public boolean containsCache (String cacheName); /** * crate an new cache instance * * @param cacheName name of cache * @param type type of cache * * @return instance of new cache */ public ICache createCache (String cacheName, CacheTypes type); /** * remove cache and cleanup values * * @param cacheName name of cache */ public void removeCache (String cacheName); /** * list names of all caches * * @return list with all cache names */ public List<String> listCacheNames (); /** * clean up outdated entries from all caches */ public void cleanUp (); /** * create default cache manager * * @param localCacheDir local cache directory * @param hazelcastInstance instance of hazelcast */
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/DefaultCacheManager.java // public class DefaultCacheManager implements CacheManager { // // //local cache directory // protected File localCacheDir = null; // // //instance of hazelcast // protected HazelcastInstance hazelcastInstance = null; // // //instance of logger // protected ILogging logger = null; // // //map with all cache instances // protected Map<String,ICache> cacheMap = new ConcurrentHashMap<>(); // // public DefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) { // this.localCacheDir = localCacheDir; // this.hazelcastInstance = hazelcastInstance; // this.logger = logger; // } // // @Override // public ICache getCache(String cacheName) { // return this.cacheMap.get(cacheName); // } // // @Override // public ICache getOrCreateCache(String cacheName, CacheTypes cacheType) { // //check, if cache is present // if (this.containsCache(cacheName)) { // //get cache // return this.getCache(cacheName); // } else { // //create new cache // return this.createCache(cacheName, cacheType); // } // } // // @Override // public boolean containsCache(String cacheName) { // return this.getCache(cacheName) != null; // } // // @Override // public ICache createCache(String cacheName, CacheTypes type) { // //first check, if cache already exists // if (this.getCache(cacheName) != null) { // throw new IllegalStateException("cache '" + cacheName + "' does already exists."); // } // // ICache cache = null; // // switch (type) { // case FILE_CACHE: // cache = new FileSystemCache(localCacheDir.getAbsolutePath() + "/" + cacheName.toLowerCase() + "/", cacheName, this.logger); // break; // // case LOCAL_MEMORY_CACHE: // cache = new LocalMemoryCache(this.logger); // break; // // case HAZELCAST_CACHE: // cache = new HazelcastCache(this.hazelcastInstance, cacheName, this.logger); // break; // // default: // throw new IllegalArgumentException("Unknown cache type: " + type); // } // // this.cacheMap.put(cacheName, cache); // // return cache; // } // // @Override // public void removeCache(String cacheName) { // ICache cache = this.getCache(cacheName); // // //remove cache from map // this.cacheMap.remove(cacheName); // // //cleanUp cache if neccessary // if (cache != null) { // cache.cleanUp(); // } // } // // @Override // public List<String> listCacheNames() { // List<String> list = new ArrayList<>(); // // for (Map.Entry<String,ICache> entry : this.cacheMap.entrySet()) { // //add cache name to list // list.add(entry.getKey()); // } // // return list; // } // // @Override // public void cleanUp() { // for (Map.Entry<String,ICache> entry : this.cacheMap.entrySet()) { // entry.getValue().cleanUp(); // } // } // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheManager.java import com.hazelcast.core.HazelcastInstance; import com.jukusoft.erp.lib.cache.impl.DefaultCacheManager; import com.jukusoft.erp.lib.logging.ILogging; import java.io.File; import java.util.List; package com.jukusoft.erp.lib.cache; public interface CacheManager { /** * get instance of cache * * @param cacheName name of cache * * @return instance of cache or null, if cache doesnt exists */ public ICache getCache (String cacheName); /** * get instance of cache or create an new one, if cache doesnt exists * * @param cacheName name of cache * * @return instance of cache or null, if cache doesnt exists */ public ICache getOrCreateCache (String cacheName, CacheTypes cacheType); /** * check, if cache is present * * @param cacheName name of cache */ public boolean containsCache (String cacheName); /** * crate an new cache instance * * @param cacheName name of cache * @param type type of cache * * @return instance of new cache */ public ICache createCache (String cacheName, CacheTypes type); /** * remove cache and cleanup values * * @param cacheName name of cache */ public void removeCache (String cacheName); /** * list names of all caches * * @return list with all cache names */ public List<String> listCacheNames (); /** * clean up outdated entries from all caches */ public void cleanUp (); /** * create default cache manager * * @param localCacheDir local cache directory * @param hazelcastInstance instance of hazelcast */
public static CacheManager createDefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) {
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheManager.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/DefaultCacheManager.java // public class DefaultCacheManager implements CacheManager { // // //local cache directory // protected File localCacheDir = null; // // //instance of hazelcast // protected HazelcastInstance hazelcastInstance = null; // // //instance of logger // protected ILogging logger = null; // // //map with all cache instances // protected Map<String,ICache> cacheMap = new ConcurrentHashMap<>(); // // public DefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) { // this.localCacheDir = localCacheDir; // this.hazelcastInstance = hazelcastInstance; // this.logger = logger; // } // // @Override // public ICache getCache(String cacheName) { // return this.cacheMap.get(cacheName); // } // // @Override // public ICache getOrCreateCache(String cacheName, CacheTypes cacheType) { // //check, if cache is present // if (this.containsCache(cacheName)) { // //get cache // return this.getCache(cacheName); // } else { // //create new cache // return this.createCache(cacheName, cacheType); // } // } // // @Override // public boolean containsCache(String cacheName) { // return this.getCache(cacheName) != null; // } // // @Override // public ICache createCache(String cacheName, CacheTypes type) { // //first check, if cache already exists // if (this.getCache(cacheName) != null) { // throw new IllegalStateException("cache '" + cacheName + "' does already exists."); // } // // ICache cache = null; // // switch (type) { // case FILE_CACHE: // cache = new FileSystemCache(localCacheDir.getAbsolutePath() + "/" + cacheName.toLowerCase() + "/", cacheName, this.logger); // break; // // case LOCAL_MEMORY_CACHE: // cache = new LocalMemoryCache(this.logger); // break; // // case HAZELCAST_CACHE: // cache = new HazelcastCache(this.hazelcastInstance, cacheName, this.logger); // break; // // default: // throw new IllegalArgumentException("Unknown cache type: " + type); // } // // this.cacheMap.put(cacheName, cache); // // return cache; // } // // @Override // public void removeCache(String cacheName) { // ICache cache = this.getCache(cacheName); // // //remove cache from map // this.cacheMap.remove(cacheName); // // //cleanUp cache if neccessary // if (cache != null) { // cache.cleanUp(); // } // } // // @Override // public List<String> listCacheNames() { // List<String> list = new ArrayList<>(); // // for (Map.Entry<String,ICache> entry : this.cacheMap.entrySet()) { // //add cache name to list // list.add(entry.getKey()); // } // // return list; // } // // @Override // public void cleanUp() { // for (Map.Entry<String,ICache> entry : this.cacheMap.entrySet()) { // entry.getValue().cleanUp(); // } // } // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // }
import com.hazelcast.core.HazelcastInstance; import com.jukusoft.erp.lib.cache.impl.DefaultCacheManager; import com.jukusoft.erp.lib.logging.ILogging; import java.io.File; import java.util.List;
package com.jukusoft.erp.lib.cache; public interface CacheManager { /** * get instance of cache * * @param cacheName name of cache * * @return instance of cache or null, if cache doesnt exists */ public ICache getCache (String cacheName); /** * get instance of cache or create an new one, if cache doesnt exists * * @param cacheName name of cache * * @return instance of cache or null, if cache doesnt exists */ public ICache getOrCreateCache (String cacheName, CacheTypes cacheType); /** * check, if cache is present * * @param cacheName name of cache */ public boolean containsCache (String cacheName); /** * crate an new cache instance * * @param cacheName name of cache * @param type type of cache * * @return instance of new cache */ public ICache createCache (String cacheName, CacheTypes type); /** * remove cache and cleanup values * * @param cacheName name of cache */ public void removeCache (String cacheName); /** * list names of all caches * * @return list with all cache names */ public List<String> listCacheNames (); /** * clean up outdated entries from all caches */ public void cleanUp (); /** * create default cache manager * * @param localCacheDir local cache directory * @param hazelcastInstance instance of hazelcast */ public static CacheManager createDefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) {
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/DefaultCacheManager.java // public class DefaultCacheManager implements CacheManager { // // //local cache directory // protected File localCacheDir = null; // // //instance of hazelcast // protected HazelcastInstance hazelcastInstance = null; // // //instance of logger // protected ILogging logger = null; // // //map with all cache instances // protected Map<String,ICache> cacheMap = new ConcurrentHashMap<>(); // // public DefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) { // this.localCacheDir = localCacheDir; // this.hazelcastInstance = hazelcastInstance; // this.logger = logger; // } // // @Override // public ICache getCache(String cacheName) { // return this.cacheMap.get(cacheName); // } // // @Override // public ICache getOrCreateCache(String cacheName, CacheTypes cacheType) { // //check, if cache is present // if (this.containsCache(cacheName)) { // //get cache // return this.getCache(cacheName); // } else { // //create new cache // return this.createCache(cacheName, cacheType); // } // } // // @Override // public boolean containsCache(String cacheName) { // return this.getCache(cacheName) != null; // } // // @Override // public ICache createCache(String cacheName, CacheTypes type) { // //first check, if cache already exists // if (this.getCache(cacheName) != null) { // throw new IllegalStateException("cache '" + cacheName + "' does already exists."); // } // // ICache cache = null; // // switch (type) { // case FILE_CACHE: // cache = new FileSystemCache(localCacheDir.getAbsolutePath() + "/" + cacheName.toLowerCase() + "/", cacheName, this.logger); // break; // // case LOCAL_MEMORY_CACHE: // cache = new LocalMemoryCache(this.logger); // break; // // case HAZELCAST_CACHE: // cache = new HazelcastCache(this.hazelcastInstance, cacheName, this.logger); // break; // // default: // throw new IllegalArgumentException("Unknown cache type: " + type); // } // // this.cacheMap.put(cacheName, cache); // // return cache; // } // // @Override // public void removeCache(String cacheName) { // ICache cache = this.getCache(cacheName); // // //remove cache from map // this.cacheMap.remove(cacheName); // // //cleanUp cache if neccessary // if (cache != null) { // cache.cleanUp(); // } // } // // @Override // public List<String> listCacheNames() { // List<String> list = new ArrayList<>(); // // for (Map.Entry<String,ICache> entry : this.cacheMap.entrySet()) { // //add cache name to list // list.add(entry.getKey()); // } // // return list; // } // // @Override // public void cleanUp() { // for (Map.Entry<String,ICache> entry : this.cacheMap.entrySet()) { // entry.getValue().cleanUp(); // } // } // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheManager.java import com.hazelcast.core.HazelcastInstance; import com.jukusoft.erp.lib.cache.impl.DefaultCacheManager; import com.jukusoft.erp.lib.logging.ILogging; import java.io.File; import java.util.List; package com.jukusoft.erp.lib.cache; public interface CacheManager { /** * get instance of cache * * @param cacheName name of cache * * @return instance of cache or null, if cache doesnt exists */ public ICache getCache (String cacheName); /** * get instance of cache or create an new one, if cache doesnt exists * * @param cacheName name of cache * * @return instance of cache or null, if cache doesnt exists */ public ICache getOrCreateCache (String cacheName, CacheTypes cacheType); /** * check, if cache is present * * @param cacheName name of cache */ public boolean containsCache (String cacheName); /** * crate an new cache instance * * @param cacheName name of cache * @param type type of cache * * @return instance of new cache */ public ICache createCache (String cacheName, CacheTypes type); /** * remove cache and cleanup values * * @param cacheName name of cache */ public void removeCache (String cacheName); /** * list names of all caches * * @return list with all cache names */ public List<String> listCacheNames (); /** * clean up outdated entries from all caches */ public void cleanUp (); /** * create default cache manager * * @param localCacheDir local cache directory * @param hazelcastInstance instance of hazelcast */ public static CacheManager createDefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) {
return new DefaultCacheManager(localCacheDir, hazelcastInstance, logger);
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/message/request/ApiRequest.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/exception/HandlerException.java // public class HandlerException extends RuntimeException { // // public HandlerException (String message) { // super(message); // } // // }
import com.jukusoft.erp.lib.exception.HandlerException; import io.vertx.core.json.JsonObject; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List;
package com.jukusoft.erp.lib.message.request; public class ApiRequest { //name of event protected String eventName = ""; //json data protected JSONObject data = null; protected String ackID = ""; //cluster wide unique message id for logging protected long messageID = 0; //external ID (for ack requests, generated by client), UUID as string protected String externalID = ""; //meta information protected JSONObject meta = new JSONObject(); protected String sessionID = ""; protected boolean isLoggedIn = false; protected long userID = -1; //user permissions protected List<String> permissions = new ArrayList<>(); /** * default constructor * * @param event event name * @param data json data */ public ApiRequest (String event, JSONObject data, long messageID, String externalID, String sessionID, boolean isLoggedIn, long userID) { this.eventName = event; this.data = data; this.messageID = messageID; this.externalID = externalID; this.sessionID = sessionID; this.isLoggedIn = isLoggedIn; this.userID = userID; } protected ApiRequest () { // } public String getEvent () { return this.eventName; } public JSONObject getData () { return this.data; } /** * check, if param exists, else throw an exception * * @param key key of param */
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/exception/HandlerException.java // public class HandlerException extends RuntimeException { // // public HandlerException (String message) { // super(message); // } // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/message/request/ApiRequest.java import com.jukusoft.erp.lib.exception.HandlerException; import io.vertx.core.json.JsonObject; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; package com.jukusoft.erp.lib.message.request; public class ApiRequest { //name of event protected String eventName = ""; //json data protected JSONObject data = null; protected String ackID = ""; //cluster wide unique message id for logging protected long messageID = 0; //external ID (for ack requests, generated by client), UUID as string protected String externalID = ""; //meta information protected JSONObject meta = new JSONObject(); protected String sessionID = ""; protected boolean isLoggedIn = false; protected long userID = -1; //user permissions protected List<String> permissions = new ArrayList<>(); /** * default constructor * * @param event event name * @param data json data */ public ApiRequest (String event, JSONObject data, long messageID, String externalID, String sessionID, boolean isLoggedIn, long userID) { this.eventName = event; this.data = data; this.messageID = messageID; this.externalID = externalID; this.sessionID = sessionID; this.isLoggedIn = isLoggedIn; this.userID = userID; } protected ApiRequest () { // } public String getEvent () { return this.eventName; } public JSONObject getData () { return this.data; } /** * check, if param exists, else throw an exception * * @param key key of param */
public void checkParam (String key) throws HandlerException {
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/controller/AbstractController.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/context/AppContext.java // public interface AppContext { // // public Vertx getVertx (); // // public ILogging getLogger (); // // /** // * get hazelcast instance // * // * @return instance of hazelcast // */ // public HazelcastInstance getHazelcast (); // // /** // * get instance of session manager // * // * @return instance of session manager // */ // public SessionManager getSessionManager (); // // /** // * get instance of database manager // * // * @return instance of database manager // */ // public DatabaseManager getDatabaseManager (); // // /** // * get instance of cache manager // * // * @return instance of cache manager // */ // public CacheManager getCacheManager (); // // /** // * get instance of permission manager // * // * @return instance of permission manager // */ // @Deprecated // public PermissionManager getPermissionManager (); // // /** // * set instance of permission manager // * // * @param permissionManager instance of permission manager // */ // @Deprecated // public void setPermissionManager (PermissionManager permissionManager); // // /** // * get permission service // * // * @return permission service // */ // public PermissionService getPermissionService (); // // /** // * set permission service // * // * @param service instance of permission service // */ // public void setPermissionService (PermissionService service); // // /** // * check, if user has permission // * // * @param request api request // * @param permission permission token // * // * @return true, if user has permission // */ // public boolean checkPermission (ApiRequest request, String permission); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // }
import com.jukusoft.erp.lib.context.AppContext; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus;
package com.jukusoft.erp.lib.controller; public class AbstractController implements IController { //instance of vertx protected Vertx vertx = null; //instance of module context
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/context/AppContext.java // public interface AppContext { // // public Vertx getVertx (); // // public ILogging getLogger (); // // /** // * get hazelcast instance // * // * @return instance of hazelcast // */ // public HazelcastInstance getHazelcast (); // // /** // * get instance of session manager // * // * @return instance of session manager // */ // public SessionManager getSessionManager (); // // /** // * get instance of database manager // * // * @return instance of database manager // */ // public DatabaseManager getDatabaseManager (); // // /** // * get instance of cache manager // * // * @return instance of cache manager // */ // public CacheManager getCacheManager (); // // /** // * get instance of permission manager // * // * @return instance of permission manager // */ // @Deprecated // public PermissionManager getPermissionManager (); // // /** // * set instance of permission manager // * // * @param permissionManager instance of permission manager // */ // @Deprecated // public void setPermissionManager (PermissionManager permissionManager); // // /** // * get permission service // * // * @return permission service // */ // public PermissionService getPermissionService (); // // /** // * set permission service // * // * @param service instance of permission service // */ // public void setPermissionService (PermissionService service); // // /** // * check, if user has permission // * // * @param request api request // * @param permission permission token // * // * @return true, if user has permission // */ // public boolean checkPermission (ApiRequest request, String permission); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/controller/AbstractController.java import com.jukusoft.erp.lib.context.AppContext; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus; package com.jukusoft.erp.lib.controller; public class AbstractController implements IController { //instance of vertx protected Vertx vertx = null; //instance of module context
protected AppContext context = null;
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/controller/AbstractController.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/context/AppContext.java // public interface AppContext { // // public Vertx getVertx (); // // public ILogging getLogger (); // // /** // * get hazelcast instance // * // * @return instance of hazelcast // */ // public HazelcastInstance getHazelcast (); // // /** // * get instance of session manager // * // * @return instance of session manager // */ // public SessionManager getSessionManager (); // // /** // * get instance of database manager // * // * @return instance of database manager // */ // public DatabaseManager getDatabaseManager (); // // /** // * get instance of cache manager // * // * @return instance of cache manager // */ // public CacheManager getCacheManager (); // // /** // * get instance of permission manager // * // * @return instance of permission manager // */ // @Deprecated // public PermissionManager getPermissionManager (); // // /** // * set instance of permission manager // * // * @param permissionManager instance of permission manager // */ // @Deprecated // public void setPermissionManager (PermissionManager permissionManager); // // /** // * get permission service // * // * @return permission service // */ // public PermissionService getPermissionService (); // // /** // * set permission service // * // * @param service instance of permission service // */ // public void setPermissionService (PermissionService service); // // /** // * check, if user has permission // * // * @param request api request // * @param permission permission token // * // * @return true, if user has permission // */ // public boolean checkPermission (ApiRequest request, String permission); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // }
import com.jukusoft.erp.lib.context.AppContext; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus;
package com.jukusoft.erp.lib.controller; public class AbstractController implements IController { //instance of vertx protected Vertx vertx = null; //instance of module context protected AppContext context = null; //instance of logger
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/context/AppContext.java // public interface AppContext { // // public Vertx getVertx (); // // public ILogging getLogger (); // // /** // * get hazelcast instance // * // * @return instance of hazelcast // */ // public HazelcastInstance getHazelcast (); // // /** // * get instance of session manager // * // * @return instance of session manager // */ // public SessionManager getSessionManager (); // // /** // * get instance of database manager // * // * @return instance of database manager // */ // public DatabaseManager getDatabaseManager (); // // /** // * get instance of cache manager // * // * @return instance of cache manager // */ // public CacheManager getCacheManager (); // // /** // * get instance of permission manager // * // * @return instance of permission manager // */ // @Deprecated // public PermissionManager getPermissionManager (); // // /** // * set instance of permission manager // * // * @param permissionManager instance of permission manager // */ // @Deprecated // public void setPermissionManager (PermissionManager permissionManager); // // /** // * get permission service // * // * @return permission service // */ // public PermissionService getPermissionService (); // // /** // * set permission service // * // * @param service instance of permission service // */ // public void setPermissionService (PermissionService service); // // /** // * check, if user has permission // * // * @param request api request // * @param permission permission token // * // * @return true, if user has permission // */ // public boolean checkPermission (ApiRequest request, String permission); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/controller/AbstractController.java import com.jukusoft.erp.lib.context.AppContext; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus; package com.jukusoft.erp.lib.controller; public class AbstractController implements IController { //instance of vertx protected Vertx vertx = null; //instance of module context protected AppContext context = null; //instance of logger
protected ILogging logger = null;
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/database/MySQLDatabase.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/utils/FileUtils.java // public class FileUtils { // // /** // * read content from file // * // * @param path // * path to file // * @param encoding // * file encoding // * // * @throws IOException // * // * @return content of file as string // */ // public static String readFile(String path, Charset encoding) throws IOException { // if (!new File(path).exists()) { // throw new IOException("File doesnt exists: " + path); // } // // if (!new File(path).canRead()) { // throw new IOException("File isnt readable, please correct permissions: " + path); // } // // // read bytes from file // byte[] encoded = Files.readAllBytes(Paths.get(path)); // // // convert bytes to string with specific encoding and return string // return new String(encoded, encoding); // } // // /** // * read lines from file // * // * @param path // * path to file // * @param charset // * encoding of file // * // * @throws IOException // * // * @return list of lines from file // */ // public static List<String> readLines(String path, Charset charset) throws IOException { // if (!(new File(path)).exists()) { // throw new FileNotFoundException("Couldnt find file: " + path); // } // // return Files.readAllLines(Paths.get(path), charset); // } // // /** // * write text to file // * // * @param path // * path to file // * @param content // * content of file // * @param encoding // * file encoding // * // * @throws IOException // */ // public static void writeFile(String path, String content, Charset encoding) throws IOException { // Files.write(Paths.get(path), content.getBytes(encoding), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); // } // // /** // * get path to user.home directory // * // * @return path to user.home directory // */ // public static String getUserHomeDir () { // return System.getProperty("user.home"); // } // // public static String getAppHomeDir (String appName) { // return getUserHomeDir() + "/." + appName + "/"; // } // // }
import com.jukusoft.erp.lib.utils.FileUtils; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.jdbc.JDBCClient; import io.vertx.ext.sql.ResultSet; import io.vertx.ext.sql.SQLClient; import io.vertx.ext.sql.SQLConnection; import io.vertx.ext.sql.UpdateResult; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import static io.vertx.ext.sync.Sync.awaitResult;
package com.jukusoft.erp.lib.database; public class MySQLDatabase implements Database { //instance of vertx protected Vertx vertx = null; //sql client protected SQLClient client = null; //sql connection protected SQLConnection connection = null; //table prefix protected String prefix = ""; public MySQLDatabase (Vertx vertx) { this.vertx = vertx; } @Override public void connect (String configFile, Handler<Future<Void>> handler) throws IOException { //check, if config file exists if (!new File(configFile).exists()) { throw new FileNotFoundException("Couldnt found database config file '" + configFile + "'."); } //read file content
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/utils/FileUtils.java // public class FileUtils { // // /** // * read content from file // * // * @param path // * path to file // * @param encoding // * file encoding // * // * @throws IOException // * // * @return content of file as string // */ // public static String readFile(String path, Charset encoding) throws IOException { // if (!new File(path).exists()) { // throw new IOException("File doesnt exists: " + path); // } // // if (!new File(path).canRead()) { // throw new IOException("File isnt readable, please correct permissions: " + path); // } // // // read bytes from file // byte[] encoded = Files.readAllBytes(Paths.get(path)); // // // convert bytes to string with specific encoding and return string // return new String(encoded, encoding); // } // // /** // * read lines from file // * // * @param path // * path to file // * @param charset // * encoding of file // * // * @throws IOException // * // * @return list of lines from file // */ // public static List<String> readLines(String path, Charset charset) throws IOException { // if (!(new File(path)).exists()) { // throw new FileNotFoundException("Couldnt find file: " + path); // } // // return Files.readAllLines(Paths.get(path), charset); // } // // /** // * write text to file // * // * @param path // * path to file // * @param content // * content of file // * @param encoding // * file encoding // * // * @throws IOException // */ // public static void writeFile(String path, String content, Charset encoding) throws IOException { // Files.write(Paths.get(path), content.getBytes(encoding), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); // } // // /** // * get path to user.home directory // * // * @return path to user.home directory // */ // public static String getUserHomeDir () { // return System.getProperty("user.home"); // } // // public static String getAppHomeDir (String appName) { // return getUserHomeDir() + "/." + appName + "/"; // } // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/database/MySQLDatabase.java import com.jukusoft.erp.lib.utils.FileUtils; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.jdbc.JDBCClient; import io.vertx.ext.sql.ResultSet; import io.vertx.ext.sql.SQLClient; import io.vertx.ext.sql.SQLConnection; import io.vertx.ext.sql.UpdateResult; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import static io.vertx.ext.sync.Sync.awaitResult; package com.jukusoft.erp.lib.database; public class MySQLDatabase implements Database { //instance of vertx protected Vertx vertx = null; //sql client protected SQLClient client = null; //sql connection protected SQLConnection connection = null; //table prefix protected String prefix = ""; public MySQLDatabase (Vertx vertx) { this.vertx = vertx; } @Override public void connect (String configFile, Handler<Future<Void>> handler) throws IOException { //check, if config file exists if (!new File(configFile).exists()) { throw new FileNotFoundException("Couldnt found database config file '" + configFile + "'."); } //read file content
String content = FileUtils.readFile(configFile, StandardCharsets.UTF_8);
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/controller/IController.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/context/AppContext.java // public interface AppContext { // // public Vertx getVertx (); // // public ILogging getLogger (); // // /** // * get hazelcast instance // * // * @return instance of hazelcast // */ // public HazelcastInstance getHazelcast (); // // /** // * get instance of session manager // * // * @return instance of session manager // */ // public SessionManager getSessionManager (); // // /** // * get instance of database manager // * // * @return instance of database manager // */ // public DatabaseManager getDatabaseManager (); // // /** // * get instance of cache manager // * // * @return instance of cache manager // */ // public CacheManager getCacheManager (); // // /** // * get instance of permission manager // * // * @return instance of permission manager // */ // @Deprecated // public PermissionManager getPermissionManager (); // // /** // * set instance of permission manager // * // * @param permissionManager instance of permission manager // */ // @Deprecated // public void setPermissionManager (PermissionManager permissionManager); // // /** // * get permission service // * // * @return permission service // */ // public PermissionService getPermissionService (); // // /** // * set permission service // * // * @param service instance of permission service // */ // public void setPermissionService (PermissionService service); // // /** // * check, if user has permission // * // * @param request api request // * @param permission permission token // * // * @return true, if user has permission // */ // public boolean checkPermission (ApiRequest request, String permission); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // }
import com.jukusoft.erp.lib.context.AppContext; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus;
package com.jukusoft.erp.lib.controller; public interface IController { /** * get a reference to the Vert.x instance that deployed this verticle * * @return reference to the Vert.x instance */ public Vertx getVertx (); /** * get instance of logger */
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/context/AppContext.java // public interface AppContext { // // public Vertx getVertx (); // // public ILogging getLogger (); // // /** // * get hazelcast instance // * // * @return instance of hazelcast // */ // public HazelcastInstance getHazelcast (); // // /** // * get instance of session manager // * // * @return instance of session manager // */ // public SessionManager getSessionManager (); // // /** // * get instance of database manager // * // * @return instance of database manager // */ // public DatabaseManager getDatabaseManager (); // // /** // * get instance of cache manager // * // * @return instance of cache manager // */ // public CacheManager getCacheManager (); // // /** // * get instance of permission manager // * // * @return instance of permission manager // */ // @Deprecated // public PermissionManager getPermissionManager (); // // /** // * set instance of permission manager // * // * @param permissionManager instance of permission manager // */ // @Deprecated // public void setPermissionManager (PermissionManager permissionManager); // // /** // * get permission service // * // * @return permission service // */ // public PermissionService getPermissionService (); // // /** // * set permission service // * // * @param service instance of permission service // */ // public void setPermissionService (PermissionService service); // // /** // * check, if user has permission // * // * @param request api request // * @param permission permission token // * // * @return true, if user has permission // */ // public boolean checkPermission (ApiRequest request, String permission); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/controller/IController.java import com.jukusoft.erp.lib.context.AppContext; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus; package com.jukusoft.erp.lib.controller; public interface IController { /** * get a reference to the Vert.x instance that deployed this verticle * * @return reference to the Vert.x instance */ public Vertx getVertx (); /** * get instance of logger */
public ILogging getLogger ();
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/controller/IController.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/context/AppContext.java // public interface AppContext { // // public Vertx getVertx (); // // public ILogging getLogger (); // // /** // * get hazelcast instance // * // * @return instance of hazelcast // */ // public HazelcastInstance getHazelcast (); // // /** // * get instance of session manager // * // * @return instance of session manager // */ // public SessionManager getSessionManager (); // // /** // * get instance of database manager // * // * @return instance of database manager // */ // public DatabaseManager getDatabaseManager (); // // /** // * get instance of cache manager // * // * @return instance of cache manager // */ // public CacheManager getCacheManager (); // // /** // * get instance of permission manager // * // * @return instance of permission manager // */ // @Deprecated // public PermissionManager getPermissionManager (); // // /** // * set instance of permission manager // * // * @param permissionManager instance of permission manager // */ // @Deprecated // public void setPermissionManager (PermissionManager permissionManager); // // /** // * get permission service // * // * @return permission service // */ // public PermissionService getPermissionService (); // // /** // * set permission service // * // * @param service instance of permission service // */ // public void setPermissionService (PermissionService service); // // /** // * check, if user has permission // * // * @param request api request // * @param permission permission token // * // * @return true, if user has permission // */ // public boolean checkPermission (ApiRequest request, String permission); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // }
import com.jukusoft.erp.lib.context.AppContext; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus;
package com.jukusoft.erp.lib.controller; public interface IController { /** * get a reference to the Vert.x instance that deployed this verticle * * @return reference to the Vert.x instance */ public Vertx getVertx (); /** * get instance of logger */ public ILogging getLogger (); /** * get instance of event bus * * @return instance of event bus */ public EventBus getEventBus (); /** * initialize module */
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/context/AppContext.java // public interface AppContext { // // public Vertx getVertx (); // // public ILogging getLogger (); // // /** // * get hazelcast instance // * // * @return instance of hazelcast // */ // public HazelcastInstance getHazelcast (); // // /** // * get instance of session manager // * // * @return instance of session manager // */ // public SessionManager getSessionManager (); // // /** // * get instance of database manager // * // * @return instance of database manager // */ // public DatabaseManager getDatabaseManager (); // // /** // * get instance of cache manager // * // * @return instance of cache manager // */ // public CacheManager getCacheManager (); // // /** // * get instance of permission manager // * // * @return instance of permission manager // */ // @Deprecated // public PermissionManager getPermissionManager (); // // /** // * set instance of permission manager // * // * @param permissionManager instance of permission manager // */ // @Deprecated // public void setPermissionManager (PermissionManager permissionManager); // // /** // * get permission service // * // * @return permission service // */ // public PermissionService getPermissionService (); // // /** // * set permission service // * // * @param service instance of permission service // */ // public void setPermissionService (PermissionService service); // // /** // * check, if user has permission // * // * @param request api request // * @param permission permission token // * // * @return true, if user has permission // */ // public boolean checkPermission (ApiRequest request, String permission); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/controller/IController.java import com.jukusoft.erp.lib.context.AppContext; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus; package com.jukusoft.erp.lib.controller; public interface IController { /** * get a reference to the Vert.x instance that deployed this verticle * * @return reference to the Vert.x instance */ public Vertx getVertx (); /** * get instance of logger */ public ILogging getLogger (); /** * get instance of event bus * * @return instance of event bus */ public EventBus getEventBus (); /** * initialize module */
public void init (Vertx vertx, AppContext context, ILogging logger);
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/DefaultCacheManager.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheManager.java // public interface CacheManager { // // /** // * get instance of cache // * // * @param cacheName name of cache // * // * @return instance of cache or null, if cache doesnt exists // */ // public ICache getCache (String cacheName); // // /** // * get instance of cache or create an new one, if cache doesnt exists // * // * @param cacheName name of cache // * // * @return instance of cache or null, if cache doesnt exists // */ // public ICache getOrCreateCache (String cacheName, CacheTypes cacheType); // // /** // * check, if cache is present // * // * @param cacheName name of cache // */ // public boolean containsCache (String cacheName); // // /** // * crate an new cache instance // * // * @param cacheName name of cache // * @param type type of cache // * // * @return instance of new cache // */ // public ICache createCache (String cacheName, CacheTypes type); // // /** // * remove cache and cleanup values // * // * @param cacheName name of cache // */ // public void removeCache (String cacheName); // // /** // * list names of all caches // * // * @return list with all cache names // */ // public List<String> listCacheNames (); // // /** // * clean up outdated entries from all caches // */ // public void cleanUp (); // // /** // * create default cache manager // * // * @param localCacheDir local cache directory // * @param hazelcastInstance instance of hazelcast // */ // public static CacheManager createDefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) { // return new DefaultCacheManager(localCacheDir, hazelcastInstance, logger); // } // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheTypes.java // public enum CacheTypes { // // /** // * cache entries on filesystem // */ // FILE_CACHE, // // /** // * cache values on local memory cache // */ // LOCAL_MEMORY_CACHE, // // /** // * cache values in distributed hazelcast cache // */ // HAZELCAST_CACHE // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/ICache.java // public interface ICache { // // public void put (String key, JsonObject data); // // default void putArray (String key, JsonArray array) { // if (array == null) { // throw new NullPointerException("array cannot be null."); // } // // JsonObject obj = new JsonObject(); // obj.put("array", array); // // put(key, obj); // } // // public void remove (String key); // // public void removeAll (); // // public boolean contains (String key); // // public JsonObject get (String key); // // default JsonArray getArray (String key) { // JsonObject obj = get(key); // // if (obj == null) { // return null; // } // // if (!obj.containsKey("array")) { // throw new IllegalStateException("cached object isnt an array."); // } // // return obj.getJsonArray("array"); // } // // public void cleanUp (); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // }
import com.hazelcast.core.HazelcastInstance; import com.jukusoft.erp.lib.cache.CacheManager; import com.jukusoft.erp.lib.cache.CacheTypes; import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.logging.ILogging; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
package com.jukusoft.erp.lib.cache.impl; public class DefaultCacheManager implements CacheManager { //local cache directory protected File localCacheDir = null; //instance of hazelcast protected HazelcastInstance hazelcastInstance = null; //instance of logger
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheManager.java // public interface CacheManager { // // /** // * get instance of cache // * // * @param cacheName name of cache // * // * @return instance of cache or null, if cache doesnt exists // */ // public ICache getCache (String cacheName); // // /** // * get instance of cache or create an new one, if cache doesnt exists // * // * @param cacheName name of cache // * // * @return instance of cache or null, if cache doesnt exists // */ // public ICache getOrCreateCache (String cacheName, CacheTypes cacheType); // // /** // * check, if cache is present // * // * @param cacheName name of cache // */ // public boolean containsCache (String cacheName); // // /** // * crate an new cache instance // * // * @param cacheName name of cache // * @param type type of cache // * // * @return instance of new cache // */ // public ICache createCache (String cacheName, CacheTypes type); // // /** // * remove cache and cleanup values // * // * @param cacheName name of cache // */ // public void removeCache (String cacheName); // // /** // * list names of all caches // * // * @return list with all cache names // */ // public List<String> listCacheNames (); // // /** // * clean up outdated entries from all caches // */ // public void cleanUp (); // // /** // * create default cache manager // * // * @param localCacheDir local cache directory // * @param hazelcastInstance instance of hazelcast // */ // public static CacheManager createDefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) { // return new DefaultCacheManager(localCacheDir, hazelcastInstance, logger); // } // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheTypes.java // public enum CacheTypes { // // /** // * cache entries on filesystem // */ // FILE_CACHE, // // /** // * cache values on local memory cache // */ // LOCAL_MEMORY_CACHE, // // /** // * cache values in distributed hazelcast cache // */ // HAZELCAST_CACHE // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/ICache.java // public interface ICache { // // public void put (String key, JsonObject data); // // default void putArray (String key, JsonArray array) { // if (array == null) { // throw new NullPointerException("array cannot be null."); // } // // JsonObject obj = new JsonObject(); // obj.put("array", array); // // put(key, obj); // } // // public void remove (String key); // // public void removeAll (); // // public boolean contains (String key); // // public JsonObject get (String key); // // default JsonArray getArray (String key) { // JsonObject obj = get(key); // // if (obj == null) { // return null; // } // // if (!obj.containsKey("array")) { // throw new IllegalStateException("cached object isnt an array."); // } // // return obj.getJsonArray("array"); // } // // public void cleanUp (); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/DefaultCacheManager.java import com.hazelcast.core.HazelcastInstance; import com.jukusoft.erp.lib.cache.CacheManager; import com.jukusoft.erp.lib.cache.CacheTypes; import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.logging.ILogging; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; package com.jukusoft.erp.lib.cache.impl; public class DefaultCacheManager implements CacheManager { //local cache directory protected File localCacheDir = null; //instance of hazelcast protected HazelcastInstance hazelcastInstance = null; //instance of logger
protected ILogging logger = null;
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/DefaultCacheManager.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheManager.java // public interface CacheManager { // // /** // * get instance of cache // * // * @param cacheName name of cache // * // * @return instance of cache or null, if cache doesnt exists // */ // public ICache getCache (String cacheName); // // /** // * get instance of cache or create an new one, if cache doesnt exists // * // * @param cacheName name of cache // * // * @return instance of cache or null, if cache doesnt exists // */ // public ICache getOrCreateCache (String cacheName, CacheTypes cacheType); // // /** // * check, if cache is present // * // * @param cacheName name of cache // */ // public boolean containsCache (String cacheName); // // /** // * crate an new cache instance // * // * @param cacheName name of cache // * @param type type of cache // * // * @return instance of new cache // */ // public ICache createCache (String cacheName, CacheTypes type); // // /** // * remove cache and cleanup values // * // * @param cacheName name of cache // */ // public void removeCache (String cacheName); // // /** // * list names of all caches // * // * @return list with all cache names // */ // public List<String> listCacheNames (); // // /** // * clean up outdated entries from all caches // */ // public void cleanUp (); // // /** // * create default cache manager // * // * @param localCacheDir local cache directory // * @param hazelcastInstance instance of hazelcast // */ // public static CacheManager createDefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) { // return new DefaultCacheManager(localCacheDir, hazelcastInstance, logger); // } // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheTypes.java // public enum CacheTypes { // // /** // * cache entries on filesystem // */ // FILE_CACHE, // // /** // * cache values on local memory cache // */ // LOCAL_MEMORY_CACHE, // // /** // * cache values in distributed hazelcast cache // */ // HAZELCAST_CACHE // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/ICache.java // public interface ICache { // // public void put (String key, JsonObject data); // // default void putArray (String key, JsonArray array) { // if (array == null) { // throw new NullPointerException("array cannot be null."); // } // // JsonObject obj = new JsonObject(); // obj.put("array", array); // // put(key, obj); // } // // public void remove (String key); // // public void removeAll (); // // public boolean contains (String key); // // public JsonObject get (String key); // // default JsonArray getArray (String key) { // JsonObject obj = get(key); // // if (obj == null) { // return null; // } // // if (!obj.containsKey("array")) { // throw new IllegalStateException("cached object isnt an array."); // } // // return obj.getJsonArray("array"); // } // // public void cleanUp (); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // }
import com.hazelcast.core.HazelcastInstance; import com.jukusoft.erp.lib.cache.CacheManager; import com.jukusoft.erp.lib.cache.CacheTypes; import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.logging.ILogging; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
package com.jukusoft.erp.lib.cache.impl; public class DefaultCacheManager implements CacheManager { //local cache directory protected File localCacheDir = null; //instance of hazelcast protected HazelcastInstance hazelcastInstance = null; //instance of logger protected ILogging logger = null; //map with all cache instances
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheManager.java // public interface CacheManager { // // /** // * get instance of cache // * // * @param cacheName name of cache // * // * @return instance of cache or null, if cache doesnt exists // */ // public ICache getCache (String cacheName); // // /** // * get instance of cache or create an new one, if cache doesnt exists // * // * @param cacheName name of cache // * // * @return instance of cache or null, if cache doesnt exists // */ // public ICache getOrCreateCache (String cacheName, CacheTypes cacheType); // // /** // * check, if cache is present // * // * @param cacheName name of cache // */ // public boolean containsCache (String cacheName); // // /** // * crate an new cache instance // * // * @param cacheName name of cache // * @param type type of cache // * // * @return instance of new cache // */ // public ICache createCache (String cacheName, CacheTypes type); // // /** // * remove cache and cleanup values // * // * @param cacheName name of cache // */ // public void removeCache (String cacheName); // // /** // * list names of all caches // * // * @return list with all cache names // */ // public List<String> listCacheNames (); // // /** // * clean up outdated entries from all caches // */ // public void cleanUp (); // // /** // * create default cache manager // * // * @param localCacheDir local cache directory // * @param hazelcastInstance instance of hazelcast // */ // public static CacheManager createDefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) { // return new DefaultCacheManager(localCacheDir, hazelcastInstance, logger); // } // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheTypes.java // public enum CacheTypes { // // /** // * cache entries on filesystem // */ // FILE_CACHE, // // /** // * cache values on local memory cache // */ // LOCAL_MEMORY_CACHE, // // /** // * cache values in distributed hazelcast cache // */ // HAZELCAST_CACHE // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/ICache.java // public interface ICache { // // public void put (String key, JsonObject data); // // default void putArray (String key, JsonArray array) { // if (array == null) { // throw new NullPointerException("array cannot be null."); // } // // JsonObject obj = new JsonObject(); // obj.put("array", array); // // put(key, obj); // } // // public void remove (String key); // // public void removeAll (); // // public boolean contains (String key); // // public JsonObject get (String key); // // default JsonArray getArray (String key) { // JsonObject obj = get(key); // // if (obj == null) { // return null; // } // // if (!obj.containsKey("array")) { // throw new IllegalStateException("cached object isnt an array."); // } // // return obj.getJsonArray("array"); // } // // public void cleanUp (); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/DefaultCacheManager.java import com.hazelcast.core.HazelcastInstance; import com.jukusoft.erp.lib.cache.CacheManager; import com.jukusoft.erp.lib.cache.CacheTypes; import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.logging.ILogging; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; package com.jukusoft.erp.lib.cache.impl; public class DefaultCacheManager implements CacheManager { //local cache directory protected File localCacheDir = null; //instance of hazelcast protected HazelcastInstance hazelcastInstance = null; //instance of logger protected ILogging logger = null; //map with all cache instances
protected Map<String,ICache> cacheMap = new ConcurrentHashMap<>();
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/DefaultCacheManager.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheManager.java // public interface CacheManager { // // /** // * get instance of cache // * // * @param cacheName name of cache // * // * @return instance of cache or null, if cache doesnt exists // */ // public ICache getCache (String cacheName); // // /** // * get instance of cache or create an new one, if cache doesnt exists // * // * @param cacheName name of cache // * // * @return instance of cache or null, if cache doesnt exists // */ // public ICache getOrCreateCache (String cacheName, CacheTypes cacheType); // // /** // * check, if cache is present // * // * @param cacheName name of cache // */ // public boolean containsCache (String cacheName); // // /** // * crate an new cache instance // * // * @param cacheName name of cache // * @param type type of cache // * // * @return instance of new cache // */ // public ICache createCache (String cacheName, CacheTypes type); // // /** // * remove cache and cleanup values // * // * @param cacheName name of cache // */ // public void removeCache (String cacheName); // // /** // * list names of all caches // * // * @return list with all cache names // */ // public List<String> listCacheNames (); // // /** // * clean up outdated entries from all caches // */ // public void cleanUp (); // // /** // * create default cache manager // * // * @param localCacheDir local cache directory // * @param hazelcastInstance instance of hazelcast // */ // public static CacheManager createDefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) { // return new DefaultCacheManager(localCacheDir, hazelcastInstance, logger); // } // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheTypes.java // public enum CacheTypes { // // /** // * cache entries on filesystem // */ // FILE_CACHE, // // /** // * cache values on local memory cache // */ // LOCAL_MEMORY_CACHE, // // /** // * cache values in distributed hazelcast cache // */ // HAZELCAST_CACHE // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/ICache.java // public interface ICache { // // public void put (String key, JsonObject data); // // default void putArray (String key, JsonArray array) { // if (array == null) { // throw new NullPointerException("array cannot be null."); // } // // JsonObject obj = new JsonObject(); // obj.put("array", array); // // put(key, obj); // } // // public void remove (String key); // // public void removeAll (); // // public boolean contains (String key); // // public JsonObject get (String key); // // default JsonArray getArray (String key) { // JsonObject obj = get(key); // // if (obj == null) { // return null; // } // // if (!obj.containsKey("array")) { // throw new IllegalStateException("cached object isnt an array."); // } // // return obj.getJsonArray("array"); // } // // public void cleanUp (); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // }
import com.hazelcast.core.HazelcastInstance; import com.jukusoft.erp.lib.cache.CacheManager; import com.jukusoft.erp.lib.cache.CacheTypes; import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.logging.ILogging; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
package com.jukusoft.erp.lib.cache.impl; public class DefaultCacheManager implements CacheManager { //local cache directory protected File localCacheDir = null; //instance of hazelcast protected HazelcastInstance hazelcastInstance = null; //instance of logger protected ILogging logger = null; //map with all cache instances protected Map<String,ICache> cacheMap = new ConcurrentHashMap<>(); public DefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) { this.localCacheDir = localCacheDir; this.hazelcastInstance = hazelcastInstance; this.logger = logger; } @Override public ICache getCache(String cacheName) { return this.cacheMap.get(cacheName); } @Override
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheManager.java // public interface CacheManager { // // /** // * get instance of cache // * // * @param cacheName name of cache // * // * @return instance of cache or null, if cache doesnt exists // */ // public ICache getCache (String cacheName); // // /** // * get instance of cache or create an new one, if cache doesnt exists // * // * @param cacheName name of cache // * // * @return instance of cache or null, if cache doesnt exists // */ // public ICache getOrCreateCache (String cacheName, CacheTypes cacheType); // // /** // * check, if cache is present // * // * @param cacheName name of cache // */ // public boolean containsCache (String cacheName); // // /** // * crate an new cache instance // * // * @param cacheName name of cache // * @param type type of cache // * // * @return instance of new cache // */ // public ICache createCache (String cacheName, CacheTypes type); // // /** // * remove cache and cleanup values // * // * @param cacheName name of cache // */ // public void removeCache (String cacheName); // // /** // * list names of all caches // * // * @return list with all cache names // */ // public List<String> listCacheNames (); // // /** // * clean up outdated entries from all caches // */ // public void cleanUp (); // // /** // * create default cache manager // * // * @param localCacheDir local cache directory // * @param hazelcastInstance instance of hazelcast // */ // public static CacheManager createDefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) { // return new DefaultCacheManager(localCacheDir, hazelcastInstance, logger); // } // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/CacheTypes.java // public enum CacheTypes { // // /** // * cache entries on filesystem // */ // FILE_CACHE, // // /** // * cache values on local memory cache // */ // LOCAL_MEMORY_CACHE, // // /** // * cache values in distributed hazelcast cache // */ // HAZELCAST_CACHE // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/ICache.java // public interface ICache { // // public void put (String key, JsonObject data); // // default void putArray (String key, JsonArray array) { // if (array == null) { // throw new NullPointerException("array cannot be null."); // } // // JsonObject obj = new JsonObject(); // obj.put("array", array); // // put(key, obj); // } // // public void remove (String key); // // public void removeAll (); // // public boolean contains (String key); // // public JsonObject get (String key); // // default JsonArray getArray (String key) { // JsonObject obj = get(key); // // if (obj == null) { // return null; // } // // if (!obj.containsKey("array")) { // throw new IllegalStateException("cached object isnt an array."); // } // // return obj.getJsonArray("array"); // } // // public void cleanUp (); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/logging/ILogging.java // public interface ILogging { // // public void debug (long messageID, String tag, String message); // // public void debug (String tag, String message); // // public void info (long messageID, String tag, String message); // // public void info (String tag, String message); // // public void warn (long messageID, String tag, String message); // // public void warn (String tag, String message); // // public void error (long messageID, String tag, String message); // // public void error (String tag, String message); // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/DefaultCacheManager.java import com.hazelcast.core.HazelcastInstance; import com.jukusoft.erp.lib.cache.CacheManager; import com.jukusoft.erp.lib.cache.CacheTypes; import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.logging.ILogging; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; package com.jukusoft.erp.lib.cache.impl; public class DefaultCacheManager implements CacheManager { //local cache directory protected File localCacheDir = null; //instance of hazelcast protected HazelcastInstance hazelcastInstance = null; //instance of logger protected ILogging logger = null; //map with all cache instances protected Map<String,ICache> cacheMap = new ConcurrentHashMap<>(); public DefaultCacheManager (File localCacheDir, HazelcastInstance hazelcastInstance, ILogging logger) { this.localCacheDir = localCacheDir; this.hazelcastInstance = hazelcastInstance; this.logger = logger; } @Override public ICache getCache(String cacheName) { return this.cacheMap.get(cacheName); } @Override
public ICache getOrCreateCache(String cacheName, CacheTypes cacheType) {
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/session/impl/HzMapSessionManager.java
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/session/ChangeableSessionManager.java // public interface ChangeableSessionManager extends SessionManager { // // public void putSession (String ssid, Session session); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/session/Session.java // public class Session implements JsonSerializable, JsonLoadable { // // //unique id of session // protected final String sessionID; // // //session attributes // protected Map<String,Object> attributes = new HashMap<>(); // // //created unix timestamp // protected long created = 0; // // private ChangeableSessionManager sessionManager = null; // // //flag, if user is logged in // protected boolean isLoggedIn = false; // // //userID of -1, if user isnt logged in // protected long userID = -1; // // //username // protected String username = "Guest"; // // /** // * default constructor // * // * @param sessionID unique session id // */ // public Session (String sessionID) { // this.sessionID = sessionID; // // this.created = System.currentTimeMillis(); // } // // /** // * get unique ID of session // * // * @return unique session id // */ // public String getSessionID () { // return this.sessionID; // } // // /** // * set a session attribute // * // * @param key key // * @param value value // */ // public <T> void putAttribute (String key, T value) { // this.attributes.put(key, value); // } // // /** // * remove attribute by key // * // * @param key key of attribute // */ // public void removeAttribute (String key) { // this.attributes.remove(key); // } // // /** // * get attribute // */ // public <T> T getAttribute (String key, Class<T> expectedClass) { // if (!this.attributes.containsKey(key)) { // return null; // } // // return expectedClass.cast(this.attributes.get(key)); // } // // public boolean containsAttribute (String key) { // return this.attributes.containsKey(key); // } // // /** // * writes session attributes to cache // */ // public void flush () { // this.sessionManager.putSession(this.sessionID, this); // } // // public boolean isLoggedIn () { // return this.isLoggedIn; // } // // public long getUserID () { // return this.userID; // } // // protected void setUserID (long userID) { // this.userID = userID; // } // // public void login (long userID, String username) { // this.isLoggedIn = true; // this.username = username; // this.setUserID(userID); // } // // public void logout () { // this.isLoggedIn = false; // this.setUserID(-1); // } // // public String getUsername () { // return this.username; // } // // @Override // public JsonObject toJSON() { // //create new json object // JsonObject json = new JsonObject(); // // //add session ID // json.put("session-id", this.sessionID); // // //add created timestamp // json.put("created", this.created); // // //add user information // json.put("is-logged-in", this.isLoggedIn); // json.put("user-id", this.userID); // json.put("username", this.username); // // //add meta information // JsonArray jsonArray = new JsonArray(); // // for (Map.Entry<String,Object> entry : attributes.entrySet()) { // JsonObject json1 = new JsonObject(); // json1.put("key", entry.getKey()); // json1.put("value", entry.getValue()); // // jsonArray.add(json1); // } // // json.put("meta", jsonArray); // // return json; // } // // @Override // public void loadFromJSON(JsonObject json) { // //this.sessionID = json.getString("session-id"); // // this.created = json.getLong("created"); // // JsonArray jsonArray = json.getJsonArray("meta"); // // //get user information // this.isLoggedIn = json.getBoolean("is-logged-in"); // this.userID = json.getLong("user-id"); // this.username = json.getString("username"); // // for (int i = 0; i < jsonArray.size(); i++) { // JsonObject json1 = jsonArray.getJsonObject(i); // // String key = json1.getString("key"); // String value = json1.getString("value"); // } // } // // public static Session createFromJSON (JsonObject json, ChangeableSessionManager sessionManager) { // //create new session with session id // Session session = new Session(json.getString("session-id")); // // //load meta information // session.loadFromJSON(json); // // session.sessionManager = sessionManager; // // return session; // } // // }
import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.jukusoft.erp.lib.session.ChangeableSessionManager; import com.jukusoft.erp.lib.session.Session; import io.vertx.core.json.JsonObject;
package com.jukusoft.erp.lib.session.impl; public class HzMapSessionManager implements ChangeableSessionManager { //map with all sessions protected IMap<String,String> sessionMap = null; /** * default constructor * * @param hazelcastInstance instance of hazelcast */ public HzMapSessionManager (HazelcastInstance hazelcastInstance) { //get map this.sessionMap = hazelcastInstance.getMap("session-cache"); } @Override
// Path: erp-library/src/main/java/com.jukusoft/erp/lib/session/ChangeableSessionManager.java // public interface ChangeableSessionManager extends SessionManager { // // public void putSession (String ssid, Session session); // // } // // Path: erp-library/src/main/java/com.jukusoft/erp/lib/session/Session.java // public class Session implements JsonSerializable, JsonLoadable { // // //unique id of session // protected final String sessionID; // // //session attributes // protected Map<String,Object> attributes = new HashMap<>(); // // //created unix timestamp // protected long created = 0; // // private ChangeableSessionManager sessionManager = null; // // //flag, if user is logged in // protected boolean isLoggedIn = false; // // //userID of -1, if user isnt logged in // protected long userID = -1; // // //username // protected String username = "Guest"; // // /** // * default constructor // * // * @param sessionID unique session id // */ // public Session (String sessionID) { // this.sessionID = sessionID; // // this.created = System.currentTimeMillis(); // } // // /** // * get unique ID of session // * // * @return unique session id // */ // public String getSessionID () { // return this.sessionID; // } // // /** // * set a session attribute // * // * @param key key // * @param value value // */ // public <T> void putAttribute (String key, T value) { // this.attributes.put(key, value); // } // // /** // * remove attribute by key // * // * @param key key of attribute // */ // public void removeAttribute (String key) { // this.attributes.remove(key); // } // // /** // * get attribute // */ // public <T> T getAttribute (String key, Class<T> expectedClass) { // if (!this.attributes.containsKey(key)) { // return null; // } // // return expectedClass.cast(this.attributes.get(key)); // } // // public boolean containsAttribute (String key) { // return this.attributes.containsKey(key); // } // // /** // * writes session attributes to cache // */ // public void flush () { // this.sessionManager.putSession(this.sessionID, this); // } // // public boolean isLoggedIn () { // return this.isLoggedIn; // } // // public long getUserID () { // return this.userID; // } // // protected void setUserID (long userID) { // this.userID = userID; // } // // public void login (long userID, String username) { // this.isLoggedIn = true; // this.username = username; // this.setUserID(userID); // } // // public void logout () { // this.isLoggedIn = false; // this.setUserID(-1); // } // // public String getUsername () { // return this.username; // } // // @Override // public JsonObject toJSON() { // //create new json object // JsonObject json = new JsonObject(); // // //add session ID // json.put("session-id", this.sessionID); // // //add created timestamp // json.put("created", this.created); // // //add user information // json.put("is-logged-in", this.isLoggedIn); // json.put("user-id", this.userID); // json.put("username", this.username); // // //add meta information // JsonArray jsonArray = new JsonArray(); // // for (Map.Entry<String,Object> entry : attributes.entrySet()) { // JsonObject json1 = new JsonObject(); // json1.put("key", entry.getKey()); // json1.put("value", entry.getValue()); // // jsonArray.add(json1); // } // // json.put("meta", jsonArray); // // return json; // } // // @Override // public void loadFromJSON(JsonObject json) { // //this.sessionID = json.getString("session-id"); // // this.created = json.getLong("created"); // // JsonArray jsonArray = json.getJsonArray("meta"); // // //get user information // this.isLoggedIn = json.getBoolean("is-logged-in"); // this.userID = json.getLong("user-id"); // this.username = json.getString("username"); // // for (int i = 0; i < jsonArray.size(); i++) { // JsonObject json1 = jsonArray.getJsonObject(i); // // String key = json1.getString("key"); // String value = json1.getString("value"); // } // } // // public static Session createFromJSON (JsonObject json, ChangeableSessionManager sessionManager) { // //create new session with session id // Session session = new Session(json.getString("session-id")); // // //load meta information // session.loadFromJSON(json); // // session.sessionManager = sessionManager; // // return session; // } // // } // Path: erp-library/src/main/java/com.jukusoft/erp/lib/session/impl/HzMapSessionManager.java import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.jukusoft.erp.lib.session.ChangeableSessionManager; import com.jukusoft.erp.lib.session.Session; import io.vertx.core.json.JsonObject; package com.jukusoft.erp.lib.session.impl; public class HzMapSessionManager implements ChangeableSessionManager { //map with all sessions protected IMap<String,String> sessionMap = null; /** * default constructor * * @param hazelcastInstance instance of hazelcast */ public HzMapSessionManager (HazelcastInstance hazelcastInstance) { //get map this.sessionMap = hazelcastInstance.getMap("session-cache"); } @Override
public Session getSession(String ssid) {
jinkg/UAFClient
fidoclient/src/main/java/com/yalin/fidoclient/asm/msg/ASMRequest.java
// Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/Version.java // public class Version { // public int major; // public int minor; // // public Version(int major, int minor) { // this.major = major; // this.minor = minor; // } // // public static Version getCurrentSupport() { // return new Version(1, 0); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Version) { // if (((Version) o).major == this.major && ((Version) o).minor == this.minor) { // return true; // } // } // return false; // } // }
import com.google.gson.Gson; import com.yalin.fidoclient.msg.Version; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type;
/* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.asm.msg; /** * Created by YaLin on 2016/1/13. */ public class ASMRequest<T> { public static final String authenticatorIndexName = "authenticatorIndex"; public Request requestType;
// Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/Version.java // public class Version { // public int major; // public int minor; // // public Version(int major, int minor) { // this.major = major; // this.minor = minor; // } // // public static Version getCurrentSupport() { // return new Version(1, 0); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Version) { // if (((Version) o).major == this.major && ((Version) o).minor == this.minor) { // return true; // } // } // return false; // } // } // Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/msg/ASMRequest.java import com.google.gson.Gson; import com.yalin.fidoclient.msg.Version; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.asm.msg; /** * Created by YaLin on 2016/1/13. */ public class ASMRequest<T> { public static final String authenticatorIndexName = "authenticatorIndex"; public Request requestType;
public Version asmVersion;
jinkg/UAFClient
fidoclient/src/main/java/com/yalin/fidoclient/ui/AuthenticatorAdapter.java
// Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/msg/obj/AuthenticatorInfo.java // public class AuthenticatorInfo { // public int authenticatorIndex; // public Version[] asmVersions; // public boolean isUserEnrolled; // public boolean hasSettings; // public String aaid; // public String assertionScheme; // public int authenticationAlgorithm; // public int[] attestationTypes; // public long userVerification; // public int keyProtection; // public int matcherProtection; // public long attachmentHint; // public boolean isSecondFactorOnly; // public boolean isRoamingAuthenticator; // public String[] supportedExtensionIDs; // public int tcDisplay; // // public String tcDisplayContentType; // public DisplayPNGCharacteristicsDescriptor[] tcDisplayPNGCharacteristics; // public String title; // public String description; // public String icon; // // public AuthenticatorInfo authenticatorIndex(int authenticatorIndex) { // this.authenticatorIndex = authenticatorIndex; // return this; // } // // public AuthenticatorInfo asmVersions(Version[] asmVersions) { // this.asmVersions = asmVersions; // return this; // } // // public AuthenticatorInfo isUserEnrolled(boolean isUserEnrolled) { // this.isUserEnrolled = isUserEnrolled; // return this; // } // // public AuthenticatorInfo hasSettings(boolean hasSettings) { // this.hasSettings = hasSettings; // return this; // } // // public AuthenticatorInfo aaid(String aaid) { // this.aaid = aaid; // return this; // } // // public AuthenticatorInfo assertionScheme(String assertionScheme) { // this.assertionScheme = assertionScheme; // return this; // } // // public AuthenticatorInfo authenticationAlgorithm(int authenticationAlgorithm) { // this.authenticationAlgorithm = authenticationAlgorithm; // return this; // } // // public AuthenticatorInfo attestationTypes(int[] attestationTypes) { // this.attestationTypes = attestationTypes; // return this; // } // // public AuthenticatorInfo userVerification(int userVerification) { // this.userVerification = userVerification; // return this; // } // // public AuthenticatorInfo keyProtection(int keyProtection) { // this.keyProtection = keyProtection; // return this; // } // // public AuthenticatorInfo matcherProtection(int matcherProtection) { // this.matcherProtection = matcherProtection; // return this; // } // // public AuthenticatorInfo attachmentHint(long attachmentHint) { // this.attachmentHint = attachmentHint; // return this; // } // // public AuthenticatorInfo isSecondFactorOnly(boolean isSecondFactorOnly) { // this.isSecondFactorOnly = isSecondFactorOnly; // return this; // } // // public AuthenticatorInfo isRoamingAuthenticator(boolean isRoamingAuthenticator) { // this.isRoamingAuthenticator = isRoamingAuthenticator; // return this; // } // // public AuthenticatorInfo supportedExtensionIDs(String[] supportedExtensionIDs) { // this.supportedExtensionIDs = supportedExtensionIDs; // return this; // } // // public AuthenticatorInfo tcDisplay(int tcDisplay) { // this.tcDisplay = tcDisplay; // return this; // } // // // }
import java.util.List; import android.content.Context; import android.content.res.Resources; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.yalin.fidoclient.R; import com.yalin.fidoclient.asm.msg.obj.AuthenticatorInfo;
/* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.ui; /** * Created by YaLin on 2016/1/19. */ public class AuthenticatorAdapter extends RecyclerView.Adapter<AuthenticatorItemViewHolder> { public interface OnAuthenticatorClickCallback {
// Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/msg/obj/AuthenticatorInfo.java // public class AuthenticatorInfo { // public int authenticatorIndex; // public Version[] asmVersions; // public boolean isUserEnrolled; // public boolean hasSettings; // public String aaid; // public String assertionScheme; // public int authenticationAlgorithm; // public int[] attestationTypes; // public long userVerification; // public int keyProtection; // public int matcherProtection; // public long attachmentHint; // public boolean isSecondFactorOnly; // public boolean isRoamingAuthenticator; // public String[] supportedExtensionIDs; // public int tcDisplay; // // public String tcDisplayContentType; // public DisplayPNGCharacteristicsDescriptor[] tcDisplayPNGCharacteristics; // public String title; // public String description; // public String icon; // // public AuthenticatorInfo authenticatorIndex(int authenticatorIndex) { // this.authenticatorIndex = authenticatorIndex; // return this; // } // // public AuthenticatorInfo asmVersions(Version[] asmVersions) { // this.asmVersions = asmVersions; // return this; // } // // public AuthenticatorInfo isUserEnrolled(boolean isUserEnrolled) { // this.isUserEnrolled = isUserEnrolled; // return this; // } // // public AuthenticatorInfo hasSettings(boolean hasSettings) { // this.hasSettings = hasSettings; // return this; // } // // public AuthenticatorInfo aaid(String aaid) { // this.aaid = aaid; // return this; // } // // public AuthenticatorInfo assertionScheme(String assertionScheme) { // this.assertionScheme = assertionScheme; // return this; // } // // public AuthenticatorInfo authenticationAlgorithm(int authenticationAlgorithm) { // this.authenticationAlgorithm = authenticationAlgorithm; // return this; // } // // public AuthenticatorInfo attestationTypes(int[] attestationTypes) { // this.attestationTypes = attestationTypes; // return this; // } // // public AuthenticatorInfo userVerification(int userVerification) { // this.userVerification = userVerification; // return this; // } // // public AuthenticatorInfo keyProtection(int keyProtection) { // this.keyProtection = keyProtection; // return this; // } // // public AuthenticatorInfo matcherProtection(int matcherProtection) { // this.matcherProtection = matcherProtection; // return this; // } // // public AuthenticatorInfo attachmentHint(long attachmentHint) { // this.attachmentHint = attachmentHint; // return this; // } // // public AuthenticatorInfo isSecondFactorOnly(boolean isSecondFactorOnly) { // this.isSecondFactorOnly = isSecondFactorOnly; // return this; // } // // public AuthenticatorInfo isRoamingAuthenticator(boolean isRoamingAuthenticator) { // this.isRoamingAuthenticator = isRoamingAuthenticator; // return this; // } // // public AuthenticatorInfo supportedExtensionIDs(String[] supportedExtensionIDs) { // this.supportedExtensionIDs = supportedExtensionIDs; // return this; // } // // public AuthenticatorInfo tcDisplay(int tcDisplay) { // this.tcDisplay = tcDisplay; // return this; // } // // // } // Path: fidoclient/src/main/java/com/yalin/fidoclient/ui/AuthenticatorAdapter.java import java.util.List; import android.content.Context; import android.content.res.Resources; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.yalin.fidoclient.R; import com.yalin.fidoclient.asm.msg.obj.AuthenticatorInfo; /* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.ui; /** * Created by YaLin on 2016/1/19. */ public class AuthenticatorAdapter extends RecyclerView.Adapter<AuthenticatorItemViewHolder> { public interface OnAuthenticatorClickCallback {
void onAuthenticatorClick(AuthenticatorInfo info);
jinkg/UAFClient
fidoclient/src/main/java/com/yalin/fidoclient/asm/msg/obj/AuthenticateIn.java
// Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/Transaction.java // public class Transaction { // public String contentType; // public String content; // public DisplayPNGCharacteristicsDescriptor tcDisplayPNGCharacteristics; // }
import com.yalin.fidoclient.msg.Transaction;
/* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.asm.msg.obj; /** * Created by YaLin on 2016/1/13. */ public class AuthenticateIn { public String appID; public String[] keyIDs; public String finalChallenge;
// Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/Transaction.java // public class Transaction { // public String contentType; // public String content; // public DisplayPNGCharacteristicsDescriptor tcDisplayPNGCharacteristics; // } // Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/msg/obj/AuthenticateIn.java import com.yalin.fidoclient.msg.Transaction; /* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.asm.msg.obj; /** * Created by YaLin on 2016/1/13. */ public class AuthenticateIn { public String appID; public String[] keyIDs; public String finalChallenge;
public Transaction[] transaction;
jinkg/UAFClient
fidoclient/src/main/java/com/yalin/fidoclient/ui/fragment/AsmListAdapter.java
// Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/AsmInfo.java // public class AsmInfo { // public String appName; // public String pack; // public Drawable icon; // // public AsmInfo appName(String appName) { // this.appName = appName; // return this; // } // // public AsmInfo pack(String pack) { // this.pack = pack; // return this; // } // // public AsmInfo icon(Drawable icon) { // this.icon = icon; // return this; // } // }
import android.content.Context; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.yalin.fidoclient.R; import com.yalin.fidoclient.msg.AsmInfo; import java.util.List;
/* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.ui.fragment; /** * Created by YaLin on 2016/2/26. */ public class AsmListAdapter extends RecyclerView.Adapter<AsmListViewHolder> { public interface ASMClickListener {
// Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/AsmInfo.java // public class AsmInfo { // public String appName; // public String pack; // public Drawable icon; // // public AsmInfo appName(String appName) { // this.appName = appName; // return this; // } // // public AsmInfo pack(String pack) { // this.pack = pack; // return this; // } // // public AsmInfo icon(Drawable icon) { // this.icon = icon; // return this; // } // } // Path: fidoclient/src/main/java/com/yalin/fidoclient/ui/fragment/AsmListAdapter.java import android.content.Context; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.yalin.fidoclient.R; import com.yalin.fidoclient.msg.AsmInfo; import java.util.List; /* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.ui.fragment; /** * Created by YaLin on 2016/2/26. */ public class AsmListAdapter extends RecyclerView.Adapter<AsmListViewHolder> { public interface ASMClickListener {
void onAsmItemClicked(AsmInfo info);
jinkg/UAFClient
fidoclient/src/main/java/com/yalin/fidoclient/api/UAFIntent.java
// Path: fidoclient/src/main/java/com/yalin/fidoclient/constants/Constants.java // public interface Constants { // String ACTION_FIDO_OPERATION = "org.fidoalliance.intent.FIDO_OPERATION"; // // String PERMISSION_FIDO_CLIENT = "org.fidoalliance.uaf.permissions.FIDO_CLIENT"; // // String FIDO_CLIENT_INTENT_MIME = "application/fido.uaf_client+json"; // String FIDO_ASM_INTENT_MIME = "application/fido.uaf_asm+json"; // // int CHALLENGE_MAX_LEN = 64; // int CHALLENGE_MIN_LEN = 8; // // int USERNAME_MAX_LEN = 128; // // int APP_ID_MAX_LEN = 512; // // int SERVER_DATA_MAX_LEN = 1536; // // int KEY_ID_MAX_LEN = 2048; // int KEY_ID_MIN_LEN = 32; // // String APP_ID_PREFIX = "https://"; // // String BASE64_REGULAR = "^[a-zA-Z0-9-_]+={0,2}$"; // } // // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/client/UAFIntentType.java // public enum UAFIntentType { // DISCOVER, // DISCOVER_RESULT, // // //Perform a no-op check if a message could be processed. // CHECK_POLICY, // // //Check Policy results. // CHECK_POLICY_RESULT, // // //Process a Registration, Authentication, Transaction Confirmation or Deregistration message. // UAF_OPERATION, // // //UAF Operation results. // UAF_OPERATION_RESULT, // // //Inform the FIDO UAF Client of the completion status of a Registration, Authentication, // // Transaction Confirmation or Deregistration message. // UAF_OPERATION_COMPLETION_STATUS // // // }
import android.content.Intent; import android.os.Bundle; import com.yalin.fidoclient.constants.Constants; import com.yalin.fidoclient.msg.client.UAFIntentType;
/* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.api; /** * Created by YaLin on 2016/1/13. */ public class UAFIntent { public static final String UAF_INTENT_TYPE_KEY = "UAFIntentType"; public static final String DISCOVERY_DATA_KEY = "discoveryData"; public static final String COMPONENT_NAME_KEY = "componentName"; public static final String ERROR_CODE_KEY = "errorCode"; public static final String MESSAGE_KEY = "message"; public static final String ORIGIN_KEY = "origin"; public static final String CHANNEL_BINDINGS_KEY = "channelBindings"; public static final String RESPONSE_CODE_KEY = "responseCode"; /** * This Android intent invokes the FIDO UAF Client to discover the available authenticators and capabilties. * The FIDO UAF Client generally will not show a UI associated with the handling of this intent, * but immediately return the JSON structure. The calling application cannot depend on this however, * as the FIDO UAF Client may show a UI for privacy purposes, * allowing the user to choose whether and which authenticators to disclose to the calling application. * <p/> * This intent must be invoked with startActivityForResult(). * * @return */ public static Intent getDiscoverIntent() {
// Path: fidoclient/src/main/java/com/yalin/fidoclient/constants/Constants.java // public interface Constants { // String ACTION_FIDO_OPERATION = "org.fidoalliance.intent.FIDO_OPERATION"; // // String PERMISSION_FIDO_CLIENT = "org.fidoalliance.uaf.permissions.FIDO_CLIENT"; // // String FIDO_CLIENT_INTENT_MIME = "application/fido.uaf_client+json"; // String FIDO_ASM_INTENT_MIME = "application/fido.uaf_asm+json"; // // int CHALLENGE_MAX_LEN = 64; // int CHALLENGE_MIN_LEN = 8; // // int USERNAME_MAX_LEN = 128; // // int APP_ID_MAX_LEN = 512; // // int SERVER_DATA_MAX_LEN = 1536; // // int KEY_ID_MAX_LEN = 2048; // int KEY_ID_MIN_LEN = 32; // // String APP_ID_PREFIX = "https://"; // // String BASE64_REGULAR = "^[a-zA-Z0-9-_]+={0,2}$"; // } // // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/client/UAFIntentType.java // public enum UAFIntentType { // DISCOVER, // DISCOVER_RESULT, // // //Perform a no-op check if a message could be processed. // CHECK_POLICY, // // //Check Policy results. // CHECK_POLICY_RESULT, // // //Process a Registration, Authentication, Transaction Confirmation or Deregistration message. // UAF_OPERATION, // // //UAF Operation results. // UAF_OPERATION_RESULT, // // //Inform the FIDO UAF Client of the completion status of a Registration, Authentication, // // Transaction Confirmation or Deregistration message. // UAF_OPERATION_COMPLETION_STATUS // // // } // Path: fidoclient/src/main/java/com/yalin/fidoclient/api/UAFIntent.java import android.content.Intent; import android.os.Bundle; import com.yalin.fidoclient.constants.Constants; import com.yalin.fidoclient.msg.client.UAFIntentType; /* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.api; /** * Created by YaLin on 2016/1/13. */ public class UAFIntent { public static final String UAF_INTENT_TYPE_KEY = "UAFIntentType"; public static final String DISCOVERY_DATA_KEY = "discoveryData"; public static final String COMPONENT_NAME_KEY = "componentName"; public static final String ERROR_CODE_KEY = "errorCode"; public static final String MESSAGE_KEY = "message"; public static final String ORIGIN_KEY = "origin"; public static final String CHANNEL_BINDINGS_KEY = "channelBindings"; public static final String RESPONSE_CODE_KEY = "responseCode"; /** * This Android intent invokes the FIDO UAF Client to discover the available authenticators and capabilties. * The FIDO UAF Client generally will not show a UI associated with the handling of this intent, * but immediately return the JSON structure. The calling application cannot depend on this however, * as the FIDO UAF Client may show a UI for privacy purposes, * allowing the user to choose whether and which authenticators to disclose to the calling application. * <p/> * This intent must be invoked with startActivityForResult(). * * @return */ public static Intent getDiscoverIntent() {
Intent intent = new Intent(Constants.ACTION_FIDO_OPERATION);
jinkg/UAFClient
fidoclient/src/main/java/com/yalin/fidoclient/msg/MatchCriteria.java
// Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/msg/obj/AuthenticatorInfo.java // public class AuthenticatorInfo { // public int authenticatorIndex; // public Version[] asmVersions; // public boolean isUserEnrolled; // public boolean hasSettings; // public String aaid; // public String assertionScheme; // public int authenticationAlgorithm; // public int[] attestationTypes; // public long userVerification; // public int keyProtection; // public int matcherProtection; // public long attachmentHint; // public boolean isSecondFactorOnly; // public boolean isRoamingAuthenticator; // public String[] supportedExtensionIDs; // public int tcDisplay; // // public String tcDisplayContentType; // public DisplayPNGCharacteristicsDescriptor[] tcDisplayPNGCharacteristics; // public String title; // public String description; // public String icon; // // public AuthenticatorInfo authenticatorIndex(int authenticatorIndex) { // this.authenticatorIndex = authenticatorIndex; // return this; // } // // public AuthenticatorInfo asmVersions(Version[] asmVersions) { // this.asmVersions = asmVersions; // return this; // } // // public AuthenticatorInfo isUserEnrolled(boolean isUserEnrolled) { // this.isUserEnrolled = isUserEnrolled; // return this; // } // // public AuthenticatorInfo hasSettings(boolean hasSettings) { // this.hasSettings = hasSettings; // return this; // } // // public AuthenticatorInfo aaid(String aaid) { // this.aaid = aaid; // return this; // } // // public AuthenticatorInfo assertionScheme(String assertionScheme) { // this.assertionScheme = assertionScheme; // return this; // } // // public AuthenticatorInfo authenticationAlgorithm(int authenticationAlgorithm) { // this.authenticationAlgorithm = authenticationAlgorithm; // return this; // } // // public AuthenticatorInfo attestationTypes(int[] attestationTypes) { // this.attestationTypes = attestationTypes; // return this; // } // // public AuthenticatorInfo userVerification(int userVerification) { // this.userVerification = userVerification; // return this; // } // // public AuthenticatorInfo keyProtection(int keyProtection) { // this.keyProtection = keyProtection; // return this; // } // // public AuthenticatorInfo matcherProtection(int matcherProtection) { // this.matcherProtection = matcherProtection; // return this; // } // // public AuthenticatorInfo attachmentHint(long attachmentHint) { // this.attachmentHint = attachmentHint; // return this; // } // // public AuthenticatorInfo isSecondFactorOnly(boolean isSecondFactorOnly) { // this.isSecondFactorOnly = isSecondFactorOnly; // return this; // } // // public AuthenticatorInfo isRoamingAuthenticator(boolean isRoamingAuthenticator) { // this.isRoamingAuthenticator = isRoamingAuthenticator; // return this; // } // // public AuthenticatorInfo supportedExtensionIDs(String[] supportedExtensionIDs) { // this.supportedExtensionIDs = supportedExtensionIDs; // return this; // } // // public AuthenticatorInfo tcDisplay(int tcDisplay) { // this.tcDisplay = tcDisplay; // return this; // } // // // }
import com.yalin.fidoclient.asm.msg.obj.AuthenticatorInfo; import java.util.Arrays;
/* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.msg; /** * Created by YaLin on 2016/1/21. */ public class MatchCriteria { public String[] aaid; //public String[] vendorID; public String[] keyIDs; // public long userVerification; // public int keyProtection; //public int matcherProtection; public long attachmentHint; //public int tcDisplay; //public int[] authenticationAlgorithms; public String[] assertionSchemes; //public int[] attestationTypes; public int authenticatorVersion; public Extension[] exts;
// Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/msg/obj/AuthenticatorInfo.java // public class AuthenticatorInfo { // public int authenticatorIndex; // public Version[] asmVersions; // public boolean isUserEnrolled; // public boolean hasSettings; // public String aaid; // public String assertionScheme; // public int authenticationAlgorithm; // public int[] attestationTypes; // public long userVerification; // public int keyProtection; // public int matcherProtection; // public long attachmentHint; // public boolean isSecondFactorOnly; // public boolean isRoamingAuthenticator; // public String[] supportedExtensionIDs; // public int tcDisplay; // // public String tcDisplayContentType; // public DisplayPNGCharacteristicsDescriptor[] tcDisplayPNGCharacteristics; // public String title; // public String description; // public String icon; // // public AuthenticatorInfo authenticatorIndex(int authenticatorIndex) { // this.authenticatorIndex = authenticatorIndex; // return this; // } // // public AuthenticatorInfo asmVersions(Version[] asmVersions) { // this.asmVersions = asmVersions; // return this; // } // // public AuthenticatorInfo isUserEnrolled(boolean isUserEnrolled) { // this.isUserEnrolled = isUserEnrolled; // return this; // } // // public AuthenticatorInfo hasSettings(boolean hasSettings) { // this.hasSettings = hasSettings; // return this; // } // // public AuthenticatorInfo aaid(String aaid) { // this.aaid = aaid; // return this; // } // // public AuthenticatorInfo assertionScheme(String assertionScheme) { // this.assertionScheme = assertionScheme; // return this; // } // // public AuthenticatorInfo authenticationAlgorithm(int authenticationAlgorithm) { // this.authenticationAlgorithm = authenticationAlgorithm; // return this; // } // // public AuthenticatorInfo attestationTypes(int[] attestationTypes) { // this.attestationTypes = attestationTypes; // return this; // } // // public AuthenticatorInfo userVerification(int userVerification) { // this.userVerification = userVerification; // return this; // } // // public AuthenticatorInfo keyProtection(int keyProtection) { // this.keyProtection = keyProtection; // return this; // } // // public AuthenticatorInfo matcherProtection(int matcherProtection) { // this.matcherProtection = matcherProtection; // return this; // } // // public AuthenticatorInfo attachmentHint(long attachmentHint) { // this.attachmentHint = attachmentHint; // return this; // } // // public AuthenticatorInfo isSecondFactorOnly(boolean isSecondFactorOnly) { // this.isSecondFactorOnly = isSecondFactorOnly; // return this; // } // // public AuthenticatorInfo isRoamingAuthenticator(boolean isRoamingAuthenticator) { // this.isRoamingAuthenticator = isRoamingAuthenticator; // return this; // } // // public AuthenticatorInfo supportedExtensionIDs(String[] supportedExtensionIDs) { // this.supportedExtensionIDs = supportedExtensionIDs; // return this; // } // // public AuthenticatorInfo tcDisplay(int tcDisplay) { // this.tcDisplay = tcDisplay; // return this; // } // // // } // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/MatchCriteria.java import com.yalin.fidoclient.asm.msg.obj.AuthenticatorInfo; import java.util.Arrays; /* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.msg; /** * Created by YaLin on 2016/1/21. */ public class MatchCriteria { public String[] aaid; //public String[] vendorID; public String[] keyIDs; // public long userVerification; // public int keyProtection; //public int matcherProtection; public long attachmentHint; //public int tcDisplay; //public int[] authenticationAlgorithms; public String[] assertionSchemes; //public int[] attestationTypes; public int authenticatorVersion; public Extension[] exts;
public boolean isMatch(AuthenticatorInfo info) {
jinkg/UAFClient
fidoclient/src/main/java/com/yalin/fidoclient/asm/api/ASMIntent.java
// Path: fidoclient/src/main/java/com/yalin/fidoclient/constants/Constants.java // public interface Constants { // String ACTION_FIDO_OPERATION = "org.fidoalliance.intent.FIDO_OPERATION"; // // String PERMISSION_FIDO_CLIENT = "org.fidoalliance.uaf.permissions.FIDO_CLIENT"; // // String FIDO_CLIENT_INTENT_MIME = "application/fido.uaf_client+json"; // String FIDO_ASM_INTENT_MIME = "application/fido.uaf_asm+json"; // // int CHALLENGE_MAX_LEN = 64; // int CHALLENGE_MIN_LEN = 8; // // int USERNAME_MAX_LEN = 128; // // int APP_ID_MAX_LEN = 512; // // int SERVER_DATA_MAX_LEN = 1536; // // int KEY_ID_MAX_LEN = 2048; // int KEY_ID_MIN_LEN = 32; // // String APP_ID_PREFIX = "https://"; // // String BASE64_REGULAR = "^[a-zA-Z0-9-_]+={0,2}$"; // }
import android.content.Intent; import android.os.Bundle; import com.yalin.fidoclient.constants.Constants;
/* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.asm.api; /** * Created by YaLin on 2016/1/13. */ public class ASMIntent { public static final String MESSAGE_KEY = "message"; public static Intent getASMIntent(){
// Path: fidoclient/src/main/java/com/yalin/fidoclient/constants/Constants.java // public interface Constants { // String ACTION_FIDO_OPERATION = "org.fidoalliance.intent.FIDO_OPERATION"; // // String PERMISSION_FIDO_CLIENT = "org.fidoalliance.uaf.permissions.FIDO_CLIENT"; // // String FIDO_CLIENT_INTENT_MIME = "application/fido.uaf_client+json"; // String FIDO_ASM_INTENT_MIME = "application/fido.uaf_asm+json"; // // int CHALLENGE_MAX_LEN = 64; // int CHALLENGE_MIN_LEN = 8; // // int USERNAME_MAX_LEN = 128; // // int APP_ID_MAX_LEN = 512; // // int SERVER_DATA_MAX_LEN = 1536; // // int KEY_ID_MAX_LEN = 2048; // int KEY_ID_MIN_LEN = 32; // // String APP_ID_PREFIX = "https://"; // // String BASE64_REGULAR = "^[a-zA-Z0-9-_]+={0,2}$"; // } // Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/api/ASMIntent.java import android.content.Intent; import android.os.Bundle; import com.yalin.fidoclient.constants.Constants; /* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.asm.api; /** * Created by YaLin on 2016/1/13. */ public class ASMIntent { public static final String MESSAGE_KEY = "message"; public static Intent getASMIntent(){
Intent intent = new Intent(Constants.ACTION_FIDO_OPERATION);
jinkg/UAFClient
fidoclient/src/main/java/com/yalin/fidoclient/asm/msg/obj/AuthenticatorInfo.java
// Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/DisplayPNGCharacteristicsDescriptor.java // public class DisplayPNGCharacteristicsDescriptor { // public long width; // public long height; // public String bitDepth; // public String colorType; // public String compression; // public String filter; // public String interlace; // public rgbPalletteEntry[] plte; // } // // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/Version.java // public class Version { // public int major; // public int minor; // // public Version(int major, int minor) { // this.major = major; // this.minor = minor; // } // // public static Version getCurrentSupport() { // return new Version(1, 0); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Version) { // if (((Version) o).major == this.major && ((Version) o).minor == this.minor) { // return true; // } // } // return false; // } // }
import com.yalin.fidoclient.msg.DisplayPNGCharacteristicsDescriptor; import com.yalin.fidoclient.msg.Version;
/* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.asm.msg.obj; /** * Created by YaLin on 2016/1/13. */ public class AuthenticatorInfo { public int authenticatorIndex;
// Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/DisplayPNGCharacteristicsDescriptor.java // public class DisplayPNGCharacteristicsDescriptor { // public long width; // public long height; // public String bitDepth; // public String colorType; // public String compression; // public String filter; // public String interlace; // public rgbPalletteEntry[] plte; // } // // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/Version.java // public class Version { // public int major; // public int minor; // // public Version(int major, int minor) { // this.major = major; // this.minor = minor; // } // // public static Version getCurrentSupport() { // return new Version(1, 0); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Version) { // if (((Version) o).major == this.major && ((Version) o).minor == this.minor) { // return true; // } // } // return false; // } // } // Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/msg/obj/AuthenticatorInfo.java import com.yalin.fidoclient.msg.DisplayPNGCharacteristicsDescriptor; import com.yalin.fidoclient.msg.Version; /* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.asm.msg.obj; /** * Created by YaLin on 2016/1/13. */ public class AuthenticatorInfo { public int authenticatorIndex;
public Version[] asmVersions;
jinkg/UAFClient
fidoclient/src/main/java/com/yalin/fidoclient/asm/msg/obj/AuthenticatorInfo.java
// Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/DisplayPNGCharacteristicsDescriptor.java // public class DisplayPNGCharacteristicsDescriptor { // public long width; // public long height; // public String bitDepth; // public String colorType; // public String compression; // public String filter; // public String interlace; // public rgbPalletteEntry[] plte; // } // // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/Version.java // public class Version { // public int major; // public int minor; // // public Version(int major, int minor) { // this.major = major; // this.minor = minor; // } // // public static Version getCurrentSupport() { // return new Version(1, 0); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Version) { // if (((Version) o).major == this.major && ((Version) o).minor == this.minor) { // return true; // } // } // return false; // } // }
import com.yalin.fidoclient.msg.DisplayPNGCharacteristicsDescriptor; import com.yalin.fidoclient.msg.Version;
/* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.asm.msg.obj; /** * Created by YaLin on 2016/1/13. */ public class AuthenticatorInfo { public int authenticatorIndex; public Version[] asmVersions; public boolean isUserEnrolled; public boolean hasSettings; public String aaid; public String assertionScheme; public int authenticationAlgorithm; public int[] attestationTypes; public long userVerification; public int keyProtection; public int matcherProtection; public long attachmentHint; public boolean isSecondFactorOnly; public boolean isRoamingAuthenticator; public String[] supportedExtensionIDs; public int tcDisplay; public String tcDisplayContentType;
// Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/DisplayPNGCharacteristicsDescriptor.java // public class DisplayPNGCharacteristicsDescriptor { // public long width; // public long height; // public String bitDepth; // public String colorType; // public String compression; // public String filter; // public String interlace; // public rgbPalletteEntry[] plte; // } // // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/Version.java // public class Version { // public int major; // public int minor; // // public Version(int major, int minor) { // this.major = major; // this.minor = minor; // } // // public static Version getCurrentSupport() { // return new Version(1, 0); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Version) { // if (((Version) o).major == this.major && ((Version) o).minor == this.minor) { // return true; // } // } // return false; // } // } // Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/msg/obj/AuthenticatorInfo.java import com.yalin.fidoclient.msg.DisplayPNGCharacteristicsDescriptor; import com.yalin.fidoclient.msg.Version; /* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.asm.msg.obj; /** * Created by YaLin on 2016/1/13. */ public class AuthenticatorInfo { public int authenticatorIndex; public Version[] asmVersions; public boolean isUserEnrolled; public boolean hasSettings; public String aaid; public String assertionScheme; public int authenticationAlgorithm; public int[] attestationTypes; public long userVerification; public int keyProtection; public int matcherProtection; public long attachmentHint; public boolean isSecondFactorOnly; public boolean isRoamingAuthenticator; public String[] supportedExtensionIDs; public int tcDisplay; public String tcDisplayContentType;
public DisplayPNGCharacteristicsDescriptor[] tcDisplayPNGCharacteristics;
jinkg/UAFClient
fidoclient/src/main/java/com/yalin/fidoclient/msg/Authenticator.java
// Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/msg/obj/AuthenticatorInfo.java // public class AuthenticatorInfo { // public int authenticatorIndex; // public Version[] asmVersions; // public boolean isUserEnrolled; // public boolean hasSettings; // public String aaid; // public String assertionScheme; // public int authenticationAlgorithm; // public int[] attestationTypes; // public long userVerification; // public int keyProtection; // public int matcherProtection; // public long attachmentHint; // public boolean isSecondFactorOnly; // public boolean isRoamingAuthenticator; // public String[] supportedExtensionIDs; // public int tcDisplay; // // public String tcDisplayContentType; // public DisplayPNGCharacteristicsDescriptor[] tcDisplayPNGCharacteristics; // public String title; // public String description; // public String icon; // // public AuthenticatorInfo authenticatorIndex(int authenticatorIndex) { // this.authenticatorIndex = authenticatorIndex; // return this; // } // // public AuthenticatorInfo asmVersions(Version[] asmVersions) { // this.asmVersions = asmVersions; // return this; // } // // public AuthenticatorInfo isUserEnrolled(boolean isUserEnrolled) { // this.isUserEnrolled = isUserEnrolled; // return this; // } // // public AuthenticatorInfo hasSettings(boolean hasSettings) { // this.hasSettings = hasSettings; // return this; // } // // public AuthenticatorInfo aaid(String aaid) { // this.aaid = aaid; // return this; // } // // public AuthenticatorInfo assertionScheme(String assertionScheme) { // this.assertionScheme = assertionScheme; // return this; // } // // public AuthenticatorInfo authenticationAlgorithm(int authenticationAlgorithm) { // this.authenticationAlgorithm = authenticationAlgorithm; // return this; // } // // public AuthenticatorInfo attestationTypes(int[] attestationTypes) { // this.attestationTypes = attestationTypes; // return this; // } // // public AuthenticatorInfo userVerification(int userVerification) { // this.userVerification = userVerification; // return this; // } // // public AuthenticatorInfo keyProtection(int keyProtection) { // this.keyProtection = keyProtection; // return this; // } // // public AuthenticatorInfo matcherProtection(int matcherProtection) { // this.matcherProtection = matcherProtection; // return this; // } // // public AuthenticatorInfo attachmentHint(long attachmentHint) { // this.attachmentHint = attachmentHint; // return this; // } // // public AuthenticatorInfo isSecondFactorOnly(boolean isSecondFactorOnly) { // this.isSecondFactorOnly = isSecondFactorOnly; // return this; // } // // public AuthenticatorInfo isRoamingAuthenticator(boolean isRoamingAuthenticator) { // this.isRoamingAuthenticator = isRoamingAuthenticator; // return this; // } // // public AuthenticatorInfo supportedExtensionIDs(String[] supportedExtensionIDs) { // this.supportedExtensionIDs = supportedExtensionIDs; // return this; // } // // public AuthenticatorInfo tcDisplay(int tcDisplay) { // this.tcDisplay = tcDisplay; // return this; // } // // // }
import com.yalin.fidoclient.asm.msg.obj.AuthenticatorInfo;
/* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.msg; /** * Created by YaLin on 2016/1/21. */ public class Authenticator { public String title; public String aaid; public String description; public Version[] supportedUAFVersions; public String assertionScheme; public int authenticationAlgorithm; public int[] attestationTypes; public long userVerification; public int keyProtection; public int matcherProtection; public long attachmentHint; public boolean isSecondFactorOnly; public int tcDisplay; public String tcDisplayContentType; public DisplayPNGCharacteristicsDescriptor[] tcDisplayPNGCharacteristics; public String icon; public String[] supportedExtensionIDs;
// Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/msg/obj/AuthenticatorInfo.java // public class AuthenticatorInfo { // public int authenticatorIndex; // public Version[] asmVersions; // public boolean isUserEnrolled; // public boolean hasSettings; // public String aaid; // public String assertionScheme; // public int authenticationAlgorithm; // public int[] attestationTypes; // public long userVerification; // public int keyProtection; // public int matcherProtection; // public long attachmentHint; // public boolean isSecondFactorOnly; // public boolean isRoamingAuthenticator; // public String[] supportedExtensionIDs; // public int tcDisplay; // // public String tcDisplayContentType; // public DisplayPNGCharacteristicsDescriptor[] tcDisplayPNGCharacteristics; // public String title; // public String description; // public String icon; // // public AuthenticatorInfo authenticatorIndex(int authenticatorIndex) { // this.authenticatorIndex = authenticatorIndex; // return this; // } // // public AuthenticatorInfo asmVersions(Version[] asmVersions) { // this.asmVersions = asmVersions; // return this; // } // // public AuthenticatorInfo isUserEnrolled(boolean isUserEnrolled) { // this.isUserEnrolled = isUserEnrolled; // return this; // } // // public AuthenticatorInfo hasSettings(boolean hasSettings) { // this.hasSettings = hasSettings; // return this; // } // // public AuthenticatorInfo aaid(String aaid) { // this.aaid = aaid; // return this; // } // // public AuthenticatorInfo assertionScheme(String assertionScheme) { // this.assertionScheme = assertionScheme; // return this; // } // // public AuthenticatorInfo authenticationAlgorithm(int authenticationAlgorithm) { // this.authenticationAlgorithm = authenticationAlgorithm; // return this; // } // // public AuthenticatorInfo attestationTypes(int[] attestationTypes) { // this.attestationTypes = attestationTypes; // return this; // } // // public AuthenticatorInfo userVerification(int userVerification) { // this.userVerification = userVerification; // return this; // } // // public AuthenticatorInfo keyProtection(int keyProtection) { // this.keyProtection = keyProtection; // return this; // } // // public AuthenticatorInfo matcherProtection(int matcherProtection) { // this.matcherProtection = matcherProtection; // return this; // } // // public AuthenticatorInfo attachmentHint(long attachmentHint) { // this.attachmentHint = attachmentHint; // return this; // } // // public AuthenticatorInfo isSecondFactorOnly(boolean isSecondFactorOnly) { // this.isSecondFactorOnly = isSecondFactorOnly; // return this; // } // // public AuthenticatorInfo isRoamingAuthenticator(boolean isRoamingAuthenticator) { // this.isRoamingAuthenticator = isRoamingAuthenticator; // return this; // } // // public AuthenticatorInfo supportedExtensionIDs(String[] supportedExtensionIDs) { // this.supportedExtensionIDs = supportedExtensionIDs; // return this; // } // // public AuthenticatorInfo tcDisplay(int tcDisplay) { // this.tcDisplay = tcDisplay; // return this; // } // // // } // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/Authenticator.java import com.yalin.fidoclient.asm.msg.obj.AuthenticatorInfo; /* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.msg; /** * Created by YaLin on 2016/1/21. */ public class Authenticator { public String title; public String aaid; public String description; public Version[] supportedUAFVersions; public String assertionScheme; public int authenticationAlgorithm; public int[] attestationTypes; public long userVerification; public int keyProtection; public int matcherProtection; public long attachmentHint; public boolean isSecondFactorOnly; public int tcDisplay; public String tcDisplayContentType; public DisplayPNGCharacteristicsDescriptor[] tcDisplayPNGCharacteristics; public String icon; public String[] supportedExtensionIDs;
public static Authenticator[] fromInfo(AuthenticatorInfo[] infos) {
jinkg/UAFClient
fidoclient/src/main/java/com/yalin/fidoclient/ui/MainActivity.java
// Path: fidoclient/src/main/java/com/yalin/fidoclient/api/UAFClientApi.java // public class UAFClientApi { // public static void doDiscover(Activity activity, int requestCode) { // if (activity == null) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getDiscoverIntent(); // activity.startActivityForResult(intent, requestCode); // } // // public static void doCheckPolicy(Activity activity, int requestCode, String responseMessage) { // if (activity == null || TextUtils.isEmpty(responseMessage)) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getCheckPolicyIntent(new UAFMessage(responseMessage).toJson(), activity.getApplication().getPackageName()); // activity.startActivityForResult(intent, requestCode); // } // // public static void doOperation(Activity activity, int requestCode, String responseMessage, String channelBinding) { // if (activity == null || TextUtils.isEmpty(responseMessage)) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getUAFOperationIntent(new UAFMessage(responseMessage).toJson(), null, channelBinding); // activity.startActivityForResult(intent, requestCode); // } // // public static void doOperation(Fragment fragment, int requestCode, String responseMessage, String channelBinding) { // if (fragment == null || TextUtils.isEmpty(responseMessage)) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getUAFOperationIntent(new UAFMessage(responseMessage).toJson(), null, channelBinding); // fragment.startActivityForResult(intent, requestCode); // } // // public static List<RegRecord> getRegRecords(String username) { // if (TextUtils.isEmpty(username)) { // throw new IllegalArgumentException(); // } // return null; // } // // public static DeregistrationRequest[] getDeRegistrationRequests(RegRecord regRecord) { // if (regRecord == null) { // throw new IllegalArgumentException("regRecord must not be null!"); // } // DeregistrationRequest[] deRegistrationRequests = new DeregistrationRequest[1]; // deRegistrationRequests[0] = new DeregistrationRequest(); // deRegistrationRequests[0].authenticators = new DeregisterAuthenticator[1]; // deRegistrationRequests[0].authenticators[0] = new DeregisterAuthenticator(); // deRegistrationRequests[0].authenticators[0].aaid = regRecord.aaid; // deRegistrationRequests[0].authenticators[0].keyID = regRecord.keyId; // // return deRegistrationRequests; // } // // public static AsmInfo getDefaultAsmInfo(Context context) { // return UAFClientActivity.getAsmInfo(context); // } // // public static void clearDefaultAsm(Context context) { // UAFClientActivity.setAsmInfo(context, null); // } // } // // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/AsmInfo.java // public class AsmInfo { // public String appName; // public String pack; // public Drawable icon; // // public AsmInfo appName(String appName) { // this.appName = appName; // return this; // } // // public AsmInfo pack(String pack) { // this.pack = pack; // return this; // } // // public AsmInfo icon(Drawable icon) { // this.icon = icon; // return this; // } // }
import android.content.DialogInterface; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import com.yalin.fidoclient.R; import com.yalin.fidoclient.api.UAFClientApi; import com.yalin.fidoclient.msg.AsmInfo;
/* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.ui; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = MainActivity.class.getSimpleName(); private View rootCoordinator;
// Path: fidoclient/src/main/java/com/yalin/fidoclient/api/UAFClientApi.java // public class UAFClientApi { // public static void doDiscover(Activity activity, int requestCode) { // if (activity == null) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getDiscoverIntent(); // activity.startActivityForResult(intent, requestCode); // } // // public static void doCheckPolicy(Activity activity, int requestCode, String responseMessage) { // if (activity == null || TextUtils.isEmpty(responseMessage)) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getCheckPolicyIntent(new UAFMessage(responseMessage).toJson(), activity.getApplication().getPackageName()); // activity.startActivityForResult(intent, requestCode); // } // // public static void doOperation(Activity activity, int requestCode, String responseMessage, String channelBinding) { // if (activity == null || TextUtils.isEmpty(responseMessage)) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getUAFOperationIntent(new UAFMessage(responseMessage).toJson(), null, channelBinding); // activity.startActivityForResult(intent, requestCode); // } // // public static void doOperation(Fragment fragment, int requestCode, String responseMessage, String channelBinding) { // if (fragment == null || TextUtils.isEmpty(responseMessage)) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getUAFOperationIntent(new UAFMessage(responseMessage).toJson(), null, channelBinding); // fragment.startActivityForResult(intent, requestCode); // } // // public static List<RegRecord> getRegRecords(String username) { // if (TextUtils.isEmpty(username)) { // throw new IllegalArgumentException(); // } // return null; // } // // public static DeregistrationRequest[] getDeRegistrationRequests(RegRecord regRecord) { // if (regRecord == null) { // throw new IllegalArgumentException("regRecord must not be null!"); // } // DeregistrationRequest[] deRegistrationRequests = new DeregistrationRequest[1]; // deRegistrationRequests[0] = new DeregistrationRequest(); // deRegistrationRequests[0].authenticators = new DeregisterAuthenticator[1]; // deRegistrationRequests[0].authenticators[0] = new DeregisterAuthenticator(); // deRegistrationRequests[0].authenticators[0].aaid = regRecord.aaid; // deRegistrationRequests[0].authenticators[0].keyID = regRecord.keyId; // // return deRegistrationRequests; // } // // public static AsmInfo getDefaultAsmInfo(Context context) { // return UAFClientActivity.getAsmInfo(context); // } // // public static void clearDefaultAsm(Context context) { // UAFClientActivity.setAsmInfo(context, null); // } // } // // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/AsmInfo.java // public class AsmInfo { // public String appName; // public String pack; // public Drawable icon; // // public AsmInfo appName(String appName) { // this.appName = appName; // return this; // } // // public AsmInfo pack(String pack) { // this.pack = pack; // return this; // } // // public AsmInfo icon(Drawable icon) { // this.icon = icon; // return this; // } // } // Path: fidoclient/src/main/java/com/yalin/fidoclient/ui/MainActivity.java import android.content.DialogInterface; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import com.yalin.fidoclient.R; import com.yalin.fidoclient.api.UAFClientApi; import com.yalin.fidoclient.msg.AsmInfo; /* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.ui; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = MainActivity.class.getSimpleName(); private View rootCoordinator;
private AsmInfo asmInfo;
jinkg/UAFClient
fidoclient/src/main/java/com/yalin/fidoclient/ui/MainActivity.java
// Path: fidoclient/src/main/java/com/yalin/fidoclient/api/UAFClientApi.java // public class UAFClientApi { // public static void doDiscover(Activity activity, int requestCode) { // if (activity == null) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getDiscoverIntent(); // activity.startActivityForResult(intent, requestCode); // } // // public static void doCheckPolicy(Activity activity, int requestCode, String responseMessage) { // if (activity == null || TextUtils.isEmpty(responseMessage)) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getCheckPolicyIntent(new UAFMessage(responseMessage).toJson(), activity.getApplication().getPackageName()); // activity.startActivityForResult(intent, requestCode); // } // // public static void doOperation(Activity activity, int requestCode, String responseMessage, String channelBinding) { // if (activity == null || TextUtils.isEmpty(responseMessage)) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getUAFOperationIntent(new UAFMessage(responseMessage).toJson(), null, channelBinding); // activity.startActivityForResult(intent, requestCode); // } // // public static void doOperation(Fragment fragment, int requestCode, String responseMessage, String channelBinding) { // if (fragment == null || TextUtils.isEmpty(responseMessage)) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getUAFOperationIntent(new UAFMessage(responseMessage).toJson(), null, channelBinding); // fragment.startActivityForResult(intent, requestCode); // } // // public static List<RegRecord> getRegRecords(String username) { // if (TextUtils.isEmpty(username)) { // throw new IllegalArgumentException(); // } // return null; // } // // public static DeregistrationRequest[] getDeRegistrationRequests(RegRecord regRecord) { // if (regRecord == null) { // throw new IllegalArgumentException("regRecord must not be null!"); // } // DeregistrationRequest[] deRegistrationRequests = new DeregistrationRequest[1]; // deRegistrationRequests[0] = new DeregistrationRequest(); // deRegistrationRequests[0].authenticators = new DeregisterAuthenticator[1]; // deRegistrationRequests[0].authenticators[0] = new DeregisterAuthenticator(); // deRegistrationRequests[0].authenticators[0].aaid = regRecord.aaid; // deRegistrationRequests[0].authenticators[0].keyID = regRecord.keyId; // // return deRegistrationRequests; // } // // public static AsmInfo getDefaultAsmInfo(Context context) { // return UAFClientActivity.getAsmInfo(context); // } // // public static void clearDefaultAsm(Context context) { // UAFClientActivity.setAsmInfo(context, null); // } // } // // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/AsmInfo.java // public class AsmInfo { // public String appName; // public String pack; // public Drawable icon; // // public AsmInfo appName(String appName) { // this.appName = appName; // return this; // } // // public AsmInfo pack(String pack) { // this.pack = pack; // return this; // } // // public AsmInfo icon(Drawable icon) { // this.icon = icon; // return this; // } // }
import android.content.DialogInterface; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import com.yalin.fidoclient.R; import com.yalin.fidoclient.api.UAFClientApi; import com.yalin.fidoclient.msg.AsmInfo;
/* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.ui; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = MainActivity.class.getSimpleName(); private View rootCoordinator; private AsmInfo asmInfo; private Button btnDefaultAsm; private boolean hasDefault = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); } private void initView() { FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); rootCoordinator = findViewById(R.id.root_coordinator); btnDefaultAsm = (Button) findViewById(R.id.setting_btn_asm_name); btnDefaultAsm.setOnClickListener(this); } private void initData() {
// Path: fidoclient/src/main/java/com/yalin/fidoclient/api/UAFClientApi.java // public class UAFClientApi { // public static void doDiscover(Activity activity, int requestCode) { // if (activity == null) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getDiscoverIntent(); // activity.startActivityForResult(intent, requestCode); // } // // public static void doCheckPolicy(Activity activity, int requestCode, String responseMessage) { // if (activity == null || TextUtils.isEmpty(responseMessage)) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getCheckPolicyIntent(new UAFMessage(responseMessage).toJson(), activity.getApplication().getPackageName()); // activity.startActivityForResult(intent, requestCode); // } // // public static void doOperation(Activity activity, int requestCode, String responseMessage, String channelBinding) { // if (activity == null || TextUtils.isEmpty(responseMessage)) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getUAFOperationIntent(new UAFMessage(responseMessage).toJson(), null, channelBinding); // activity.startActivityForResult(intent, requestCode); // } // // public static void doOperation(Fragment fragment, int requestCode, String responseMessage, String channelBinding) { // if (fragment == null || TextUtils.isEmpty(responseMessage)) { // throw new IllegalArgumentException(); // } // Intent intent = UAFIntent.getUAFOperationIntent(new UAFMessage(responseMessage).toJson(), null, channelBinding); // fragment.startActivityForResult(intent, requestCode); // } // // public static List<RegRecord> getRegRecords(String username) { // if (TextUtils.isEmpty(username)) { // throw new IllegalArgumentException(); // } // return null; // } // // public static DeregistrationRequest[] getDeRegistrationRequests(RegRecord regRecord) { // if (regRecord == null) { // throw new IllegalArgumentException("regRecord must not be null!"); // } // DeregistrationRequest[] deRegistrationRequests = new DeregistrationRequest[1]; // deRegistrationRequests[0] = new DeregistrationRequest(); // deRegistrationRequests[0].authenticators = new DeregisterAuthenticator[1]; // deRegistrationRequests[0].authenticators[0] = new DeregisterAuthenticator(); // deRegistrationRequests[0].authenticators[0].aaid = regRecord.aaid; // deRegistrationRequests[0].authenticators[0].keyID = regRecord.keyId; // // return deRegistrationRequests; // } // // public static AsmInfo getDefaultAsmInfo(Context context) { // return UAFClientActivity.getAsmInfo(context); // } // // public static void clearDefaultAsm(Context context) { // UAFClientActivity.setAsmInfo(context, null); // } // } // // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/AsmInfo.java // public class AsmInfo { // public String appName; // public String pack; // public Drawable icon; // // public AsmInfo appName(String appName) { // this.appName = appName; // return this; // } // // public AsmInfo pack(String pack) { // this.pack = pack; // return this; // } // // public AsmInfo icon(Drawable icon) { // this.icon = icon; // return this; // } // } // Path: fidoclient/src/main/java/com/yalin/fidoclient/ui/MainActivity.java import android.content.DialogInterface; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import com.yalin.fidoclient.R; import com.yalin.fidoclient.api.UAFClientApi; import com.yalin.fidoclient.msg.AsmInfo; /* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.ui; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = MainActivity.class.getSimpleName(); private View rootCoordinator; private AsmInfo asmInfo; private Button btnDefaultAsm; private boolean hasDefault = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); } private void initView() { FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); rootCoordinator = findViewById(R.id.root_coordinator); btnDefaultAsm = (Button) findViewById(R.id.setting_btn_asm_name); btnDefaultAsm.setOnClickListener(this); } private void initData() {
asmInfo = UAFClientApi.getDefaultAsmInfo(getApplicationContext());
jinkg/UAFClient
fidoclient/src/main/java/com/yalin/fidoclient/ui/fragment/AsmListFragment.java
// Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/api/ASMIntent.java // public class ASMIntent { // public static final String MESSAGE_KEY = "message"; // // public static Intent getASMIntent(){ // Intent intent = new Intent(Constants.ACTION_FIDO_OPERATION); // intent.setType(Constants.FIDO_ASM_INTENT_MIME); // // return intent; // } // // public static Intent getASMOperationIntent(String asmRequest) { // Intent intent = new Intent(Constants.ACTION_FIDO_OPERATION); // intent.setType(Constants.FIDO_ASM_INTENT_MIME); // // Bundle bundle = new Bundle(); // bundle.putString(MESSAGE_KEY, asmRequest); // intent.putExtras(bundle); // return intent; // } // // public static Intent getASMOperationResultIntent(String asmResponse) { // Intent intent = new Intent(); // // Bundle bundle = new Bundle(); // bundle.putString(MESSAGE_KEY, asmResponse); // intent.putExtras(bundle); // return intent; // } // } // // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/AsmInfo.java // public class AsmInfo { // public String appName; // public String pack; // public Drawable icon; // // public AsmInfo appName(String appName) { // this.appName = appName; // return this; // } // // public AsmInfo pack(String pack) { // this.pack = pack; // return this; // } // // public AsmInfo icon(Drawable icon) { // this.icon = icon; // return this; // } // }
import com.yalin.fidoclient.R; import com.yalin.fidoclient.asm.api.ASMIntent; import com.yalin.fidoclient.msg.AsmInfo; import java.util.List; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;
/* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.ui.fragment; /** * Created by YaLin on 2016/2/26. */ public class AsmListFragment extends Fragment implements AsmListAdapter.ASMClickListener { public interface AsmItemPickListener {
// Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/api/ASMIntent.java // public class ASMIntent { // public static final String MESSAGE_KEY = "message"; // // public static Intent getASMIntent(){ // Intent intent = new Intent(Constants.ACTION_FIDO_OPERATION); // intent.setType(Constants.FIDO_ASM_INTENT_MIME); // // return intent; // } // // public static Intent getASMOperationIntent(String asmRequest) { // Intent intent = new Intent(Constants.ACTION_FIDO_OPERATION); // intent.setType(Constants.FIDO_ASM_INTENT_MIME); // // Bundle bundle = new Bundle(); // bundle.putString(MESSAGE_KEY, asmRequest); // intent.putExtras(bundle); // return intent; // } // // public static Intent getASMOperationResultIntent(String asmResponse) { // Intent intent = new Intent(); // // Bundle bundle = new Bundle(); // bundle.putString(MESSAGE_KEY, asmResponse); // intent.putExtras(bundle); // return intent; // } // } // // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/AsmInfo.java // public class AsmInfo { // public String appName; // public String pack; // public Drawable icon; // // public AsmInfo appName(String appName) { // this.appName = appName; // return this; // } // // public AsmInfo pack(String pack) { // this.pack = pack; // return this; // } // // public AsmInfo icon(Drawable icon) { // this.icon = icon; // return this; // } // } // Path: fidoclient/src/main/java/com/yalin/fidoclient/ui/fragment/AsmListFragment.java import com.yalin.fidoclient.R; import com.yalin.fidoclient.asm.api.ASMIntent; import com.yalin.fidoclient.msg.AsmInfo; import java.util.List; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /* * Copyright 2016 YaLin Jin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yalin.fidoclient.ui.fragment; /** * Created by YaLin on 2016/2/26. */ public class AsmListFragment extends Fragment implements AsmListAdapter.ASMClickListener { public interface AsmItemPickListener {
void onAsmItemPick(AsmInfo info);
jinkg/UAFClient
fidoclient/src/main/java/com/yalin/fidoclient/ui/fragment/AsmListFragment.java
// Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/api/ASMIntent.java // public class ASMIntent { // public static final String MESSAGE_KEY = "message"; // // public static Intent getASMIntent(){ // Intent intent = new Intent(Constants.ACTION_FIDO_OPERATION); // intent.setType(Constants.FIDO_ASM_INTENT_MIME); // // return intent; // } // // public static Intent getASMOperationIntent(String asmRequest) { // Intent intent = new Intent(Constants.ACTION_FIDO_OPERATION); // intent.setType(Constants.FIDO_ASM_INTENT_MIME); // // Bundle bundle = new Bundle(); // bundle.putString(MESSAGE_KEY, asmRequest); // intent.putExtras(bundle); // return intent; // } // // public static Intent getASMOperationResultIntent(String asmResponse) { // Intent intent = new Intent(); // // Bundle bundle = new Bundle(); // bundle.putString(MESSAGE_KEY, asmResponse); // intent.putExtras(bundle); // return intent; // } // } // // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/AsmInfo.java // public class AsmInfo { // public String appName; // public String pack; // public Drawable icon; // // public AsmInfo appName(String appName) { // this.appName = appName; // return this; // } // // public AsmInfo pack(String pack) { // this.pack = pack; // return this; // } // // public AsmInfo icon(Drawable icon) { // this.icon = icon; // return this; // } // }
import com.yalin.fidoclient.R; import com.yalin.fidoclient.asm.api.ASMIntent; import com.yalin.fidoclient.msg.AsmInfo; import java.util.List; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;
return fragment; } public static void open(int container, FragmentManager manager, AsmItemPickListener listener) { if (manager.findFragmentByTag(TAG) != null) { return; } manager.beginTransaction() .add(container, getInstance(listener), TAG) .addToBackStack(null) .commit(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_asm_list, container, false); findView(view); initData(); return view; } private void findView(View view) { tvAsmListPrompt = (TextView) view.findViewById(R.id.tv_asm_list_prompt); rvAsmList = (RecyclerView) view.findViewById(R.id.rv_asm_list); rvAsmList.setLayoutManager(new LinearLayoutManager(getActivity())); } private void initData() {
// Path: fidoclient/src/main/java/com/yalin/fidoclient/asm/api/ASMIntent.java // public class ASMIntent { // public static final String MESSAGE_KEY = "message"; // // public static Intent getASMIntent(){ // Intent intent = new Intent(Constants.ACTION_FIDO_OPERATION); // intent.setType(Constants.FIDO_ASM_INTENT_MIME); // // return intent; // } // // public static Intent getASMOperationIntent(String asmRequest) { // Intent intent = new Intent(Constants.ACTION_FIDO_OPERATION); // intent.setType(Constants.FIDO_ASM_INTENT_MIME); // // Bundle bundle = new Bundle(); // bundle.putString(MESSAGE_KEY, asmRequest); // intent.putExtras(bundle); // return intent; // } // // public static Intent getASMOperationResultIntent(String asmResponse) { // Intent intent = new Intent(); // // Bundle bundle = new Bundle(); // bundle.putString(MESSAGE_KEY, asmResponse); // intent.putExtras(bundle); // return intent; // } // } // // Path: fidoclient/src/main/java/com/yalin/fidoclient/msg/AsmInfo.java // public class AsmInfo { // public String appName; // public String pack; // public Drawable icon; // // public AsmInfo appName(String appName) { // this.appName = appName; // return this; // } // // public AsmInfo pack(String pack) { // this.pack = pack; // return this; // } // // public AsmInfo icon(Drawable icon) { // this.icon = icon; // return this; // } // } // Path: fidoclient/src/main/java/com/yalin/fidoclient/ui/fragment/AsmListFragment.java import com.yalin.fidoclient.R; import com.yalin.fidoclient.asm.api.ASMIntent; import com.yalin.fidoclient.msg.AsmInfo; import java.util.List; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; return fragment; } public static void open(int container, FragmentManager manager, AsmItemPickListener listener) { if (manager.findFragmentByTag(TAG) != null) { return; } manager.beginTransaction() .add(container, getInstance(listener), TAG) .addToBackStack(null) .commit(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_asm_list, container, false); findView(view); initData(); return view; } private void findView(View view) { tvAsmListPrompt = (TextView) view.findViewById(R.id.tv_asm_list_prompt); rvAsmList = (RecyclerView) view.findViewById(R.id.rv_asm_list); rvAsmList.setLayoutManager(new LinearLayoutManager(getActivity())); } private void initData() {
Intent intent = ASMIntent.getASMIntent();
kinabalu/mysticpaste
web/src/main/java/com/mysticcoders/mysticpaste/web/components/highlighter/HighlighterPanel.java
// Path: web/src/main/java/com/mysticcoders/mysticpaste/model/LanguageSyntax.java // public class LanguageSyntax implements Serializable { // private static final long serialVersionUID = 1L; // // private String language; // private String name; // private String script; // // public LanguageSyntax(String language, String name, String script) { // this.language = language; // this.name = name; // this.script = script; // } // // public String getLanguage() { // return language; // } // // public String getName() { // return name; // } // // public String getScript() { // return script; // } // }
import com.mysticcoders.mysticpaste.model.LanguageSyntax; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.core.util.string.JavaScriptUtils; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.head.CssHeaderItem; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.request.IRequestHandler; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler; import org.apache.wicket.request.resource.CssResourceReference; import org.apache.wicket.request.resource.PackageResourceReference; import org.apache.wicket.request.resource.ResourceReference; import java.util.ArrayList; import java.util.List;
package com.mysticcoders.mysticpaste.web.components.highlighter; /** * HighlighterTextAreaPanel * <p/> * Created by: Andrew Lombardi * Copyright 2006 Mystic Coders, LLC */ public class HighlighterPanel extends Panel { private static final long serialVersionUID = 1L;
// Path: web/src/main/java/com/mysticcoders/mysticpaste/model/LanguageSyntax.java // public class LanguageSyntax implements Serializable { // private static final long serialVersionUID = 1L; // // private String language; // private String name; // private String script; // // public LanguageSyntax(String language, String name, String script) { // this.language = language; // this.name = name; // this.script = script; // } // // public String getLanguage() { // return language; // } // // public String getName() { // return name; // } // // public String getScript() { // return script; // } // } // Path: web/src/main/java/com/mysticcoders/mysticpaste/web/components/highlighter/HighlighterPanel.java import com.mysticcoders.mysticpaste.model.LanguageSyntax; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.core.util.string.JavaScriptUtils; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.head.CssHeaderItem; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.request.IRequestHandler; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler; import org.apache.wicket.request.resource.CssResourceReference; import org.apache.wicket.request.resource.PackageResourceReference; import org.apache.wicket.request.resource.ResourceReference; import java.util.ArrayList; import java.util.List; package com.mysticcoders.mysticpaste.web.components.highlighter; /** * HighlighterTextAreaPanel * <p/> * Created by: Andrew Lombardi * Copyright 2006 Mystic Coders, LLC */ public class HighlighterPanel extends Panel { private static final long serialVersionUID = 1L;
private static List<LanguageSyntax> types
kinabalu/mysticpaste
web/src/test/java/com/mysticcoders/mocks/AbstractMockTestCase.java
// Path: web/src/main/java/com/mysticcoders/mysticpaste/persistence/PasteItemDao.java // public interface PasteItemDao { // // String create(PasteItem item); // // PasteItem get(String id); // // List<PasteItem> find(int count, int startIndex, String filter); // // long count(); // // int incViewCount(PasteItem pasteItem); // // void increaseAbuseCount(PasteItem pasteItem); // // void decreaseAbuseCount(PasteItem pasteItem); // // List<PasteItem> getChildren(PasteItem pasteItem); // // String getAdminPassword(); // // void appendIpAddress(String ipAddress); // } // // Path: web/src/main/java/com/mysticcoders/mysticpaste/services/PasteService.java // public interface PasteService { // // List<PasteItem> getLatestItems(int count, int startIndex); // // List<PasteItem> getLatestItems(int count, int startIndex, String filter); // // PasteItem getItem(String id); // // String createItem(PasteItem item); // // String createItem(PasteItem item, boolean twitter); // // String createReplyItem(PasteItem item, String parentId) // throws ParentNotFoundException; // // long getLatestItemsCount(); // // int incViewCount(PasteItem pasteItem); // // void increaseAbuseCount(PasteItem pasteItem); // // void decreaseAbuseCount(PasteItem pasteItem); // // List<PasteItem> hasChildren(PasteItem pasteItem); // // String getAdminPassword(); // // void appendIpAddress(String ipAddress); // }
import com.mysticcoders.mysticpaste.persistence.PasteItemDao; import com.mysticcoders.mysticpaste.services.PasteService; import static org.easymock.EasyMock.createMock; import org.junit.Before;
package com.mysticcoders.mocks; /** * Copyright 2006 Mystic Coders, LLC * * @author: joed * Date : Mar 6, 2009 */ public abstract class AbstractMockTestCase { private PasteItemDao pasteItemDao;
// Path: web/src/main/java/com/mysticcoders/mysticpaste/persistence/PasteItemDao.java // public interface PasteItemDao { // // String create(PasteItem item); // // PasteItem get(String id); // // List<PasteItem> find(int count, int startIndex, String filter); // // long count(); // // int incViewCount(PasteItem pasteItem); // // void increaseAbuseCount(PasteItem pasteItem); // // void decreaseAbuseCount(PasteItem pasteItem); // // List<PasteItem> getChildren(PasteItem pasteItem); // // String getAdminPassword(); // // void appendIpAddress(String ipAddress); // } // // Path: web/src/main/java/com/mysticcoders/mysticpaste/services/PasteService.java // public interface PasteService { // // List<PasteItem> getLatestItems(int count, int startIndex); // // List<PasteItem> getLatestItems(int count, int startIndex, String filter); // // PasteItem getItem(String id); // // String createItem(PasteItem item); // // String createItem(PasteItem item, boolean twitter); // // String createReplyItem(PasteItem item, String parentId) // throws ParentNotFoundException; // // long getLatestItemsCount(); // // int incViewCount(PasteItem pasteItem); // // void increaseAbuseCount(PasteItem pasteItem); // // void decreaseAbuseCount(PasteItem pasteItem); // // List<PasteItem> hasChildren(PasteItem pasteItem); // // String getAdminPassword(); // // void appendIpAddress(String ipAddress); // } // Path: web/src/test/java/com/mysticcoders/mocks/AbstractMockTestCase.java import com.mysticcoders.mysticpaste.persistence.PasteItemDao; import com.mysticcoders.mysticpaste.services.PasteService; import static org.easymock.EasyMock.createMock; import org.junit.Before; package com.mysticcoders.mocks; /** * Copyright 2006 Mystic Coders, LLC * * @author: joed * Date : Mar 6, 2009 */ public abstract class AbstractMockTestCase { private PasteItemDao pasteItemDao;
private PasteService pasteService;
kinabalu/mysticpaste
web/src/main/java/com/mysticcoders/mysticpaste/web/pages/Footer.java
// Path: web/src/main/java/com/mysticcoders/mysticpaste/web/components/google/TagExternalLink.java // public class TagExternalLink extends ExternalLink { // // private String prefix = "/outbound/"; // private String suffix = ""; // // public TagExternalLink(String id, String href, String label) { // super(id, href, label); // } // // public TagExternalLink(String id, String href) { // super(id, href); // } // // public TagExternalLink(String id, IModel<String> href, IModel<String> label) { // super(id, href, label); // } // // public TagExternalLink(String id, IModel<String> href) { // super(id, href); // } // // /** // * Returns the prefix to place in the pageTracker tagging url // * // * @return prefix of the external link // */ // protected String getPrefix() { // return prefix; // } // // /** // * Returns the suffix to place after the pageTracker tagging url // * // * @return suffix of the external link // */ // protected String getSuffix() { // return suffix; // } // // /** // * Processes and adds the Google Tracking code to our external link // * // * @param tag // * Tag to modify // * @see org.apache.wicket.Component#onComponentTag(org.apache.wicket.markup.ComponentTag) // */ // @Override // protected void onComponentTag(final ComponentTag tag) { // super.onComponentTag(tag); // // Object hrefValue = getDefaultModelObject(); // // StringBuffer pageTrackerCode = new StringBuffer("pageTracker._trackPageView('"); // pageTrackerCode.append(getPrefix()); // pageTrackerCode.append(hrefValue); // pageTrackerCode.append(getSuffix()); // pageTrackerCode.append("');"); // // pageTrackerCode.append(tag.getAttribute("onclick") != null ? tag.getAttribute("onclick") : ""); // // tag.put("onclick", pageTrackerCode.toString()); // } // }
import com.mysticcoders.mysticpaste.web.components.google.TagExternalLink; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.AbstractReadOnlyModel; import java.util.Calendar;
package com.mysticcoders.mysticpaste.web.pages; /** * Created with IntelliJ IDEA. * User: kinabalu * Date: 11/11/12 * Time: 1:50 PM * To change this template use File | Settings | File Templates. */ public class Footer extends Panel { /** * Construct. * * @param markupId The components markup id. */ public Footer(String markupId) { super(markupId); AbstractReadOnlyModel<String> dateModel = new AbstractReadOnlyModel<String>() { public String getObject() { Calendar cal = Calendar.getInstance(); return "" + cal.get(Calendar.YEAR); } }; add(new Label("latestYear", dateModel)); add(new ExternalLink("sourceLink", "http://github.com/kinabalu/mysticpaste/"));
// Path: web/src/main/java/com/mysticcoders/mysticpaste/web/components/google/TagExternalLink.java // public class TagExternalLink extends ExternalLink { // // private String prefix = "/outbound/"; // private String suffix = ""; // // public TagExternalLink(String id, String href, String label) { // super(id, href, label); // } // // public TagExternalLink(String id, String href) { // super(id, href); // } // // public TagExternalLink(String id, IModel<String> href, IModel<String> label) { // super(id, href, label); // } // // public TagExternalLink(String id, IModel<String> href) { // super(id, href); // } // // /** // * Returns the prefix to place in the pageTracker tagging url // * // * @return prefix of the external link // */ // protected String getPrefix() { // return prefix; // } // // /** // * Returns the suffix to place after the pageTracker tagging url // * // * @return suffix of the external link // */ // protected String getSuffix() { // return suffix; // } // // /** // * Processes and adds the Google Tracking code to our external link // * // * @param tag // * Tag to modify // * @see org.apache.wicket.Component#onComponentTag(org.apache.wicket.markup.ComponentTag) // */ // @Override // protected void onComponentTag(final ComponentTag tag) { // super.onComponentTag(tag); // // Object hrefValue = getDefaultModelObject(); // // StringBuffer pageTrackerCode = new StringBuffer("pageTracker._trackPageView('"); // pageTrackerCode.append(getPrefix()); // pageTrackerCode.append(hrefValue); // pageTrackerCode.append(getSuffix()); // pageTrackerCode.append("');"); // // pageTrackerCode.append(tag.getAttribute("onclick") != null ? tag.getAttribute("onclick") : ""); // // tag.put("onclick", pageTrackerCode.toString()); // } // } // Path: web/src/main/java/com/mysticcoders/mysticpaste/web/pages/Footer.java import com.mysticcoders.mysticpaste.web.components.google.TagExternalLink; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.AbstractReadOnlyModel; import java.util.Calendar; package com.mysticcoders.mysticpaste.web.pages; /** * Created with IntelliJ IDEA. * User: kinabalu * Date: 11/11/12 * Time: 1:50 PM * To change this template use File | Settings | File Templates. */ public class Footer extends Panel { /** * Construct. * * @param markupId The components markup id. */ public Footer(String markupId) { super(markupId); AbstractReadOnlyModel<String> dateModel = new AbstractReadOnlyModel<String>() { public String getObject() { Calendar cal = Calendar.getInstance(); return "" + cal.get(Calendar.YEAR); } }; add(new Label("latestYear", dateModel)); add(new ExternalLink("sourceLink", "http://github.com/kinabalu/mysticpaste/"));
add(new TagExternalLink("blogLink", "http://www.mysticcoders.com/blog"));
kinabalu/mysticpaste
web/src/test/java/com/mysticcoders/webapp/TestHomePage.java
// Path: web/src/test/java/com/mysticcoders/integrations/AbstractIntegrationTest.java // @SpringApplicationContext({"/applicationContext.xml", "applicationContext-test.xml"}) // public abstract class AbstractIntegrationTest extends UnitilsJUnit4 { // // // private ApplicationContext applicationContext; // // } // // Path: web/src/main/java/com/mysticcoders/mysticpaste/persistence/PasteItemDao.java // public interface PasteItemDao { // // String create(PasteItem item); // // PasteItem get(String id); // // List<PasteItem> find(int count, int startIndex, String filter); // // long count(); // // int incViewCount(PasteItem pasteItem); // // void increaseAbuseCount(PasteItem pasteItem); // // void decreaseAbuseCount(PasteItem pasteItem); // // List<PasteItem> getChildren(PasteItem pasteItem); // // String getAdminPassword(); // // void appendIpAddress(String ipAddress); // } // // Path: web/src/main/java/com/mysticcoders/mysticpaste/services/PasteService.java // public interface PasteService { // // List<PasteItem> getLatestItems(int count, int startIndex); // // List<PasteItem> getLatestItems(int count, int startIndex, String filter); // // PasteItem getItem(String id); // // String createItem(PasteItem item); // // String createItem(PasteItem item, boolean twitter); // // String createReplyItem(PasteItem item, String parentId) // throws ParentNotFoundException; // // long getLatestItemsCount(); // // int incViewCount(PasteItem pasteItem); // // void increaseAbuseCount(PasteItem pasteItem); // // void decreaseAbuseCount(PasteItem pasteItem); // // List<PasteItem> hasChildren(PasteItem pasteItem); // // String getAdminPassword(); // // void appendIpAddress(String ipAddress); // }
import com.mysticcoders.integrations.AbstractIntegrationTest; import com.mysticcoders.mysticpaste.persistence.PasteItemDao; import com.mysticcoders.mysticpaste.services.PasteService; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.spring.test.ApplicationContextMock; import org.apache.wicket.util.tester.WicketTester; import org.junit.Before; import org.junit.Test; import org.unitils.spring.annotation.SpringBeanByType;
package com.mysticcoders.webapp; /** * Simple test using the WicketTester */ public class TestHomePage extends AbstractIntegrationTest { @SpringBeanByType
// Path: web/src/test/java/com/mysticcoders/integrations/AbstractIntegrationTest.java // @SpringApplicationContext({"/applicationContext.xml", "applicationContext-test.xml"}) // public abstract class AbstractIntegrationTest extends UnitilsJUnit4 { // // // private ApplicationContext applicationContext; // // } // // Path: web/src/main/java/com/mysticcoders/mysticpaste/persistence/PasteItemDao.java // public interface PasteItemDao { // // String create(PasteItem item); // // PasteItem get(String id); // // List<PasteItem> find(int count, int startIndex, String filter); // // long count(); // // int incViewCount(PasteItem pasteItem); // // void increaseAbuseCount(PasteItem pasteItem); // // void decreaseAbuseCount(PasteItem pasteItem); // // List<PasteItem> getChildren(PasteItem pasteItem); // // String getAdminPassword(); // // void appendIpAddress(String ipAddress); // } // // Path: web/src/main/java/com/mysticcoders/mysticpaste/services/PasteService.java // public interface PasteService { // // List<PasteItem> getLatestItems(int count, int startIndex); // // List<PasteItem> getLatestItems(int count, int startIndex, String filter); // // PasteItem getItem(String id); // // String createItem(PasteItem item); // // String createItem(PasteItem item, boolean twitter); // // String createReplyItem(PasteItem item, String parentId) // throws ParentNotFoundException; // // long getLatestItemsCount(); // // int incViewCount(PasteItem pasteItem); // // void increaseAbuseCount(PasteItem pasteItem); // // void decreaseAbuseCount(PasteItem pasteItem); // // List<PasteItem> hasChildren(PasteItem pasteItem); // // String getAdminPassword(); // // void appendIpAddress(String ipAddress); // } // Path: web/src/test/java/com/mysticcoders/webapp/TestHomePage.java import com.mysticcoders.integrations.AbstractIntegrationTest; import com.mysticcoders.mysticpaste.persistence.PasteItemDao; import com.mysticcoders.mysticpaste.services.PasteService; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.spring.test.ApplicationContextMock; import org.apache.wicket.util.tester.WicketTester; import org.junit.Before; import org.junit.Test; import org.unitils.spring.annotation.SpringBeanByType; package com.mysticcoders.webapp; /** * Simple test using the WicketTester */ public class TestHomePage extends AbstractIntegrationTest { @SpringBeanByType
private PasteService svc;
kinabalu/mysticpaste
web/src/test/java/com/mysticcoders/webapp/TestHomePage.java
// Path: web/src/test/java/com/mysticcoders/integrations/AbstractIntegrationTest.java // @SpringApplicationContext({"/applicationContext.xml", "applicationContext-test.xml"}) // public abstract class AbstractIntegrationTest extends UnitilsJUnit4 { // // // private ApplicationContext applicationContext; // // } // // Path: web/src/main/java/com/mysticcoders/mysticpaste/persistence/PasteItemDao.java // public interface PasteItemDao { // // String create(PasteItem item); // // PasteItem get(String id); // // List<PasteItem> find(int count, int startIndex, String filter); // // long count(); // // int incViewCount(PasteItem pasteItem); // // void increaseAbuseCount(PasteItem pasteItem); // // void decreaseAbuseCount(PasteItem pasteItem); // // List<PasteItem> getChildren(PasteItem pasteItem); // // String getAdminPassword(); // // void appendIpAddress(String ipAddress); // } // // Path: web/src/main/java/com/mysticcoders/mysticpaste/services/PasteService.java // public interface PasteService { // // List<PasteItem> getLatestItems(int count, int startIndex); // // List<PasteItem> getLatestItems(int count, int startIndex, String filter); // // PasteItem getItem(String id); // // String createItem(PasteItem item); // // String createItem(PasteItem item, boolean twitter); // // String createReplyItem(PasteItem item, String parentId) // throws ParentNotFoundException; // // long getLatestItemsCount(); // // int incViewCount(PasteItem pasteItem); // // void increaseAbuseCount(PasteItem pasteItem); // // void decreaseAbuseCount(PasteItem pasteItem); // // List<PasteItem> hasChildren(PasteItem pasteItem); // // String getAdminPassword(); // // void appendIpAddress(String ipAddress); // }
import com.mysticcoders.integrations.AbstractIntegrationTest; import com.mysticcoders.mysticpaste.persistence.PasteItemDao; import com.mysticcoders.mysticpaste.services.PasteService; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.spring.test.ApplicationContextMock; import org.apache.wicket.util.tester.WicketTester; import org.junit.Before; import org.junit.Test; import org.unitils.spring.annotation.SpringBeanByType;
package com.mysticcoders.webapp; /** * Simple test using the WicketTester */ public class TestHomePage extends AbstractIntegrationTest { @SpringBeanByType private PasteService svc; @SpringBeanByType
// Path: web/src/test/java/com/mysticcoders/integrations/AbstractIntegrationTest.java // @SpringApplicationContext({"/applicationContext.xml", "applicationContext-test.xml"}) // public abstract class AbstractIntegrationTest extends UnitilsJUnit4 { // // // private ApplicationContext applicationContext; // // } // // Path: web/src/main/java/com/mysticcoders/mysticpaste/persistence/PasteItemDao.java // public interface PasteItemDao { // // String create(PasteItem item); // // PasteItem get(String id); // // List<PasteItem> find(int count, int startIndex, String filter); // // long count(); // // int incViewCount(PasteItem pasteItem); // // void increaseAbuseCount(PasteItem pasteItem); // // void decreaseAbuseCount(PasteItem pasteItem); // // List<PasteItem> getChildren(PasteItem pasteItem); // // String getAdminPassword(); // // void appendIpAddress(String ipAddress); // } // // Path: web/src/main/java/com/mysticcoders/mysticpaste/services/PasteService.java // public interface PasteService { // // List<PasteItem> getLatestItems(int count, int startIndex); // // List<PasteItem> getLatestItems(int count, int startIndex, String filter); // // PasteItem getItem(String id); // // String createItem(PasteItem item); // // String createItem(PasteItem item, boolean twitter); // // String createReplyItem(PasteItem item, String parentId) // throws ParentNotFoundException; // // long getLatestItemsCount(); // // int incViewCount(PasteItem pasteItem); // // void increaseAbuseCount(PasteItem pasteItem); // // void decreaseAbuseCount(PasteItem pasteItem); // // List<PasteItem> hasChildren(PasteItem pasteItem); // // String getAdminPassword(); // // void appendIpAddress(String ipAddress); // } // Path: web/src/test/java/com/mysticcoders/webapp/TestHomePage.java import com.mysticcoders.integrations.AbstractIntegrationTest; import com.mysticcoders.mysticpaste.persistence.PasteItemDao; import com.mysticcoders.mysticpaste.services.PasteService; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.spring.test.ApplicationContextMock; import org.apache.wicket.util.tester.WicketTester; import org.junit.Before; import org.junit.Test; import org.unitils.spring.annotation.SpringBeanByType; package com.mysticcoders.webapp; /** * Simple test using the WicketTester */ public class TestHomePage extends AbstractIntegrationTest { @SpringBeanByType private PasteService svc; @SpringBeanByType
private PasteItemDao dao;
TangXiaoLv/TelegramGallery
telegramgallery/src/main/java/com/tangxiaolv/telegramgallery/Utils/AndroidUtilities.java
// Path: telegramgallery/src/main/java/com/tangxiaolv/telegramgallery/Gallery.java // public class Gallery { // // public volatile static Application applicationContext; // public volatile static Handler applicationHandler; // // public static void init(Application application) { // if (applicationContext == null) { // applicationContext = application; // applicationHandler = new Handler(application.getMainLooper()); // } // } // }
import android.annotation.SuppressLint; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Color; import android.graphics.Point; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.util.DisplayMetrics; import android.util.Log; import android.util.StateSet; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.EdgeEffect; import android.widget.ListView; import android.widget.Toast; import com.tangxiaolv.telegramgallery.Gallery; import com.tangxiaolv.telegramgallery.R; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Hashtable; import java.util.Locale; import java.util.regex.Pattern;
final String GOOD_IRI_CHAR = "a-zA-Z0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF"; final Pattern IP_ADDRESS = Pattern.compile( "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]" + "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]" + "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}" + "|[1-9][0-9]|[0-9]))"); final String IRI = "[" + GOOD_IRI_CHAR + "]([" + GOOD_IRI_CHAR + "\\-]{0,61}[" + GOOD_IRI_CHAR + "]){0,1}"; final String GOOD_GTLD_CHAR = "a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF"; final String GTLD = "[" + GOOD_GTLD_CHAR + "]{2,63}"; final String HOST_NAME = "(" + IRI + "\\.)+" + GTLD; final Pattern DOMAIN_NAME = Pattern.compile("(" + HOST_NAME + "|" + IP_ADDRESS + ")"); WEB_URL = Pattern.compile( "((?:(http|https|Http|Https):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)" + "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_" + "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?" + "(?:" + DOMAIN_NAME + ")" + "(?:\\:\\d{1,5})?)" // plus option port number + "(\\/(?:(?:[" + GOOD_IRI_CHAR + "\\;\\/\\?\\:\\@\\&\\=\\#\\~" // plus // option // query // params + "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?" + "(?:\\b|$)"); } catch (Exception e) { e.printStackTrace(); } } static {
// Path: telegramgallery/src/main/java/com/tangxiaolv/telegramgallery/Gallery.java // public class Gallery { // // public volatile static Application applicationContext; // public volatile static Handler applicationHandler; // // public static void init(Application application) { // if (applicationContext == null) { // applicationContext = application; // applicationHandler = new Handler(application.getMainLooper()); // } // } // } // Path: telegramgallery/src/main/java/com/tangxiaolv/telegramgallery/Utils/AndroidUtilities.java import android.annotation.SuppressLint; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Color; import android.graphics.Point; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.util.DisplayMetrics; import android.util.Log; import android.util.StateSet; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.EdgeEffect; import android.widget.ListView; import android.widget.Toast; import com.tangxiaolv.telegramgallery.Gallery; import com.tangxiaolv.telegramgallery.R; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Hashtable; import java.util.Locale; import java.util.regex.Pattern; final String GOOD_IRI_CHAR = "a-zA-Z0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF"; final Pattern IP_ADDRESS = Pattern.compile( "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]" + "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]" + "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}" + "|[1-9][0-9]|[0-9]))"); final String IRI = "[" + GOOD_IRI_CHAR + "]([" + GOOD_IRI_CHAR + "\\-]{0,61}[" + GOOD_IRI_CHAR + "]){0,1}"; final String GOOD_GTLD_CHAR = "a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF"; final String GTLD = "[" + GOOD_GTLD_CHAR + "]{2,63}"; final String HOST_NAME = "(" + IRI + "\\.)+" + GTLD; final Pattern DOMAIN_NAME = Pattern.compile("(" + HOST_NAME + "|" + IP_ADDRESS + ")"); WEB_URL = Pattern.compile( "((?:(http|https|Http|Https):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)" + "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_" + "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?" + "(?:" + DOMAIN_NAME + ")" + "(?:\\:\\d{1,5})?)" // plus option port number + "(\\/(?:(?:[" + GOOD_IRI_CHAR + "\\;\\/\\?\\:\\@\\&\\=\\#\\~" // plus // option // query // params + "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?" + "(?:\\b|$)"); } catch (Exception e) { e.printStackTrace(); } } static {
density = Gallery.applicationContext.getResources().getDisplayMetrics().density;
TangXiaoLv/TelegramGallery
telegramgallery/src/main/java/com/tangxiaolv/telegramgallery/Actionbar/BaseFragment.java
// Path: telegramgallery/src/main/java/com/tangxiaolv/telegramgallery/Theme.java // public class Theme { // // public static final int ACTION_BAR_COLOR = 0xff527da3; // public static final int ACTION_BAR_PHOTO_VIEWER_COLOR = 0x7f000000; // public static final int ACTION_BAR_MEDIA_PICKER_COLOR = 0xff333333; // public static final int ACTION_BAR_SUBTITLE_COLOR = 0xffd5e8f7; // public static final int ACTION_BAR_SELECTOR_COLOR = 0xff406d94; // // public static final int ACTION_BAR_PICKER_SELECTOR_COLOR = 0xff3d3d3d; // public static final int ACTION_BAR_WHITE_SELECTOR_COLOR = 0x40ffffff; // public static final int ACTION_BAR_AUDIO_SELECTOR_COLOR = 0x2f000000; // public static final int ACTION_BAR_MODE_SELECTOR_COLOR = 0xfff0f0f0; // // private static Paint maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // // public static Drawable createBarSelectorDrawable(int color) { // return createBarSelectorDrawable(color, true); // } // // public static Drawable createBarSelectorDrawable(int color, boolean masked) { // if (Build.VERSION.SDK_INT >= 21) { // Drawable maskDrawable = null; // if (masked) { // maskPaint.setColor(0xffffffff); // maskDrawable = new Drawable() { // @Override // public void draw(Canvas canvas) { // android.graphics.Rect bounds = getBounds(); // canvas.drawCircle(bounds.centerX(), bounds.centerY(), // AndroidUtilities.dp(18), maskPaint); // } // // @Override // public void setAlpha(int alpha) { // // } // // @Override // public void setColorFilter(ColorFilter colorFilter) { // // } // // @Override // public int getOpacity() { // return 0; // } // }; // } // ColorStateList colorStateList = new ColorStateList( // new int[][] { // new int[] {} // }, // new int[] { // color // }); // return new RippleDrawable(colorStateList, null, maskDrawable); // } else { // StateListDrawable stateListDrawable = new StateListDrawable(); // stateListDrawable.addState(new int[] { // android.R.attr.state_pressed // }, new ColorDrawable(color)); // stateListDrawable.addState(new int[] { // android.R.attr.state_focused // }, new ColorDrawable(color)); // stateListDrawable.addState(new int[] { // android.R.attr.state_selected // }, new ColorDrawable(color)); // stateListDrawable.addState(new int[] { // android.R.attr.state_activated // }, new ColorDrawable(color)); // stateListDrawable.addState(new int[] {}, new ColorDrawable(0x00000000)); // return stateListDrawable; // } // } // }
import android.animation.AnimatorSet; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import com.tangxiaolv.telegramgallery.Theme;
} catch (Exception e) { e.printStackTrace(); } } if (parentLayout != null && parentLayout.getContext() != fragmentView.getContext()) { fragmentView = null; } } if (actionBar != null) { ViewGroup parent = (ViewGroup) actionBar.getParent(); if (parent != null) { try { parent.removeView(actionBar); } catch (Exception e) { e.printStackTrace(); } } if (parentLayout != null && parentLayout.getContext() != actionBar.getContext()) { actionBar = null; } } if (parentLayout != null && actionBar == null) { actionBar = createActionBar(parentLayout.getContext()); actionBar.parentFragment = this; } } } protected ActionBar createActionBar(Context context) { ActionBar actionBar = new ActionBar(context);
// Path: telegramgallery/src/main/java/com/tangxiaolv/telegramgallery/Theme.java // public class Theme { // // public static final int ACTION_BAR_COLOR = 0xff527da3; // public static final int ACTION_BAR_PHOTO_VIEWER_COLOR = 0x7f000000; // public static final int ACTION_BAR_MEDIA_PICKER_COLOR = 0xff333333; // public static final int ACTION_BAR_SUBTITLE_COLOR = 0xffd5e8f7; // public static final int ACTION_BAR_SELECTOR_COLOR = 0xff406d94; // // public static final int ACTION_BAR_PICKER_SELECTOR_COLOR = 0xff3d3d3d; // public static final int ACTION_BAR_WHITE_SELECTOR_COLOR = 0x40ffffff; // public static final int ACTION_BAR_AUDIO_SELECTOR_COLOR = 0x2f000000; // public static final int ACTION_BAR_MODE_SELECTOR_COLOR = 0xfff0f0f0; // // private static Paint maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // // public static Drawable createBarSelectorDrawable(int color) { // return createBarSelectorDrawable(color, true); // } // // public static Drawable createBarSelectorDrawable(int color, boolean masked) { // if (Build.VERSION.SDK_INT >= 21) { // Drawable maskDrawable = null; // if (masked) { // maskPaint.setColor(0xffffffff); // maskDrawable = new Drawable() { // @Override // public void draw(Canvas canvas) { // android.graphics.Rect bounds = getBounds(); // canvas.drawCircle(bounds.centerX(), bounds.centerY(), // AndroidUtilities.dp(18), maskPaint); // } // // @Override // public void setAlpha(int alpha) { // // } // // @Override // public void setColorFilter(ColorFilter colorFilter) { // // } // // @Override // public int getOpacity() { // return 0; // } // }; // } // ColorStateList colorStateList = new ColorStateList( // new int[][] { // new int[] {} // }, // new int[] { // color // }); // return new RippleDrawable(colorStateList, null, maskDrawable); // } else { // StateListDrawable stateListDrawable = new StateListDrawable(); // stateListDrawable.addState(new int[] { // android.R.attr.state_pressed // }, new ColorDrawable(color)); // stateListDrawable.addState(new int[] { // android.R.attr.state_focused // }, new ColorDrawable(color)); // stateListDrawable.addState(new int[] { // android.R.attr.state_selected // }, new ColorDrawable(color)); // stateListDrawable.addState(new int[] { // android.R.attr.state_activated // }, new ColorDrawable(color)); // stateListDrawable.addState(new int[] {}, new ColorDrawable(0x00000000)); // return stateListDrawable; // } // } // } // Path: telegramgallery/src/main/java/com/tangxiaolv/telegramgallery/Actionbar/BaseFragment.java import android.animation.AnimatorSet; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import com.tangxiaolv.telegramgallery.Theme; } catch (Exception e) { e.printStackTrace(); } } if (parentLayout != null && parentLayout.getContext() != fragmentView.getContext()) { fragmentView = null; } } if (actionBar != null) { ViewGroup parent = (ViewGroup) actionBar.getParent(); if (parent != null) { try { parent.removeView(actionBar); } catch (Exception e) { e.printStackTrace(); } } if (parentLayout != null && parentLayout.getContext() != actionBar.getContext()) { actionBar = null; } } if (parentLayout != null && actionBar == null) { actionBar = createActionBar(parentLayout.getContext()); actionBar.parentFragment = this; } } } protected ActionBar createActionBar(Context context) { ActionBar actionBar = new ActionBar(context);
actionBar.setBackgroundColor(Theme.ACTION_BAR_COLOR);
TangXiaoLv/TelegramGallery
telegramgallery/src/main/java/com/tangxiaolv/telegramgallery/Utils/Utilities.java
// Path: telegramgallery/src/main/java/com/tangxiaolv/telegramgallery/DispatchQueue.java // public class DispatchQueue extends Thread { // // private volatile Handler handler = null; // private CountDownLatch syncLatch = new CountDownLatch(1); // // public DispatchQueue(final String threadName) { // setName(threadName); // start(); // } // // private void sendMessage(Message msg, int delay) { // try { // syncLatch.await(); // if (delay <= 0) { // handler.sendMessage(msg); // } else { // handler.sendMessageDelayed(msg, delay); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // // public void cancelRunnable(Runnable runnable) { // try { // syncLatch.await(); // handler.removeCallbacks(runnable); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public void postRunnable(Runnable runnable) { // postRunnable(runnable, 0); // } // // public void postRunnable(Runnable runnable, long delay) { // try { // syncLatch.await(); // if (delay <= 0) { // handler.post(runnable); // } else { // handler.postDelayed(runnable, delay); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // // public void cleanupQueue() { // try { // syncLatch.await(); // handler.removeCallbacksAndMessages(null); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void run() { // Looper.prepare(); // handler = new Handler(); // syncLatch.countDown(); // Looper.loop(); // } // }
import android.graphics.Bitmap; import com.tangxiaolv.telegramgallery.DispatchQueue; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.regex.Matcher; import java.util.regex.Pattern;
package com.tangxiaolv.telegramgallery.Utils; public class Utilities { public static Pattern pattern = Pattern.compile("[\\-0-9]+"); public static SecureRandom random = new SecureRandom();
// Path: telegramgallery/src/main/java/com/tangxiaolv/telegramgallery/DispatchQueue.java // public class DispatchQueue extends Thread { // // private volatile Handler handler = null; // private CountDownLatch syncLatch = new CountDownLatch(1); // // public DispatchQueue(final String threadName) { // setName(threadName); // start(); // } // // private void sendMessage(Message msg, int delay) { // try { // syncLatch.await(); // if (delay <= 0) { // handler.sendMessage(msg); // } else { // handler.sendMessageDelayed(msg, delay); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // // public void cancelRunnable(Runnable runnable) { // try { // syncLatch.await(); // handler.removeCallbacks(runnable); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public void postRunnable(Runnable runnable) { // postRunnable(runnable, 0); // } // // public void postRunnable(Runnable runnable, long delay) { // try { // syncLatch.await(); // if (delay <= 0) { // handler.post(runnable); // } else { // handler.postDelayed(runnable, delay); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // // public void cleanupQueue() { // try { // syncLatch.await(); // handler.removeCallbacksAndMessages(null); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void run() { // Looper.prepare(); // handler = new Handler(); // syncLatch.countDown(); // Looper.loop(); // } // } // Path: telegramgallery/src/main/java/com/tangxiaolv/telegramgallery/Utils/Utilities.java import android.graphics.Bitmap; import com.tangxiaolv.telegramgallery.DispatchQueue; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.regex.Matcher; import java.util.regex.Pattern; package com.tangxiaolv.telegramgallery.Utils; public class Utilities { public static Pattern pattern = Pattern.compile("[\\-0-9]+"); public static SecureRandom random = new SecureRandom();
public static volatile DispatchQueue stageQueue = new DispatchQueue("stageQueue");
nicbet/MailboxMiner
MailboxMiner2/src/main/java/ca/queensu/cs/sail/mailboxmina2/parsetools/ParseDateHelper.java
// Path: MailboxMiner2/src/main/java/ca/queensu/cs/sail/mailboxmina2/main/Main.java // public class Main { // private static Logger logger; // /** // * @param args // */ // public static void main(String[] args) { // // // Read command line arguments as specified in CLICreateDatabase Class // CLIMain cli = new CLIMain(); // try { // Args.parse(cli, args); // } catch (Exception e) { // System.err.println("Error while parsing command line arguments: " + e.getMessage()); // Args.usage(cli); // System.exit(1); // } // // if (cli.debug) // logger = new Logger(true); // else // logger = new Logger(false); // // // logger.setMaxDebugLevel(Integer.parseInt(cli.loglevel)); // // FileOutputStream logfileStream=null; // if (cli.logfile != null) { // try { // logfileStream = new FileOutputStream(cli.logfile, false); // Default: append to logfile ;-) // PrintStream logPrintStream = new PrintStream(logfileStream); // // logger.setDebugStream(logPrintStream); // logger.setErrorStream(logPrintStream); // logger.setLogStream(logPrintStream); // // } catch (IOException e) { // logger.error("Could not use logfile " + cli.logfile + " for logging!", e); // } // } // // if (cli.module.equalsIgnoreCase("insert")) { // System.out.println("Running insertion module..."); // // run the insertion module // // // Properties insertProps = new Properties(); // insertProps.setProperty("db_url", cli.connection); // insertProps.setProperty("username", cli.username); // insertProps.setProperty("password", cli.password); // insertProps.setProperty("path", cli.path); // // IModule insertModule = new InsertModule(cli.testonly); // boolean success = insertModule.run(insertProps, logger); // // if (success) // System.out.println("InsertModule finished successfully!"); // else // System.out.println("There were errors while running the insert module!"); // // } else if (cli.module.equalsIgnoreCase("threads")) { // // run the threads module // System.out.println("Running threads module..."); // // Properties threadsProps = new Properties(); // threadsProps.setProperty("db_url", cli.connection); // threadsProps.setProperty("username", cli.username); // threadsProps.setProperty("password", cli.password); // threadsProps.setProperty("path", cli.path); // // IModule threadsModule = new ThreadsModule(); // boolean success = threadsModule.run(threadsProps, logger); // // if (success) // System.out.println("ThreadsModule finished successfully!"); // else // System.out.println("There were errors while running the threads module!"); // // } else if (cli.module.equalsIgnoreCase("clean")) { // // run the cleanup module // // } else if (cli.module.equalsIgnoreCase("create")) { // CreateDatabase.main(args); // } else if (cli.module.equalsIgnoreCase("persons")) { // IModule personsModule = new PersonalitiesModule(); // // Properties personsProps = new Properties(); // personsProps.setProperty("db_url", cli.connection); // personsProps.setProperty("username", cli.username); // personsProps.setProperty("password", cli.password); // personsProps.setProperty("path", cli.path); // // boolean success = personsModule.run(personsProps, logger); // // if (success) // System.out.println("PersonalitiesModule finished successfully!"); // else // System.out.println("There were errors while running the personalities module!"); // // }else { // System.out.println("Invalid module specified!"); // System.out.println("Available Modules:\n" + // "insert insert messages inside the mbox file into the database.\n" + // "threads re-create messages threads using the information in the database.\n" + // "clean clean up message bodies (remove quotes and signatures)." + // "persons merge multiple personalitites in the database"); // } // // if (cli.logfile != null && logfileStream != null) { // try { // logfileStream.close(); // } catch (IOException e) { // logger.error("Could not close logfile's stream " + cli.logfile, e); // } // } // // } // // public static Logger getLogger() { // if (logger == null) // logger = new Logger(true); // // return logger; // } // // }
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; import javax.mail.Message; import javax.mail.MessagingException; import ca.queensu.cs.sail.mailboxmina2.main.Main;
/******************************************************************************* * Copyright (c) 2012 Nicolas Bettenburg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Nicolas Bettenburg - initial API and implementation ******************************************************************************/ package ca.queensu.cs.sail.mailboxmina2.parsetools; public class ParseDateHelper { public static Date getDateFromMessage(Message message, Connection con) { Date result = null; try { if (hasHeader("Date", message)) { Date msg_date = message.getSentDate(); // If Java Mail could not parse the date ... if (msg_date == null) { // see if the postgresql server can infer the date ... String datestr = message.getHeader("Date")[0];
// Path: MailboxMiner2/src/main/java/ca/queensu/cs/sail/mailboxmina2/main/Main.java // public class Main { // private static Logger logger; // /** // * @param args // */ // public static void main(String[] args) { // // // Read command line arguments as specified in CLICreateDatabase Class // CLIMain cli = new CLIMain(); // try { // Args.parse(cli, args); // } catch (Exception e) { // System.err.println("Error while parsing command line arguments: " + e.getMessage()); // Args.usage(cli); // System.exit(1); // } // // if (cli.debug) // logger = new Logger(true); // else // logger = new Logger(false); // // // logger.setMaxDebugLevel(Integer.parseInt(cli.loglevel)); // // FileOutputStream logfileStream=null; // if (cli.logfile != null) { // try { // logfileStream = new FileOutputStream(cli.logfile, false); // Default: append to logfile ;-) // PrintStream logPrintStream = new PrintStream(logfileStream); // // logger.setDebugStream(logPrintStream); // logger.setErrorStream(logPrintStream); // logger.setLogStream(logPrintStream); // // } catch (IOException e) { // logger.error("Could not use logfile " + cli.logfile + " for logging!", e); // } // } // // if (cli.module.equalsIgnoreCase("insert")) { // System.out.println("Running insertion module..."); // // run the insertion module // // // Properties insertProps = new Properties(); // insertProps.setProperty("db_url", cli.connection); // insertProps.setProperty("username", cli.username); // insertProps.setProperty("password", cli.password); // insertProps.setProperty("path", cli.path); // // IModule insertModule = new InsertModule(cli.testonly); // boolean success = insertModule.run(insertProps, logger); // // if (success) // System.out.println("InsertModule finished successfully!"); // else // System.out.println("There were errors while running the insert module!"); // // } else if (cli.module.equalsIgnoreCase("threads")) { // // run the threads module // System.out.println("Running threads module..."); // // Properties threadsProps = new Properties(); // threadsProps.setProperty("db_url", cli.connection); // threadsProps.setProperty("username", cli.username); // threadsProps.setProperty("password", cli.password); // threadsProps.setProperty("path", cli.path); // // IModule threadsModule = new ThreadsModule(); // boolean success = threadsModule.run(threadsProps, logger); // // if (success) // System.out.println("ThreadsModule finished successfully!"); // else // System.out.println("There were errors while running the threads module!"); // // } else if (cli.module.equalsIgnoreCase("clean")) { // // run the cleanup module // // } else if (cli.module.equalsIgnoreCase("create")) { // CreateDatabase.main(args); // } else if (cli.module.equalsIgnoreCase("persons")) { // IModule personsModule = new PersonalitiesModule(); // // Properties personsProps = new Properties(); // personsProps.setProperty("db_url", cli.connection); // personsProps.setProperty("username", cli.username); // personsProps.setProperty("password", cli.password); // personsProps.setProperty("path", cli.path); // // boolean success = personsModule.run(personsProps, logger); // // if (success) // System.out.println("PersonalitiesModule finished successfully!"); // else // System.out.println("There were errors while running the personalities module!"); // // }else { // System.out.println("Invalid module specified!"); // System.out.println("Available Modules:\n" + // "insert insert messages inside the mbox file into the database.\n" + // "threads re-create messages threads using the information in the database.\n" + // "clean clean up message bodies (remove quotes and signatures)." + // "persons merge multiple personalitites in the database"); // } // // if (cli.logfile != null && logfileStream != null) { // try { // logfileStream.close(); // } catch (IOException e) { // logger.error("Could not close logfile's stream " + cli.logfile, e); // } // } // // } // // public static Logger getLogger() { // if (logger == null) // logger = new Logger(true); // // return logger; // } // // } // Path: MailboxMiner2/src/main/java/ca/queensu/cs/sail/mailboxmina2/parsetools/ParseDateHelper.java import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; import javax.mail.Message; import javax.mail.MessagingException; import ca.queensu.cs.sail.mailboxmina2.main.Main; /******************************************************************************* * Copyright (c) 2012 Nicolas Bettenburg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Nicolas Bettenburg - initial API and implementation ******************************************************************************/ package ca.queensu.cs.sail.mailboxmina2.parsetools; public class ParseDateHelper { public static Date getDateFromMessage(Message message, Connection con) { Date result = null; try { if (hasHeader("Date", message)) { Date msg_date = message.getSentDate(); // If Java Mail could not parse the date ... if (msg_date == null) { // see if the postgresql server can infer the date ... String datestr = message.getHeader("Date")[0];
Main.getLogger().debug(2,"Invalid Message date supplied - letting Postgresql guess: " + datestr);
nicbet/MailboxMiner
MailboxMiner2/src/main/java/ca/queensu/cs/sail/mailboxmina2/common/Attachment.java
// Path: MailboxMiner2/src/main/java/ca/queensu/cs/sail/mailboxmina2/main/Main.java // public class Main { // private static Logger logger; // /** // * @param args // */ // public static void main(String[] args) { // // // Read command line arguments as specified in CLICreateDatabase Class // CLIMain cli = new CLIMain(); // try { // Args.parse(cli, args); // } catch (Exception e) { // System.err.println("Error while parsing command line arguments: " + e.getMessage()); // Args.usage(cli); // System.exit(1); // } // // if (cli.debug) // logger = new Logger(true); // else // logger = new Logger(false); // // // logger.setMaxDebugLevel(Integer.parseInt(cli.loglevel)); // // FileOutputStream logfileStream=null; // if (cli.logfile != null) { // try { // logfileStream = new FileOutputStream(cli.logfile, false); // Default: append to logfile ;-) // PrintStream logPrintStream = new PrintStream(logfileStream); // // logger.setDebugStream(logPrintStream); // logger.setErrorStream(logPrintStream); // logger.setLogStream(logPrintStream); // // } catch (IOException e) { // logger.error("Could not use logfile " + cli.logfile + " for logging!", e); // } // } // // if (cli.module.equalsIgnoreCase("insert")) { // System.out.println("Running insertion module..."); // // run the insertion module // // // Properties insertProps = new Properties(); // insertProps.setProperty("db_url", cli.connection); // insertProps.setProperty("username", cli.username); // insertProps.setProperty("password", cli.password); // insertProps.setProperty("path", cli.path); // // IModule insertModule = new InsertModule(cli.testonly); // boolean success = insertModule.run(insertProps, logger); // // if (success) // System.out.println("InsertModule finished successfully!"); // else // System.out.println("There were errors while running the insert module!"); // // } else if (cli.module.equalsIgnoreCase("threads")) { // // run the threads module // System.out.println("Running threads module..."); // // Properties threadsProps = new Properties(); // threadsProps.setProperty("db_url", cli.connection); // threadsProps.setProperty("username", cli.username); // threadsProps.setProperty("password", cli.password); // threadsProps.setProperty("path", cli.path); // // IModule threadsModule = new ThreadsModule(); // boolean success = threadsModule.run(threadsProps, logger); // // if (success) // System.out.println("ThreadsModule finished successfully!"); // else // System.out.println("There were errors while running the threads module!"); // // } else if (cli.module.equalsIgnoreCase("clean")) { // // run the cleanup module // // } else if (cli.module.equalsIgnoreCase("create")) { // CreateDatabase.main(args); // } else if (cli.module.equalsIgnoreCase("persons")) { // IModule personsModule = new PersonalitiesModule(); // // Properties personsProps = new Properties(); // personsProps.setProperty("db_url", cli.connection); // personsProps.setProperty("username", cli.username); // personsProps.setProperty("password", cli.password); // personsProps.setProperty("path", cli.path); // // boolean success = personsModule.run(personsProps, logger); // // if (success) // System.out.println("PersonalitiesModule finished successfully!"); // else // System.out.println("There were errors while running the personalities module!"); // // }else { // System.out.println("Invalid module specified!"); // System.out.println("Available Modules:\n" + // "insert insert messages inside the mbox file into the database.\n" + // "threads re-create messages threads using the information in the database.\n" + // "clean clean up message bodies (remove quotes and signatures)." + // "persons merge multiple personalitites in the database"); // } // // if (cli.logfile != null && logfileStream != null) { // try { // logfileStream.close(); // } catch (IOException e) { // logger.error("Could not close logfile's stream " + cli.logfile, e); // } // } // // } // // public static Logger getLogger() { // if (logger == null) // logger = new Logger(true); // // return logger; // } // // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import ca.queensu.cs.sail.mailboxmina2.main.Main;
/** * Getter method * @return a byte array containing the data of the file. */ public byte[] getData() { return data; } /** * Setter method * @param data a byte array representing the file's data. */ public void setData(byte[] data) { this.data = data; } /** * Compress the data contained in the attachment in the gzip format. * @return a byte array containing the gzip compressed data. */ public byte[] getZippedData () { try { ByteArrayOutputStream ba_out = new ByteArrayOutputStream(); java.util.zip.GZIPOutputStream zipStream = new java.util.zip.GZIPOutputStream(ba_out); zipStream.write(data, 0, data.length); zipStream.finish(); zipStream.close(); return ba_out.toByteArray(); } catch (IOException e) {
// Path: MailboxMiner2/src/main/java/ca/queensu/cs/sail/mailboxmina2/main/Main.java // public class Main { // private static Logger logger; // /** // * @param args // */ // public static void main(String[] args) { // // // Read command line arguments as specified in CLICreateDatabase Class // CLIMain cli = new CLIMain(); // try { // Args.parse(cli, args); // } catch (Exception e) { // System.err.println("Error while parsing command line arguments: " + e.getMessage()); // Args.usage(cli); // System.exit(1); // } // // if (cli.debug) // logger = new Logger(true); // else // logger = new Logger(false); // // // logger.setMaxDebugLevel(Integer.parseInt(cli.loglevel)); // // FileOutputStream logfileStream=null; // if (cli.logfile != null) { // try { // logfileStream = new FileOutputStream(cli.logfile, false); // Default: append to logfile ;-) // PrintStream logPrintStream = new PrintStream(logfileStream); // // logger.setDebugStream(logPrintStream); // logger.setErrorStream(logPrintStream); // logger.setLogStream(logPrintStream); // // } catch (IOException e) { // logger.error("Could not use logfile " + cli.logfile + " for logging!", e); // } // } // // if (cli.module.equalsIgnoreCase("insert")) { // System.out.println("Running insertion module..."); // // run the insertion module // // // Properties insertProps = new Properties(); // insertProps.setProperty("db_url", cli.connection); // insertProps.setProperty("username", cli.username); // insertProps.setProperty("password", cli.password); // insertProps.setProperty("path", cli.path); // // IModule insertModule = new InsertModule(cli.testonly); // boolean success = insertModule.run(insertProps, logger); // // if (success) // System.out.println("InsertModule finished successfully!"); // else // System.out.println("There were errors while running the insert module!"); // // } else if (cli.module.equalsIgnoreCase("threads")) { // // run the threads module // System.out.println("Running threads module..."); // // Properties threadsProps = new Properties(); // threadsProps.setProperty("db_url", cli.connection); // threadsProps.setProperty("username", cli.username); // threadsProps.setProperty("password", cli.password); // threadsProps.setProperty("path", cli.path); // // IModule threadsModule = new ThreadsModule(); // boolean success = threadsModule.run(threadsProps, logger); // // if (success) // System.out.println("ThreadsModule finished successfully!"); // else // System.out.println("There were errors while running the threads module!"); // // } else if (cli.module.equalsIgnoreCase("clean")) { // // run the cleanup module // // } else if (cli.module.equalsIgnoreCase("create")) { // CreateDatabase.main(args); // } else if (cli.module.equalsIgnoreCase("persons")) { // IModule personsModule = new PersonalitiesModule(); // // Properties personsProps = new Properties(); // personsProps.setProperty("db_url", cli.connection); // personsProps.setProperty("username", cli.username); // personsProps.setProperty("password", cli.password); // personsProps.setProperty("path", cli.path); // // boolean success = personsModule.run(personsProps, logger); // // if (success) // System.out.println("PersonalitiesModule finished successfully!"); // else // System.out.println("There were errors while running the personalities module!"); // // }else { // System.out.println("Invalid module specified!"); // System.out.println("Available Modules:\n" + // "insert insert messages inside the mbox file into the database.\n" + // "threads re-create messages threads using the information in the database.\n" + // "clean clean up message bodies (remove quotes and signatures)." + // "persons merge multiple personalitites in the database"); // } // // if (cli.logfile != null && logfileStream != null) { // try { // logfileStream.close(); // } catch (IOException e) { // logger.error("Could not close logfile's stream " + cli.logfile, e); // } // } // // } // // public static Logger getLogger() { // if (logger == null) // logger = new Logger(true); // // return logger; // } // // } // Path: MailboxMiner2/src/main/java/ca/queensu/cs/sail/mailboxmina2/common/Attachment.java import java.io.ByteArrayOutputStream; import java.io.IOException; import ca.queensu.cs.sail.mailboxmina2.main.Main; /** * Getter method * @return a byte array containing the data of the file. */ public byte[] getData() { return data; } /** * Setter method * @param data a byte array representing the file's data. */ public void setData(byte[] data) { this.data = data; } /** * Compress the data contained in the attachment in the gzip format. * @return a byte array containing the gzip compressed data. */ public byte[] getZippedData () { try { ByteArrayOutputStream ba_out = new ByteArrayOutputStream(); java.util.zip.GZIPOutputStream zipStream = new java.util.zip.GZIPOutputStream(ba_out); zipStream.write(data, 0, data.length); zipStream.finish(); zipStream.close(); return ba_out.toByteArray(); } catch (IOException e) {
Main.getLogger().error("Unable to compress the attachment data!", e);
yassirh/digitalocean-swimmer
DigitalOceanSwimmer/src/main/java/com/yassirh/digitalocean/data/DatabaseHelper.java
// Path: DigitalOceanSwimmer/src/main/java/com/yassirh/digitalocean/utils/MyApplication.java // public class MyApplication extends Application{ // // private static Context context; // // public void onCreate(){ // super.onCreate(); // MyApplication.context = getApplicationContext(); // SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); // // Configuration config = getBaseContext().getResources().getConfiguration(); // // String lang = settings.getString("pref_locale", ""); // if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang)) // { // locale = new Locale(lang); // Locale.setDefault(locale); // config.locale = locale; // getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); // } // } // // public static Context getAppContext() { // return MyApplication.context; // } // // private Locale locale = null; // // @Override // public void onConfigurationChanged(Configuration newConfig) // { // super.onConfigurationChanged(newConfig); // if (locale != null) // { // newConfig.locale = locale; // Locale.setDefault(locale); // getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics()); // } // } // // }
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.yassirh.digitalocean.utils.MyApplication;
package com.yassirh.digitalocean.data; public class DatabaseHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 17; private static final String DATABASE_NAME = "digital_ocean"; private TableHelper imageTable = new ImageTable(); private TableHelper regionTable = new RegionTable(); private TableHelper sizeTable = new SizeTable(); private TableHelper domainTable = new DomainTable(); private TableHelper dropletTable = new DropletTable(); private TableHelper recordTable = new RecordTable(); private TableHelper sshKeyTable = new SSHKeyTable(); private TableHelper accountTable = new AccountTable(); private TableHelper networkTable = new NetworkTable(); private TableHelper floatingIPTable = new FloatingIPTable(); static DatabaseHelper sDatabaseHelper; private Context context; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context; } public static DatabaseHelper getInstance(Context context) { if (sDatabaseHelper == null) { sDatabaseHelper = new DatabaseHelper(context); } return sDatabaseHelper; } public static SQLiteDatabase getWritableDatabaseInstance() { if (sDatabaseHelper == null) {
// Path: DigitalOceanSwimmer/src/main/java/com/yassirh/digitalocean/utils/MyApplication.java // public class MyApplication extends Application{ // // private static Context context; // // public void onCreate(){ // super.onCreate(); // MyApplication.context = getApplicationContext(); // SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); // // Configuration config = getBaseContext().getResources().getConfiguration(); // // String lang = settings.getString("pref_locale", ""); // if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang)) // { // locale = new Locale(lang); // Locale.setDefault(locale); // config.locale = locale; // getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); // } // } // // public static Context getAppContext() { // return MyApplication.context; // } // // private Locale locale = null; // // @Override // public void onConfigurationChanged(Configuration newConfig) // { // super.onConfigurationChanged(newConfig); // if (locale != null) // { // newConfig.locale = locale; // Locale.setDefault(locale); // getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics()); // } // } // // } // Path: DigitalOceanSwimmer/src/main/java/com/yassirh/digitalocean/data/DatabaseHelper.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.yassirh.digitalocean.utils.MyApplication; package com.yassirh.digitalocean.data; public class DatabaseHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 17; private static final String DATABASE_NAME = "digital_ocean"; private TableHelper imageTable = new ImageTable(); private TableHelper regionTable = new RegionTable(); private TableHelper sizeTable = new SizeTable(); private TableHelper domainTable = new DomainTable(); private TableHelper dropletTable = new DropletTable(); private TableHelper recordTable = new RecordTable(); private TableHelper sshKeyTable = new SSHKeyTable(); private TableHelper accountTable = new AccountTable(); private TableHelper networkTable = new NetworkTable(); private TableHelper floatingIPTable = new FloatingIPTable(); static DatabaseHelper sDatabaseHelper; private Context context; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context; } public static DatabaseHelper getInstance(Context context) { if (sDatabaseHelper == null) { sDatabaseHelper = new DatabaseHelper(context); } return sDatabaseHelper; } public static SQLiteDatabase getWritableDatabaseInstance() { if (sDatabaseHelper == null) {
sDatabaseHelper = new DatabaseHelper(MyApplication.getAppContext());
RxBroadcast/RxBroadcast
src/main/java/rxbroadcast/CausalOrder.java
// Path: src/main/java/rxbroadcast/time/LamportClock.java // public final class LamportClock { // private final Lock lock; // // private long currentTime; // // LamportClock(final Lock lock) { // this.lock = lock; // } // // /** // * Creates an instance of {@code LamportClock}. // */ // public LamportClock() { // this(new ReentrantLock()); // } // // /** // * Returns the current clock timestamp. // * @return the current clock timestamp. // */ // public long time() { // lock.lock(); // try { // return currentTime; // } finally { // lock.unlock(); // } // } // // /** // * Updates this clock to account for the given incoming timestamp. // * // * If the given timestamp is larger than the current clock's time, // * the clock will set its timestamp to the given value, and the // * next timestamp generated by the instance will be {@code incoming + 1}. // * @param incoming the incoming timestamp // */ // public void set(final long incoming) { // lock.lock(); // try { // currentTime = incoming; // } finally { // lock.unlock(); // } // } // // public <T> T tick(@NotNull final LongFunction<T> ticker) { // lock.lock(); // try { // currentTime = currentTime + 1; // return ticker.apply(currentTime); // } finally { // lock.unlock(); // } // } // // public <T> T tick(@NotNull final Supplier<T> ticker) { // lock.lock(); // try { // currentTime = currentTime + 1; // return ticker.get(); // } finally { // lock.unlock(); // } // } // // @NotNull // @Override // public final String toString() { // lock.lock(); // try { // return String.format("LamportClock{currentTime=%d}", currentTime); // } finally { // lock.unlock(); // } // } // }
import rxbroadcast.time.LamportClock; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer;
package rxbroadcast; public final class CausalOrder<T> implements BroadcastOrder<VectorTimestamped<T>, T> { private final class DelayQueueEntry { final Sender sender; final VectorTimestamped<T> message; private DelayQueueEntry(final Sender sender, final VectorTimestamped<T> message) { this.sender = sender; this.message = message; } } private final Sender me;
// Path: src/main/java/rxbroadcast/time/LamportClock.java // public final class LamportClock { // private final Lock lock; // // private long currentTime; // // LamportClock(final Lock lock) { // this.lock = lock; // } // // /** // * Creates an instance of {@code LamportClock}. // */ // public LamportClock() { // this(new ReentrantLock()); // } // // /** // * Returns the current clock timestamp. // * @return the current clock timestamp. // */ // public long time() { // lock.lock(); // try { // return currentTime; // } finally { // lock.unlock(); // } // } // // /** // * Updates this clock to account for the given incoming timestamp. // * // * If the given timestamp is larger than the current clock's time, // * the clock will set its timestamp to the given value, and the // * next timestamp generated by the instance will be {@code incoming + 1}. // * @param incoming the incoming timestamp // */ // public void set(final long incoming) { // lock.lock(); // try { // currentTime = incoming; // } finally { // lock.unlock(); // } // } // // public <T> T tick(@NotNull final LongFunction<T> ticker) { // lock.lock(); // try { // currentTime = currentTime + 1; // return ticker.apply(currentTime); // } finally { // lock.unlock(); // } // } // // public <T> T tick(@NotNull final Supplier<T> ticker) { // lock.lock(); // try { // currentTime = currentTime + 1; // return ticker.get(); // } finally { // lock.unlock(); // } // } // // @NotNull // @Override // public final String toString() { // lock.lock(); // try { // return String.format("LamportClock{currentTime=%d}", currentTime); // } finally { // lock.unlock(); // } // } // } // Path: src/main/java/rxbroadcast/CausalOrder.java import rxbroadcast.time.LamportClock; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; package rxbroadcast; public final class CausalOrder<T> implements BroadcastOrder<VectorTimestamped<T>, T> { private final class DelayQueueEntry { final Sender sender; final VectorTimestamped<T> message; private DelayQueueEntry(final Sender sender, final VectorTimestamped<T> message) { this.sender = sender; this.message = message; } } private final Sender me;
private final Map<Sender, LamportClock> vt = new ConcurrentHashMap<>();
RxBroadcast/RxBroadcast
src/test/java/rxbroadcast/integration/pp/PingPongUdpNoOrder.java
// Path: src/main/java/rxbroadcast/Broadcast.java // public interface Broadcast { // /** // * Broadcasts the given value when the returned {@code Observable} is subscribed to. // * @param value the value to broadcast // * @return an Observable stream representing the message sent status // */ // @Contract(pure = true) // Observable<@NotNull Void> send(@NotNull Object value); // // /** // * Returns a (hot) {@code Observable} stream of broadcasted values. // * @param clazz the class type to filter the broadcasted values by // * @param <T> the output stream type // * @return an Observable stream of broadcasted values // */ // @Contract(pure = true) // <T> Observable<@NotNull T> valuesOfType(@NotNull Class<T> clazz); // } // // Path: src/main/java/rxbroadcast/NoOrder.java // public final class NoOrder<T> implements BroadcastOrder<T, T> { // /** // * {@inheritDoc} // */ // @Contract(pure = true) // @Override // public T prepare(final T value) { // return value; // } // // /** // * {@inheritDoc} // */ // @Override // public void receive(final Sender sender, final Consumer<T> consumer, final T message) { // consumer.accept(message); // } // } // // Path: src/main/java/rxbroadcast/UdpBroadcast.java // public final class UdpBroadcast<T> implements Broadcast { // private final DatagramSocket socket; // // private final Observable<Object> values; // // private final ConcurrentHashMap<Class<?>, Observable<?>> streams; // // private final Serializer<T> serializer; // // private final InetSocketAddress destination; // // private final Single<BroadcastOrder<T, Object>> broadcastOrder; // // @SuppressWarnings("WeakerAccess") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Serializer<T> serializer, // final Function<Sender, BroadcastOrder<T, Object>> createBroadcastOrder // ) { // this.socket = socket; // final Scheduler singleThreadScheduler = Schedulers.from( // Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory())); // final Single<Sender> host = Single.fromCallable(new WhoAmI( // socket.getLocalPort(), destination.getAddress() instanceof Inet6Address)); // this.broadcastOrder = host.subscribeOn(Schedulers.io()).map(createBroadcastOrder::apply).cache(); // this.broadcastOrder.subscribe(); // this.values = broadcastOrder.flatMapObservable((order1) -> // Observable.unsafeCreate(new UdpBroadcastOnSubscribe<>(socket, serializer, order1)) // .subscribeOn(singleThreadScheduler)) // .share(); // this.serializer = serializer; // this.streams = new ConcurrentHashMap<>(); // this.destination = destination; // } // // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Serializer<T> serializer, // final BroadcastOrder<T, Object> order // ) { // this(socket, destination, serializer, (host) -> order); // } // // @SuppressWarnings("unchecked") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final BroadcastOrder<T, Object> order // ) { // this(socket, destination, new KryoSerializer<>(), (host) -> order); // } // // @SuppressWarnings("unchecked") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Function<Sender, BroadcastOrder<T, Object>> createBroadcastOrder // ) { // this(socket, destination, new KryoSerializer<>(), createBroadcastOrder); // } // // @Override // public Observable<Void> send(@NotNull final Object value) { // return broadcastOrder.flatMapObservable((order) -> { // try { // final byte[] data = serializer.encode(order.prepare(value)); // final DatagramPacket packet = new DatagramPacket( // data, data.length, destination.getAddress(), destination.getPort()); // socket.send(packet); // return null; // } catch (final Exception e) { // return Observable.error(e); // } // }); // } // // @Override // @SuppressWarnings("unchecked") // public <V> Observable<@NotNull V> valuesOfType(@NotNull final Class<V> clazz) { // return (Observable<V>) streams.computeIfAbsent(clazz, k -> values.ofType(k).share()); // } // }
import rxbroadcast.Broadcast; import rxbroadcast.NoOrder; import rxbroadcast.UdpBroadcast; import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.concurrent.TimeUnit;
package rxbroadcast.integration.pp; @SuppressWarnings({"checkstyle:MagicNumber", "checkstyle:AvoidInlineConditionals"}) public final class PingPongUdpNoOrder { private static final int MESSAGE_COUNT = 100; private static final long TIMEOUT = 30; /** * Receive a PING and respond with a PONG. * @throws SocketException if the socket could not be opened, or the socket could not bind to the given port. * @throws UnknownHostException if no IP address for the host machine could be found. */ @Test public final void recv() throws SocketException, UnknownHostException { final int port = System.getProperty("port") != null ? Integer.parseInt(System.getProperty("port")) : 54321; final int destinationPort = System.getProperty("destinationPort") != null ? Integer.parseInt(System.getProperty("destinationPort")) : 12345; final InetAddress destination = System.getProperty("destination") != null ? InetAddress.getByName(System.getProperty("destination")) : InetAddress.getLoopbackAddress(); final InetSocketAddress destinationSocket = new InetSocketAddress(destination, destinationPort); final TestSubscriber<Ping> subscriber = new TestSubscriber<>(); try (final DatagramSocket socket = new DatagramSocket(port)) {
// Path: src/main/java/rxbroadcast/Broadcast.java // public interface Broadcast { // /** // * Broadcasts the given value when the returned {@code Observable} is subscribed to. // * @param value the value to broadcast // * @return an Observable stream representing the message sent status // */ // @Contract(pure = true) // Observable<@NotNull Void> send(@NotNull Object value); // // /** // * Returns a (hot) {@code Observable} stream of broadcasted values. // * @param clazz the class type to filter the broadcasted values by // * @param <T> the output stream type // * @return an Observable stream of broadcasted values // */ // @Contract(pure = true) // <T> Observable<@NotNull T> valuesOfType(@NotNull Class<T> clazz); // } // // Path: src/main/java/rxbroadcast/NoOrder.java // public final class NoOrder<T> implements BroadcastOrder<T, T> { // /** // * {@inheritDoc} // */ // @Contract(pure = true) // @Override // public T prepare(final T value) { // return value; // } // // /** // * {@inheritDoc} // */ // @Override // public void receive(final Sender sender, final Consumer<T> consumer, final T message) { // consumer.accept(message); // } // } // // Path: src/main/java/rxbroadcast/UdpBroadcast.java // public final class UdpBroadcast<T> implements Broadcast { // private final DatagramSocket socket; // // private final Observable<Object> values; // // private final ConcurrentHashMap<Class<?>, Observable<?>> streams; // // private final Serializer<T> serializer; // // private final InetSocketAddress destination; // // private final Single<BroadcastOrder<T, Object>> broadcastOrder; // // @SuppressWarnings("WeakerAccess") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Serializer<T> serializer, // final Function<Sender, BroadcastOrder<T, Object>> createBroadcastOrder // ) { // this.socket = socket; // final Scheduler singleThreadScheduler = Schedulers.from( // Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory())); // final Single<Sender> host = Single.fromCallable(new WhoAmI( // socket.getLocalPort(), destination.getAddress() instanceof Inet6Address)); // this.broadcastOrder = host.subscribeOn(Schedulers.io()).map(createBroadcastOrder::apply).cache(); // this.broadcastOrder.subscribe(); // this.values = broadcastOrder.flatMapObservable((order1) -> // Observable.unsafeCreate(new UdpBroadcastOnSubscribe<>(socket, serializer, order1)) // .subscribeOn(singleThreadScheduler)) // .share(); // this.serializer = serializer; // this.streams = new ConcurrentHashMap<>(); // this.destination = destination; // } // // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Serializer<T> serializer, // final BroadcastOrder<T, Object> order // ) { // this(socket, destination, serializer, (host) -> order); // } // // @SuppressWarnings("unchecked") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final BroadcastOrder<T, Object> order // ) { // this(socket, destination, new KryoSerializer<>(), (host) -> order); // } // // @SuppressWarnings("unchecked") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Function<Sender, BroadcastOrder<T, Object>> createBroadcastOrder // ) { // this(socket, destination, new KryoSerializer<>(), createBroadcastOrder); // } // // @Override // public Observable<Void> send(@NotNull final Object value) { // return broadcastOrder.flatMapObservable((order) -> { // try { // final byte[] data = serializer.encode(order.prepare(value)); // final DatagramPacket packet = new DatagramPacket( // data, data.length, destination.getAddress(), destination.getPort()); // socket.send(packet); // return null; // } catch (final Exception e) { // return Observable.error(e); // } // }); // } // // @Override // @SuppressWarnings("unchecked") // public <V> Observable<@NotNull V> valuesOfType(@NotNull final Class<V> clazz) { // return (Observable<V>) streams.computeIfAbsent(clazz, k -> values.ofType(k).share()); // } // } // Path: src/test/java/rxbroadcast/integration/pp/PingPongUdpNoOrder.java import rxbroadcast.Broadcast; import rxbroadcast.NoOrder; import rxbroadcast.UdpBroadcast; import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.concurrent.TimeUnit; package rxbroadcast.integration.pp; @SuppressWarnings({"checkstyle:MagicNumber", "checkstyle:AvoidInlineConditionals"}) public final class PingPongUdpNoOrder { private static final int MESSAGE_COUNT = 100; private static final long TIMEOUT = 30; /** * Receive a PING and respond with a PONG. * @throws SocketException if the socket could not be opened, or the socket could not bind to the given port. * @throws UnknownHostException if no IP address for the host machine could be found. */ @Test public final void recv() throws SocketException, UnknownHostException { final int port = System.getProperty("port") != null ? Integer.parseInt(System.getProperty("port")) : 54321; final int destinationPort = System.getProperty("destinationPort") != null ? Integer.parseInt(System.getProperty("destinationPort")) : 12345; final InetAddress destination = System.getProperty("destination") != null ? InetAddress.getByName(System.getProperty("destination")) : InetAddress.getLoopbackAddress(); final InetSocketAddress destinationSocket = new InetSocketAddress(destination, destinationPort); final TestSubscriber<Ping> subscriber = new TestSubscriber<>(); try (final DatagramSocket socket = new DatagramSocket(port)) {
final Broadcast broadcast = new UdpBroadcast<>(socket, destinationSocket, new NoOrder<>());
RxBroadcast/RxBroadcast
src/test/java/rxbroadcast/integration/pp/PingPongUdpNoOrder.java
// Path: src/main/java/rxbroadcast/Broadcast.java // public interface Broadcast { // /** // * Broadcasts the given value when the returned {@code Observable} is subscribed to. // * @param value the value to broadcast // * @return an Observable stream representing the message sent status // */ // @Contract(pure = true) // Observable<@NotNull Void> send(@NotNull Object value); // // /** // * Returns a (hot) {@code Observable} stream of broadcasted values. // * @param clazz the class type to filter the broadcasted values by // * @param <T> the output stream type // * @return an Observable stream of broadcasted values // */ // @Contract(pure = true) // <T> Observable<@NotNull T> valuesOfType(@NotNull Class<T> clazz); // } // // Path: src/main/java/rxbroadcast/NoOrder.java // public final class NoOrder<T> implements BroadcastOrder<T, T> { // /** // * {@inheritDoc} // */ // @Contract(pure = true) // @Override // public T prepare(final T value) { // return value; // } // // /** // * {@inheritDoc} // */ // @Override // public void receive(final Sender sender, final Consumer<T> consumer, final T message) { // consumer.accept(message); // } // } // // Path: src/main/java/rxbroadcast/UdpBroadcast.java // public final class UdpBroadcast<T> implements Broadcast { // private final DatagramSocket socket; // // private final Observable<Object> values; // // private final ConcurrentHashMap<Class<?>, Observable<?>> streams; // // private final Serializer<T> serializer; // // private final InetSocketAddress destination; // // private final Single<BroadcastOrder<T, Object>> broadcastOrder; // // @SuppressWarnings("WeakerAccess") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Serializer<T> serializer, // final Function<Sender, BroadcastOrder<T, Object>> createBroadcastOrder // ) { // this.socket = socket; // final Scheduler singleThreadScheduler = Schedulers.from( // Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory())); // final Single<Sender> host = Single.fromCallable(new WhoAmI( // socket.getLocalPort(), destination.getAddress() instanceof Inet6Address)); // this.broadcastOrder = host.subscribeOn(Schedulers.io()).map(createBroadcastOrder::apply).cache(); // this.broadcastOrder.subscribe(); // this.values = broadcastOrder.flatMapObservable((order1) -> // Observable.unsafeCreate(new UdpBroadcastOnSubscribe<>(socket, serializer, order1)) // .subscribeOn(singleThreadScheduler)) // .share(); // this.serializer = serializer; // this.streams = new ConcurrentHashMap<>(); // this.destination = destination; // } // // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Serializer<T> serializer, // final BroadcastOrder<T, Object> order // ) { // this(socket, destination, serializer, (host) -> order); // } // // @SuppressWarnings("unchecked") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final BroadcastOrder<T, Object> order // ) { // this(socket, destination, new KryoSerializer<>(), (host) -> order); // } // // @SuppressWarnings("unchecked") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Function<Sender, BroadcastOrder<T, Object>> createBroadcastOrder // ) { // this(socket, destination, new KryoSerializer<>(), createBroadcastOrder); // } // // @Override // public Observable<Void> send(@NotNull final Object value) { // return broadcastOrder.flatMapObservable((order) -> { // try { // final byte[] data = serializer.encode(order.prepare(value)); // final DatagramPacket packet = new DatagramPacket( // data, data.length, destination.getAddress(), destination.getPort()); // socket.send(packet); // return null; // } catch (final Exception e) { // return Observable.error(e); // } // }); // } // // @Override // @SuppressWarnings("unchecked") // public <V> Observable<@NotNull V> valuesOfType(@NotNull final Class<V> clazz) { // return (Observable<V>) streams.computeIfAbsent(clazz, k -> values.ofType(k).share()); // } // }
import rxbroadcast.Broadcast; import rxbroadcast.NoOrder; import rxbroadcast.UdpBroadcast; import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.concurrent.TimeUnit;
package rxbroadcast.integration.pp; @SuppressWarnings({"checkstyle:MagicNumber", "checkstyle:AvoidInlineConditionals"}) public final class PingPongUdpNoOrder { private static final int MESSAGE_COUNT = 100; private static final long TIMEOUT = 30; /** * Receive a PING and respond with a PONG. * @throws SocketException if the socket could not be opened, or the socket could not bind to the given port. * @throws UnknownHostException if no IP address for the host machine could be found. */ @Test public final void recv() throws SocketException, UnknownHostException { final int port = System.getProperty("port") != null ? Integer.parseInt(System.getProperty("port")) : 54321; final int destinationPort = System.getProperty("destinationPort") != null ? Integer.parseInt(System.getProperty("destinationPort")) : 12345; final InetAddress destination = System.getProperty("destination") != null ? InetAddress.getByName(System.getProperty("destination")) : InetAddress.getLoopbackAddress(); final InetSocketAddress destinationSocket = new InetSocketAddress(destination, destinationPort); final TestSubscriber<Ping> subscriber = new TestSubscriber<>(); try (final DatagramSocket socket = new DatagramSocket(port)) {
// Path: src/main/java/rxbroadcast/Broadcast.java // public interface Broadcast { // /** // * Broadcasts the given value when the returned {@code Observable} is subscribed to. // * @param value the value to broadcast // * @return an Observable stream representing the message sent status // */ // @Contract(pure = true) // Observable<@NotNull Void> send(@NotNull Object value); // // /** // * Returns a (hot) {@code Observable} stream of broadcasted values. // * @param clazz the class type to filter the broadcasted values by // * @param <T> the output stream type // * @return an Observable stream of broadcasted values // */ // @Contract(pure = true) // <T> Observable<@NotNull T> valuesOfType(@NotNull Class<T> clazz); // } // // Path: src/main/java/rxbroadcast/NoOrder.java // public final class NoOrder<T> implements BroadcastOrder<T, T> { // /** // * {@inheritDoc} // */ // @Contract(pure = true) // @Override // public T prepare(final T value) { // return value; // } // // /** // * {@inheritDoc} // */ // @Override // public void receive(final Sender sender, final Consumer<T> consumer, final T message) { // consumer.accept(message); // } // } // // Path: src/main/java/rxbroadcast/UdpBroadcast.java // public final class UdpBroadcast<T> implements Broadcast { // private final DatagramSocket socket; // // private final Observable<Object> values; // // private final ConcurrentHashMap<Class<?>, Observable<?>> streams; // // private final Serializer<T> serializer; // // private final InetSocketAddress destination; // // private final Single<BroadcastOrder<T, Object>> broadcastOrder; // // @SuppressWarnings("WeakerAccess") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Serializer<T> serializer, // final Function<Sender, BroadcastOrder<T, Object>> createBroadcastOrder // ) { // this.socket = socket; // final Scheduler singleThreadScheduler = Schedulers.from( // Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory())); // final Single<Sender> host = Single.fromCallable(new WhoAmI( // socket.getLocalPort(), destination.getAddress() instanceof Inet6Address)); // this.broadcastOrder = host.subscribeOn(Schedulers.io()).map(createBroadcastOrder::apply).cache(); // this.broadcastOrder.subscribe(); // this.values = broadcastOrder.flatMapObservable((order1) -> // Observable.unsafeCreate(new UdpBroadcastOnSubscribe<>(socket, serializer, order1)) // .subscribeOn(singleThreadScheduler)) // .share(); // this.serializer = serializer; // this.streams = new ConcurrentHashMap<>(); // this.destination = destination; // } // // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Serializer<T> serializer, // final BroadcastOrder<T, Object> order // ) { // this(socket, destination, serializer, (host) -> order); // } // // @SuppressWarnings("unchecked") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final BroadcastOrder<T, Object> order // ) { // this(socket, destination, new KryoSerializer<>(), (host) -> order); // } // // @SuppressWarnings("unchecked") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Function<Sender, BroadcastOrder<T, Object>> createBroadcastOrder // ) { // this(socket, destination, new KryoSerializer<>(), createBroadcastOrder); // } // // @Override // public Observable<Void> send(@NotNull final Object value) { // return broadcastOrder.flatMapObservable((order) -> { // try { // final byte[] data = serializer.encode(order.prepare(value)); // final DatagramPacket packet = new DatagramPacket( // data, data.length, destination.getAddress(), destination.getPort()); // socket.send(packet); // return null; // } catch (final Exception e) { // return Observable.error(e); // } // }); // } // // @Override // @SuppressWarnings("unchecked") // public <V> Observable<@NotNull V> valuesOfType(@NotNull final Class<V> clazz) { // return (Observable<V>) streams.computeIfAbsent(clazz, k -> values.ofType(k).share()); // } // } // Path: src/test/java/rxbroadcast/integration/pp/PingPongUdpNoOrder.java import rxbroadcast.Broadcast; import rxbroadcast.NoOrder; import rxbroadcast.UdpBroadcast; import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.concurrent.TimeUnit; package rxbroadcast.integration.pp; @SuppressWarnings({"checkstyle:MagicNumber", "checkstyle:AvoidInlineConditionals"}) public final class PingPongUdpNoOrder { private static final int MESSAGE_COUNT = 100; private static final long TIMEOUT = 30; /** * Receive a PING and respond with a PONG. * @throws SocketException if the socket could not be opened, or the socket could not bind to the given port. * @throws UnknownHostException if no IP address for the host machine could be found. */ @Test public final void recv() throws SocketException, UnknownHostException { final int port = System.getProperty("port") != null ? Integer.parseInt(System.getProperty("port")) : 54321; final int destinationPort = System.getProperty("destinationPort") != null ? Integer.parseInt(System.getProperty("destinationPort")) : 12345; final InetAddress destination = System.getProperty("destination") != null ? InetAddress.getByName(System.getProperty("destination")) : InetAddress.getLoopbackAddress(); final InetSocketAddress destinationSocket = new InetSocketAddress(destination, destinationPort); final TestSubscriber<Ping> subscriber = new TestSubscriber<>(); try (final DatagramSocket socket = new DatagramSocket(port)) {
final Broadcast broadcast = new UdpBroadcast<>(socket, destinationSocket, new NoOrder<>());
RxBroadcast/RxBroadcast
src/test/java/rxbroadcast/integration/pp/PingPongUdpNoOrder.java
// Path: src/main/java/rxbroadcast/Broadcast.java // public interface Broadcast { // /** // * Broadcasts the given value when the returned {@code Observable} is subscribed to. // * @param value the value to broadcast // * @return an Observable stream representing the message sent status // */ // @Contract(pure = true) // Observable<@NotNull Void> send(@NotNull Object value); // // /** // * Returns a (hot) {@code Observable} stream of broadcasted values. // * @param clazz the class type to filter the broadcasted values by // * @param <T> the output stream type // * @return an Observable stream of broadcasted values // */ // @Contract(pure = true) // <T> Observable<@NotNull T> valuesOfType(@NotNull Class<T> clazz); // } // // Path: src/main/java/rxbroadcast/NoOrder.java // public final class NoOrder<T> implements BroadcastOrder<T, T> { // /** // * {@inheritDoc} // */ // @Contract(pure = true) // @Override // public T prepare(final T value) { // return value; // } // // /** // * {@inheritDoc} // */ // @Override // public void receive(final Sender sender, final Consumer<T> consumer, final T message) { // consumer.accept(message); // } // } // // Path: src/main/java/rxbroadcast/UdpBroadcast.java // public final class UdpBroadcast<T> implements Broadcast { // private final DatagramSocket socket; // // private final Observable<Object> values; // // private final ConcurrentHashMap<Class<?>, Observable<?>> streams; // // private final Serializer<T> serializer; // // private final InetSocketAddress destination; // // private final Single<BroadcastOrder<T, Object>> broadcastOrder; // // @SuppressWarnings("WeakerAccess") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Serializer<T> serializer, // final Function<Sender, BroadcastOrder<T, Object>> createBroadcastOrder // ) { // this.socket = socket; // final Scheduler singleThreadScheduler = Schedulers.from( // Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory())); // final Single<Sender> host = Single.fromCallable(new WhoAmI( // socket.getLocalPort(), destination.getAddress() instanceof Inet6Address)); // this.broadcastOrder = host.subscribeOn(Schedulers.io()).map(createBroadcastOrder::apply).cache(); // this.broadcastOrder.subscribe(); // this.values = broadcastOrder.flatMapObservable((order1) -> // Observable.unsafeCreate(new UdpBroadcastOnSubscribe<>(socket, serializer, order1)) // .subscribeOn(singleThreadScheduler)) // .share(); // this.serializer = serializer; // this.streams = new ConcurrentHashMap<>(); // this.destination = destination; // } // // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Serializer<T> serializer, // final BroadcastOrder<T, Object> order // ) { // this(socket, destination, serializer, (host) -> order); // } // // @SuppressWarnings("unchecked") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final BroadcastOrder<T, Object> order // ) { // this(socket, destination, new KryoSerializer<>(), (host) -> order); // } // // @SuppressWarnings("unchecked") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Function<Sender, BroadcastOrder<T, Object>> createBroadcastOrder // ) { // this(socket, destination, new KryoSerializer<>(), createBroadcastOrder); // } // // @Override // public Observable<Void> send(@NotNull final Object value) { // return broadcastOrder.flatMapObservable((order) -> { // try { // final byte[] data = serializer.encode(order.prepare(value)); // final DatagramPacket packet = new DatagramPacket( // data, data.length, destination.getAddress(), destination.getPort()); // socket.send(packet); // return null; // } catch (final Exception e) { // return Observable.error(e); // } // }); // } // // @Override // @SuppressWarnings("unchecked") // public <V> Observable<@NotNull V> valuesOfType(@NotNull final Class<V> clazz) { // return (Observable<V>) streams.computeIfAbsent(clazz, k -> values.ofType(k).share()); // } // }
import rxbroadcast.Broadcast; import rxbroadcast.NoOrder; import rxbroadcast.UdpBroadcast; import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.concurrent.TimeUnit;
package rxbroadcast.integration.pp; @SuppressWarnings({"checkstyle:MagicNumber", "checkstyle:AvoidInlineConditionals"}) public final class PingPongUdpNoOrder { private static final int MESSAGE_COUNT = 100; private static final long TIMEOUT = 30; /** * Receive a PING and respond with a PONG. * @throws SocketException if the socket could not be opened, or the socket could not bind to the given port. * @throws UnknownHostException if no IP address for the host machine could be found. */ @Test public final void recv() throws SocketException, UnknownHostException { final int port = System.getProperty("port") != null ? Integer.parseInt(System.getProperty("port")) : 54321; final int destinationPort = System.getProperty("destinationPort") != null ? Integer.parseInt(System.getProperty("destinationPort")) : 12345; final InetAddress destination = System.getProperty("destination") != null ? InetAddress.getByName(System.getProperty("destination")) : InetAddress.getLoopbackAddress(); final InetSocketAddress destinationSocket = new InetSocketAddress(destination, destinationPort); final TestSubscriber<Ping> subscriber = new TestSubscriber<>(); try (final DatagramSocket socket = new DatagramSocket(port)) {
// Path: src/main/java/rxbroadcast/Broadcast.java // public interface Broadcast { // /** // * Broadcasts the given value when the returned {@code Observable} is subscribed to. // * @param value the value to broadcast // * @return an Observable stream representing the message sent status // */ // @Contract(pure = true) // Observable<@NotNull Void> send(@NotNull Object value); // // /** // * Returns a (hot) {@code Observable} stream of broadcasted values. // * @param clazz the class type to filter the broadcasted values by // * @param <T> the output stream type // * @return an Observable stream of broadcasted values // */ // @Contract(pure = true) // <T> Observable<@NotNull T> valuesOfType(@NotNull Class<T> clazz); // } // // Path: src/main/java/rxbroadcast/NoOrder.java // public final class NoOrder<T> implements BroadcastOrder<T, T> { // /** // * {@inheritDoc} // */ // @Contract(pure = true) // @Override // public T prepare(final T value) { // return value; // } // // /** // * {@inheritDoc} // */ // @Override // public void receive(final Sender sender, final Consumer<T> consumer, final T message) { // consumer.accept(message); // } // } // // Path: src/main/java/rxbroadcast/UdpBroadcast.java // public final class UdpBroadcast<T> implements Broadcast { // private final DatagramSocket socket; // // private final Observable<Object> values; // // private final ConcurrentHashMap<Class<?>, Observable<?>> streams; // // private final Serializer<T> serializer; // // private final InetSocketAddress destination; // // private final Single<BroadcastOrder<T, Object>> broadcastOrder; // // @SuppressWarnings("WeakerAccess") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Serializer<T> serializer, // final Function<Sender, BroadcastOrder<T, Object>> createBroadcastOrder // ) { // this.socket = socket; // final Scheduler singleThreadScheduler = Schedulers.from( // Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory())); // final Single<Sender> host = Single.fromCallable(new WhoAmI( // socket.getLocalPort(), destination.getAddress() instanceof Inet6Address)); // this.broadcastOrder = host.subscribeOn(Schedulers.io()).map(createBroadcastOrder::apply).cache(); // this.broadcastOrder.subscribe(); // this.values = broadcastOrder.flatMapObservable((order1) -> // Observable.unsafeCreate(new UdpBroadcastOnSubscribe<>(socket, serializer, order1)) // .subscribeOn(singleThreadScheduler)) // .share(); // this.serializer = serializer; // this.streams = new ConcurrentHashMap<>(); // this.destination = destination; // } // // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Serializer<T> serializer, // final BroadcastOrder<T, Object> order // ) { // this(socket, destination, serializer, (host) -> order); // } // // @SuppressWarnings("unchecked") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final BroadcastOrder<T, Object> order // ) { // this(socket, destination, new KryoSerializer<>(), (host) -> order); // } // // @SuppressWarnings("unchecked") // public UdpBroadcast( // final DatagramSocket socket, // final InetSocketAddress destination, // final Function<Sender, BroadcastOrder<T, Object>> createBroadcastOrder // ) { // this(socket, destination, new KryoSerializer<>(), createBroadcastOrder); // } // // @Override // public Observable<Void> send(@NotNull final Object value) { // return broadcastOrder.flatMapObservable((order) -> { // try { // final byte[] data = serializer.encode(order.prepare(value)); // final DatagramPacket packet = new DatagramPacket( // data, data.length, destination.getAddress(), destination.getPort()); // socket.send(packet); // return null; // } catch (final Exception e) { // return Observable.error(e); // } // }); // } // // @Override // @SuppressWarnings("unchecked") // public <V> Observable<@NotNull V> valuesOfType(@NotNull final Class<V> clazz) { // return (Observable<V>) streams.computeIfAbsent(clazz, k -> values.ofType(k).share()); // } // } // Path: src/test/java/rxbroadcast/integration/pp/PingPongUdpNoOrder.java import rxbroadcast.Broadcast; import rxbroadcast.NoOrder; import rxbroadcast.UdpBroadcast; import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.concurrent.TimeUnit; package rxbroadcast.integration.pp; @SuppressWarnings({"checkstyle:MagicNumber", "checkstyle:AvoidInlineConditionals"}) public final class PingPongUdpNoOrder { private static final int MESSAGE_COUNT = 100; private static final long TIMEOUT = 30; /** * Receive a PING and respond with a PONG. * @throws SocketException if the socket could not be opened, or the socket could not bind to the given port. * @throws UnknownHostException if no IP address for the host machine could be found. */ @Test public final void recv() throws SocketException, UnknownHostException { final int port = System.getProperty("port") != null ? Integer.parseInt(System.getProperty("port")) : 54321; final int destinationPort = System.getProperty("destinationPort") != null ? Integer.parseInt(System.getProperty("destinationPort")) : 12345; final InetAddress destination = System.getProperty("destination") != null ? InetAddress.getByName(System.getProperty("destination")) : InetAddress.getLoopbackAddress(); final InetSocketAddress destinationSocket = new InetSocketAddress(destination, destinationPort); final TestSubscriber<Ping> subscriber = new TestSubscriber<>(); try (final DatagramSocket socket = new DatagramSocket(port)) {
final Broadcast broadcast = new UdpBroadcast<>(socket, destinationSocket, new NoOrder<>());
RxBroadcast/RxBroadcast
src/main/java/rxbroadcast/SingleSourceFifoOrder.java
// Path: src/main/java/rxbroadcast/time/LamportClock.java // public final class LamportClock { // private final Lock lock; // // private long currentTime; // // LamportClock(final Lock lock) { // this.lock = lock; // } // // /** // * Creates an instance of {@code LamportClock}. // */ // public LamportClock() { // this(new ReentrantLock()); // } // // /** // * Returns the current clock timestamp. // * @return the current clock timestamp. // */ // public long time() { // lock.lock(); // try { // return currentTime; // } finally { // lock.unlock(); // } // } // // /** // * Updates this clock to account for the given incoming timestamp. // * // * If the given timestamp is larger than the current clock's time, // * the clock will set its timestamp to the given value, and the // * next timestamp generated by the instance will be {@code incoming + 1}. // * @param incoming the incoming timestamp // */ // public void set(final long incoming) { // lock.lock(); // try { // currentTime = incoming; // } finally { // lock.unlock(); // } // } // // public <T> T tick(@NotNull final LongFunction<T> ticker) { // lock.lock(); // try { // currentTime = currentTime + 1; // return ticker.apply(currentTime); // } finally { // lock.unlock(); // } // } // // public <T> T tick(@NotNull final Supplier<T> ticker) { // lock.lock(); // try { // currentTime = currentTime + 1; // return ticker.get(); // } finally { // lock.unlock(); // } // } // // @NotNull // @Override // public final String toString() { // lock.lock(); // try { // return String.format("LamportClock{currentTime=%d}", currentTime); // } finally { // lock.unlock(); // } // } // }
import rxbroadcast.time.LamportClock; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import java.util.function.Consumer;
package rxbroadcast; public final class SingleSourceFifoOrder<T> implements BroadcastOrder<Timestamped<T>, T> { public enum SingleSourceFifoOrderQueueOption { DROP, QUEUE, } @SuppressWarnings("WeakerAccess") public static final SingleSourceFifoOrderQueueOption DROP_LATE = SingleSourceFifoOrderQueueOption.DROP;
// Path: src/main/java/rxbroadcast/time/LamportClock.java // public final class LamportClock { // private final Lock lock; // // private long currentTime; // // LamportClock(final Lock lock) { // this.lock = lock; // } // // /** // * Creates an instance of {@code LamportClock}. // */ // public LamportClock() { // this(new ReentrantLock()); // } // // /** // * Returns the current clock timestamp. // * @return the current clock timestamp. // */ // public long time() { // lock.lock(); // try { // return currentTime; // } finally { // lock.unlock(); // } // } // // /** // * Updates this clock to account for the given incoming timestamp. // * // * If the given timestamp is larger than the current clock's time, // * the clock will set its timestamp to the given value, and the // * next timestamp generated by the instance will be {@code incoming + 1}. // * @param incoming the incoming timestamp // */ // public void set(final long incoming) { // lock.lock(); // try { // currentTime = incoming; // } finally { // lock.unlock(); // } // } // // public <T> T tick(@NotNull final LongFunction<T> ticker) { // lock.lock(); // try { // currentTime = currentTime + 1; // return ticker.apply(currentTime); // } finally { // lock.unlock(); // } // } // // public <T> T tick(@NotNull final Supplier<T> ticker) { // lock.lock(); // try { // currentTime = currentTime + 1; // return ticker.get(); // } finally { // lock.unlock(); // } // } // // @NotNull // @Override // public final String toString() { // lock.lock(); // try { // return String.format("LamportClock{currentTime=%d}", currentTime); // } finally { // lock.unlock(); // } // } // } // Path: src/main/java/rxbroadcast/SingleSourceFifoOrder.java import rxbroadcast.time.LamportClock; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import java.util.function.Consumer; package rxbroadcast; public final class SingleSourceFifoOrder<T> implements BroadcastOrder<Timestamped<T>, T> { public enum SingleSourceFifoOrderQueueOption { DROP, QUEUE, } @SuppressWarnings("WeakerAccess") public static final SingleSourceFifoOrderQueueOption DROP_LATE = SingleSourceFifoOrderQueueOption.DROP;
private final LamportClock clock = new LamportClock();